<?php
// Instalador Giftcards PRO — versión corregida y completa
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  /* ================================
       1. Capturar datos del formulario
  ===================================*/
  $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;

  /* ================================
       2. Calcular BASE_URL automático
  ===================================*/
  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $host   = $_SERVER['HTTP_HOST'];
  $scriptDir = rtrim(str_replace('\\','/', dirname($_SERVER['SCRIPT_NAME'])), '/');
  $baseUrl = $scheme . '://' . $host . ($scriptDir !== '/' ? $scriptDir : '') . '/';

  try {

    /* ================================
         3. Conectar a MySQL
    ===================================*/
    $pdo = new PDO("mysql:host=$dbHost;charset=utf8mb4", $dbUser, $dbPass, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    /* ================================
         4. Crear base de datos si no existe
    ===================================*/
    if (!$dbName) throw new Exception("Debes indicar un nombre de base de datos.");

    $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    $pdo->exec("USE `$dbName`");

    /* ================================
         5. Crear tablas
    ===================================*/
    $schema = <<<SQL

CREATE TABLE IF NOT EXISTS amount_options (
  id INT AUTO_INCREMENT PRIMARY KEY,
  amount INT NOT NULL,
  title VARCHAR(100) NOT NULL,
  description VARCHAR(255),
  is_active TINYINT(1) DEFAULT 1,
  icon VARCHAR(255)
);

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 y reduce líneas de expresión.',1,'icons/anti_edad.png'),
(3000,'Facial de lujo + masaje','Incluye limpieza, hidratación y masaje.',1,'icons/lujo_masaje.png'),
(5000,'Paquete VIP rejuvenecedor','Tratamiento completo premium.',1,'icons/vip.png');

CREATE TABLE IF NOT EXISTS giftcards (
  id INT AUTO_INCREMENT PRIMARY KEY,
  recipient_name VARCHAR(100),
  recipient_contact VARCHAR(100),
  message TEXT,
  sender_name VARCHAR(100),
  sender_email VARCHAR(100),
  amount DECIMAL(10,2),
  image_filename VARCHAR(255),
  qr_payload TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  days_valid INT DEFAULT 30,
  days_remaining INT DEFAULT 30,
  is_valid TINYINT(1) DEFAULT 1,
  code VARCHAR(100) UNIQUE,
  purchase_token VARCHAR(100),
  stripe_session_id VARCHAR(255)
);

CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  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
);

CREATE TABLE IF NOT EXISTS settings (
  id INT AUTO_INCREMENT PRIMARY KEY,
  business_name VARCHAR(150),
  base_url VARCHAR(255),
  stripe_public_key VARCHAR(255),
  stripe_secret_key VARCHAR(255),
  smtp_host VARCHAR(255),
  smtp_port INT,
  smtp_user VARCHAR(255),
  smtp_pass VARCHAR(255),
  smtp_from_email VARCHAR(255),
  smtp_from_name VARCHAR(255),
  points_per_currency DECIMAL(10,2) DEFAULT 1.00,
  currency_unit VARCHAR(10) DEFAULT 'MXN',
  default_days_valid INT DEFAULT 30,
  logo_filename VARCHAR(255) DEFAULT 'logo.png'
);

CREATE TABLE IF NOT EXISTS customers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(150) NOT NULL UNIQUE,
  name VARCHAR(150),
  total_spent DECIMAL(10,2) DEFAULT 0,
  points_balance INT DEFAULT 0,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS points_log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  customer_id INT NOT NULL,
  giftcards_batch VARCHAR(100),
  amount DECIMAL(10,2) DEFAULT 0,
  points_added INT DEFAULT 0,
  description VARCHAR(255),
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
);

SQL;

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

    /* ================================
         6. Insertar fila settings
    ===================================*/
    $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, logo_filename)
      VALUES (?,?,?,?,?,?,?,?,?,?,?)
    ");

    $stmt->execute([
      $business,
      $baseUrl,
      $stripePub,
      $stripeSec,
      $smtpHost,
      $smtpPort,
      $smtpUser,
      $smtpPass,
      $smtpFrom,
      $smtpFromNm,
      'logo.png'
    ]);

    /* ================================
         7. Crear usuario admin
    ===================================*/
    if (!$adminEmail || !$adminPass) {
      throw new Exception("Debes capturar correo y contraseña del administrador.");
    }

    $hash = password_hash($adminPass, PASSWORD_BCRYPT);
    $pdo->prepare("INSERT INTO users (name,email,password_hash,role)
                   VALUES ('Administrador',?,?, 'admin')")
        ->execute([$adminEmail, $hash]);

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

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

    file_put_contents(__DIR__ . "/config.php", $config);

    $ok = true;

  } catch (Exception $e) {
    $error = $e->getMessage();
  }
}
?>
<!DOCTYPE html>
<html>
<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.<br>
      Borra <code>installer.php</code> por seguridad.<br>
      <a href="index.php">Ir al sitio</a> | <a href="admin/">Entrar al panel</a>
    </div>
  <?php endif; ?>

  <?php if (!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"><input name="db_host" class="form-control" placeholder="Host" value="localhost"></div>
      <div class="col-md-3"><input name="db_name" class="form-control" placeholder="Nombre BD" required></div>
      <div class="col-md-3"><input name="db_user" class="form-control" placeholder="Usuario" required></div>
      <div class="col-md-3"><input type="password" name="db_pass" class="form-control" placeholder="Password"></div>
    </div>

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

    <h4>Datos del negocio</h4>
    <input name="business_name" class="form-control mb-3" placeholder="Nombre del negocio" value="Mi Negocio">

    <h4>Stripe</h4>
    <div class="row mb-3">
      <div class="col-md-6"><input name="stripe_public_key" class="form-control" placeholder="Stripe Public Key"></div>
      <div class="col-md-6"><input name="stripe_secret_key" class="form-control" placeholder="Stripe Secret Key"></div>
    </div>

    <h4>SMTP</h4>
    <div class="row mb-3">
      <div class="col-md-4"><input name="smtp_host" class="form-control" placeholder="SMTP Host"></div>
      <div class="col-md-2"><input name="smtp_port" type="number" class="form-control" placeholder="Port" value="587"></div>
      <div class="col-md-3"><input name="smtp_user" class="form-control" placeholder="SMTP User"></div>
      <div class="col-md-3"><input name="smtp_pass" type="password" class="form-control" placeholder="SMTP Password"></div>
    </div>
    <div class="row mb-3">
      <div class="col-md-6"><input name="smtp_from_email" class="form-control" placeholder="From Email"></div>
      <div class="col-md-6"><input name="smtp_from_name" class="form-control" placeholder="From Name"></div>
    </div>

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

</div>
</body>
</html>
