<?php
// Instalador de Giftcards PRO
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $dbHost   = $_POST['db_host'] ?? 'localhost';
  $dbName   = $_POST['db_name'] ?? '';
  $dbUser   = $_POST['db_user'] ?? '';
  $dbPass   = $_POST['db_pass'] ?? '';

  $adminEmail = $_POST['admin_email'] ?? '';
  $adminPass  = $_POST['admin_pass'] ?? '';
  $business   = $_POST['business_name'] ?? 'Mi Negocio';

  $stripePub  = $_POST['stripe_public_key'] ?? '';
  $stripeSec  = $_POST['stripe_secret_key'] ?? '';

  $smtpHost   = $_POST['smtp_host'] ?? '';
  $smtpPort   = (int)($_POST['smtp_port'] ?? 587);
  $smtpUser   = $_POST['smtp_user'] ?? '';
  $smtpPass   = $_POST['smtp_pass'] ?? '';
  $smtpFrom   = $_POST['smtp_from_email'] ?? $adminEmail;
  $smtpFromNm = $_POST['smtp_from_name'] ?? $business;

  // Detectar BASE_URL (soporta raíz y subcarpeta)
  $scheme   = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $host     = $_SERVER['HTTP_HOST'] ?? 'localhost';
  $scriptDir= rtrim(str_replace('\\','/', dirname($_SERVER['SCRIPT_NAME'])), '/');
  $baseUrl  = $scheme . '://' . $host . ($scriptDir !== '/' ? $scriptDir : '') . '/';

  try {
    // Conectar a MySQL sin DB para poder crearla
    $pdo = new PDO("mysql:host=$dbHost;charset=utf8mb4", $dbUser, $dbPass, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    // Crear BD si no existe
    if ($dbName) {
      $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
      $pdo->exec("USE `$dbName`");
    } else {
      throw new Exception("Debes indicar un nombre de base de datos.");
    }

    // Crear tablas
    $schemaSql = <<<SQL

CREATE TABLE IF NOT EXISTS `amount_options` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `amount` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `is_active` tinyint(1) DEFAULT 1,
  `icon` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `amount_options` (`amount`, `title`, `description`, `is_active`, `icon`) VALUES
  (500,  'Limpieza básica', 'Ideal para piel joven o mantenimiento rápido.', 1, 'icons/limpieza.png'),
  (1000, 'Limpieza profunda', 'Elimina impurezas y mejora la textura.', 1, 'icons/limpieza_profunda.png'),
  (1500, 'Hidratación avanzada', 'Hidratación intensa con mascarilla premium.', 1, 'icons/hidratacion.png'),
  (2000, 'Anti-edad premium', 'Reafirma, reduce líneas de expresión y nutre la piel.', 1, 'icons/anti_edad.png'),
  (3000, 'Facial de lujo + masaje', 'Incluye limpieza, hidratación avanzada y masaje relajante.', 1, 'icons/lujo_masaje.png'),
  (5000, 'Paquete VIP rejuvenecedor', 'Tratamiento completo: anti-edad, hidratación y vitaminas.', 1, 'icons/vip.png');

CREATE TABLE IF NOT EXISTS `giftcards` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `recipient_name` varchar(100) DEFAULT NULL,
  `recipient_contact` varchar(100) DEFAULT NULL,
  `message` text DEFAULT NULL,
  `sender_name` varchar(100) DEFAULT NULL,
  `sender_email` varchar(100) DEFAULT NULL,
  `amount` decimal(10,2) DEFAULT NULL,
  `image_filename` varchar(255) DEFAULT NULL,
  `qr_payload` text DEFAULT NULL,
  `created_at` datetime DEFAULT current_timestamp(),
  `days_valid` int(11) DEFAULT 30,
  `days_remaining` int(11) DEFAULT 30,
  `is_valid` tinyint(1) DEFAULT 1,
  `code` varchar(100) DEFAULT NULL,
  `purchase_token` varchar(100) DEFAULT NULL,
  `stripe_session_id` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `email` varchar(150) NOT NULL UNIQUE,
  `password_hash` varchar(255) NOT NULL,
  `role` enum('admin','staff') DEFAULT 'admin',
  `is_active` tinyint(1) DEFAULT 1,
  `created_at` datetime DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `settings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `business_name` varchar(150) DEFAULT NULL,
  `base_url` varchar(255) DEFAULT NULL,
  `stripe_public_key` varchar(255) DEFAULT NULL,
  `stripe_secret_key` varchar(255) DEFAULT NULL,
  `smtp_host` varchar(255) DEFAULT NULL,
  `smtp_port` int(11) DEFAULT NULL,
  `smtp_user` varchar(255) DEFAULT NULL,
  `smtp_pass` varchar(255) DEFAULT NULL,
  `smtp_from_email` varchar(255) DEFAULT NULL,
  `smtp_from_name` varchar(255) DEFAULT NULL,
  `points_per_currency` decimal(10,2) DEFAULT 1.00,
  `currency_unit` varchar(10) DEFAULT 'MXN',
  `default_days_valid` int(11) DEFAULT 30,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(150) NOT NULL UNIQUE,
  `name` varchar(150) DEFAULT NULL,
  `total_spent` decimal(10,2) DEFAULT 0,
  `points_balance` int(11) DEFAULT 0,
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `points_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `giftcards_batch` varchar(100) DEFAULT NULL,
  `amount` decimal(10,2) DEFAULT 0,
  `points_added` int(11) DEFAULT 0,
  `description` varchar(255) DEFAULT NULL,
  `created_at` datetime DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `customer_id` (`customer_id`),
  CONSTRAINT `points_log_customer_fk` FOREIGN KEY (`customer_id`)
    REFERENCES `customers`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

SQL;

    foreach (explode(";", $schemaSql) as $sql) {
      $sql = trim($sql);
      if ($sql) {
        $pdo->exec($sql);
      }
    }

    // Insertar ajustes base
    $stmt = $pdo->prepare("INSERT INTO settings 
      (business_name, base_url, stripe_public_key, stripe_secret_key,
       smtp_host, smtp_port, smtp_user, smtp_pass, smtp_from_email, smtp_from_name)
      VALUES (?,?,?,?,?,?,?,?,?,?)");
    $stmt->execute([
      $business, $baseUrl, $stripePub, $stripeSec,
      $smtpHost, $smtpPort, $smtpUser, $smtpPass, $smtpFrom, $smtpFromNm
    ]);

    // Crear usuario admin
    if (!$adminEmail || !$adminPass) {
      throw new Exception("Debes capturar correo y contraseña del administrador.");
    }
    $passHash = password_hash($adminPass, PASSWORD_BCRYPT);
    $stmt = $pdo->prepare("INSERT INTO users (name,email,password_hash,role) VALUES (?,?,?,'admin')");
    $stmt->execute(['Administrador', $adminEmail, $passHash]);

    // Crear carpetas necesarias
    $folders = [
      'giftcards',
      'images',
      'images/square',
      'images/portrait',
      'images/landscape',
      'icons',
      'logo',
      'wallpapers',
      'admin'
    ];
    foreach ($folders as $folder) {
      $path = __DIR__ . '/' . $folder;
      if (!is_dir($path)) {
        mkdir($path, 0775, true);
      }
    }

    // Crear config.php
    $configContent = "<?php\n"
      . "define('DB_HOST', '" . addslashes($dbHost) . "');\n"
      . "define('DB_NAME', '" . addslashes($dbName) . "');\n"
      . "define('DB_USER', '" . addslashes($dbUser) . "');\n"
      . "define('DB_PASS', '" . addslashes($dbPass) . "');\n"
      . "define('BASE_URL', '" . addslashes($baseUrl) . "');\n";

    file_put_contents(__DIR__ . '/config.php', $configContent);

    $ok = true;
  } catch (Exception $e) {
    $error = $e->getMessage();
  }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Instalador Giftcards PRO</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
  <h1 class="mb-4">Instalador Giftcards PRO</h1>

  <?php if (!empty($ok)): ?>
    <div class="alert alert-success">
      Instalación completada. Borra o renombra <code>installer.php</code> por seguridad.
      <br>Ahora puedes ir a <a href="index.php">index.php</a> o al panel <a href="admin/">admin/</a>.
    </div>
  <?php elseif (!empty($error)): ?>
    <div class="alert alert-danger">
      Error: <?= htmlspecialchars($error) ?>
    </div>
  <?php endif; ?>

  <form method="post" class="card card-body">
    <h4>Datos de la base de datos</h4>
    <div class="row mb-3">
      <div class="col-md-3">
        <label class="form-label">Host</label>
        <input type="text" name="db_host" class="form-control" value="localhost">
      </div>
      <div class="col-md-3">
        <label class="form-label">Nombre BD</label>
        <input type="text" name="db_name" class="form-control" required>
      </div>
      <div class="col-md-3">
        <label class="form-label">Usuario</label>
        <input type="text" name="db_user" class="form-control" required>
      </div>
      <div class="col-md-3">
        <label class="form-label">Password</label>
        <input type="password" name="db_pass" class="form-control">
      </div>
    </div>

    <h4>Administrador</h4>
    <div class="row mb-3">
      <div class="col-md-6">
        <label class="form-label">Email admin</label>
        <input type="email" name="admin_email" class="form-control" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">Password admin</label>
        <input type="password" name="admin_pass" class="form-control" required>
      </div>
    </div>

    <h4>Datos del negocio</h4>
    <div class="mb-3">
      <label class="form-label">Nombre del negocio</label>
      <input type="text" name="business_name" class="form-control" value="Mi Negocio de Giftcards">
    </div>

    <h4>Stripe (opcional por ahora)</h4>
    <div class="row mb-3">
      <div class="col-md-6">
        <label class="form-label">Stripe Public Key</label>
        <input type="text" name="stripe_public_key" class="form-control">
      </div>
      <div class="col-md-6">
        <label class="form-label">Stripe Secret Key</label>
        <input type="text" name="stripe_secret_key" class="form-control">
      </div>
    </div>

    <h4>Correo SMTP (para envío automático de giftcards)</h4>
    <div class="row mb-3">
      <div class="col-md-4">
        <label class="form-label">SMTP Host</label>
        <input type="text" name="smtp_host" class="form-control">
      </div>
      <div class="col-md-2">
        <label class="form-label">SMTP Port</label>
        <input type="number" name="smtp_port" class="form-control" value="587">
      </div>
      <div class="col-md-3">
        <label class="form-label">SMTP User</label>
        <input type="text" name="smtp_user" class="form-control">
      </div>
      <div class="col-md-3">
        <label class="form-label">SMTP Password</label>
        <input type="password" name="smtp_pass" class="form-control">
      </div>
    </div>

    <div class="row mb-3">
      <div class="col-md-6">
        <label class="form-label">From Email</label>
        <input type="email" name="smtp_from_email" class="form-control">
      </div>
      <div class="col-md-6">
        <label class="form-label">From Name</label>
        <input type="text" name="smtp_from_name" class="form-control">
      </div>
    </div>

    <button class="btn btn-primary">Instalar</button>
  </form>
</div>
</body>
</html>
