<?php
/**
 * Rig N Dig - Installation Wizard
 * Step-by-step setup for cPanel hosting
 */

define('INSTALL_MODE', true);
session_start();

$configFile = dirname(__DIR__) . '/config/config.php';

// Load config so we can check the INSTALLED constant
if (file_exists($configFile)) {
    require_once $configFile;
}

// If already fully installed, redirect (unless ?force=1 passed)
if (defined('INSTALLED') && INSTALLED === true && !isset($_GET['force'])) {
    header('Location: /');
    exit;
}

$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
$errors = [];
$success = false;

// Step 2: Test DB Connection
if ($step === 2 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $host = trim($_POST['db_host'] ?? '');
    $port = trim($_POST['db_port'] ?? '3306');
    $name = trim($_POST['db_name'] ?? '');
    $user = trim($_POST['db_user'] ?? '');
    $pass = trim($_POST['db_pass'] ?? '');

    try {
        $dsn = "mysql:host={$host};port={$port};dbname={$name};charset=utf8mb4";
        $pdo = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
        $_SESSION['install_db'] = compact('host', 'port', 'name', 'user', 'pass');
        header('Location: ?step=3');
        exit;
    } catch (PDOException $e) {
        $errors[] = "Database connection failed: " . $e->getMessage();
    }
}

// Step 3: Create tables + admin account
if ($step === 3 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $db = $_SESSION['install_db'] ?? null;
    if (!$db) { header('Location: ?step=2'); exit; }

    $adminName  = trim($_POST['admin_name'] ?? '');
    $adminEmail = trim($_POST['admin_email'] ?? '');
    $adminPass  = trim($_POST['admin_pass'] ?? '');
    $siteUrl    = rtrim(trim($_POST['site_url'] ?? ''), '/');
    $smtpHost   = trim($_POST['smtp_host'] ?? '');
    $smtpPort   = trim($_POST['smtp_port'] ?? '587');
    $smtpUser   = trim($_POST['smtp_user'] ?? '');
    $smtpPass   = trim($_POST['smtp_pass'] ?? '');

    if (!$adminName || !$adminEmail || !$adminPass) {
        $errors[] = "Admin name, email and password are required.";
    } else {
        try {
            $dsn = "mysql:host={$db['host']};port={$db['port']};dbname={$db['name']};charset=utf8mb4";
            $pdo = new PDO($dsn, $db['user'], $db['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

            // Run SQL schema
            $sql = file_get_contents(__DIR__ . '/schema.sql');
            $pdo->exec($sql);

            // Insert admin user
            $hash = password_hash($adminPass, PASSWORD_BCRYPT);
            $stmt = $pdo->prepare("INSERT INTO admins (name, email, password, role) VALUES (?, ?, ?, 'super_admin') ON DUPLICATE KEY UPDATE password=VALUES(password)");
            $stmt->execute([$adminName, $adminEmail, $hash]);

            // Create required upload subdirectories
            $uploadBase = dirname(__DIR__) . '/uploads';
            foreach (['images','products','gallery','categories','repair','documents'] as $sub) {
                $subDir = $uploadBase . '/' . $sub;
                if (!is_dir($subDir)) mkdir($subDir, 0755, true);
            }

            // Write config file
            $configDir = dirname(__DIR__) . '/config';
            if (!is_dir($configDir)) mkdir($configDir, 0755, true);

            $secret = bin2hex(random_bytes(32));
            $configContent = "<?php\n"
                . "// Rig N Dig Configuration — Auto-generated by Install Wizard\n"
                . "// DO NOT edit manually unless you know what you are doing.\n\n"
                . "define('INSTALLED', true);\n\n"
                . "// Database\n"
                . "define('DB_HOST', " . var_export($db['host'], true) . ");\n"
                . "define('DB_PORT', " . var_export($db['port'], true) . ");\n"
                . "define('DB_NAME', " . var_export($db['name'], true) . ");\n"
                . "define('DB_USER', " . var_export($db['user'], true) . ");\n"
                . "define('DB_PASS', " . var_export($db['pass'], true) . ");\n\n"
                . "// Site\n"
                . "define('SITE_URL', " . var_export($siteUrl, true) . ");\n"
                . "define('SITE_NAME', 'Rig N Dig');\n"
                . "define('APP_SECRET', " . var_export($secret, true) . ");\n"
                . "define('APP_VERSION', '1.0.0');\n\n"
                . "// Email / SMTP\n"
                . "define('SMTP_HOST', " . var_export($smtpHost, true) . ");\n"
                . "define('SMTP_PORT', " . var_export($smtpPort, true) . ");\n"
                . "define('SMTP_USER', " . var_export($smtpUser, true) . ");\n"
                . "define('SMTP_PASS', " . var_export($smtpPass, true) . ");\n\n"
                . "// Paths\n"
                . "define('ROOT_PATH', dirname(__DIR__));\n"
                . "define('UPLOAD_PATH', ROOT_PATH . '/uploads');\n"
                . "define('PDF_PATH', ROOT_PATH . '/pdf');\n"
                . "define('LOG_PATH', ROOT_PATH . '/logs');\n\n"
                . "// Upload settings\n"
                . "define('MAX_FILE_SIZE', 10 * 1024 * 1024);\n"
                . "define('ALLOWED_IMAGE_TYPES', ['image/jpeg', 'image/png', 'image/webp', 'image/gif']);\n"
                . "define('ALLOWED_DOC_TYPES', ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']);\n\n"
                . "// Pagination\n"
                . "define('PRODUCTS_PER_PAGE', 12);\n"
                . "define('ADMIN_PER_PAGE', 20);\n\n"
                . "// Session lifetime (seconds)\n"
                . "define('SESSION_LIFETIME', 3600 * 8);\n";

            file_put_contents($configFile, $configContent);
            $success = true;
        } catch (Exception $e) {
            $errors[] = "Installation failed: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rig N Dig - Installation Wizard</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
  body { background: #0a0e1a; color: #e8eaed; font-family: 'Segoe UI', sans-serif; }
  .orange { color: #ff6b00; }
  .card { background: #1a1f2e; border: 1px solid #2a3147; border-radius: 12px; }
  .step-circle { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 14px; }
  .active-step { background: #ff6b00; color: #fff; }
  .done-step { background: #22c55e; color: #fff; }
  .pending-step { background: #2a3147; color: #8892a0; }
  input, select { background: #0a0e1a; border: 1px solid #2a3147; color: #e8eaed; padding: 10px 14px; border-radius: 8px; width: 100%; outline: none; transition: border-color .2s; }
  input:focus, select:focus { border-color: #ff6b00; }
  .btn-orange { background: #ff6b00; color: #fff; padding: 12px 28px; border-radius: 8px; font-weight: 600; cursor: pointer; border: none; transition: background .2s; }
  .btn-orange:hover { background: #e55a00; }
  label { font-size: 13px; color: #8892a0; display: block; margin-bottom: 6px; }
  .error { background: #3b0000; border: 1px solid #dc2626; color: #fca5a5; padding: 12px; border-radius: 8px; margin-bottom: 16px; font-size: 14px; }
</style>
</head>
<body class="min-h-screen flex items-center justify-center p-6">
<div class="w-full max-w-2xl">

  <!-- Logo -->
  <div class="text-center mb-8">
    <div class="text-3xl font-black mb-1"><span class="orange">RIG</span> N <span class="orange">DIG</span></div>
    <div class="text-sm text-gray-400">Installation Wizard</div>
  </div>

  <!-- Steps -->
  <div class="flex items-center justify-center gap-4 mb-8">
    <?php
    $steps = ['Welcome', 'Database', 'Setup', 'Complete'];
    foreach ($steps as $i => $label):
      $n = $i + 1;
      $cls = $n < $step ? 'done-step' : ($n === $step ? 'active-step' : 'pending-step');
    ?>
    <div class="flex flex-col items-center gap-1">
      <div class="step-circle <?= $cls ?>"><?= $n < $step ? '✓' : $n ?></div>
      <span class="text-xs text-gray-400"><?= $label ?></span>
    </div>
    <?php if ($i < count($steps)-1): ?><div class="flex-1 h-px bg-gray-700 mb-4"></div><?php endif; ?>
    <?php endforeach; ?>
  </div>

  <div class="card p-8">

  <?php if ($success): ?>
    <!-- SUCCESS -->
    <div class="text-center py-6">
      <div class="text-6xl mb-4">🎉</div>
      <h2 class="text-2xl font-bold text-green-400 mb-2">Installation Complete!</h2>
      <p class="text-gray-400 mb-6">Rig N Dig has been successfully installed. For security, please delete the <code class="bg-gray-800 px-1 rounded">/install/</code> folder from your server.</p>
      <div class="flex gap-4 justify-center">
        <a href="/" class="btn-orange">Go to Website</a>
        <a href="/admin/" class="btn-orange" style="background:#2a3147">Admin Panel</a>
      </div>
    </div>

  <?php elseif ($step === 1): ?>
    <!-- STEP 1: WELCOME -->
    <h2 class="text-xl font-bold mb-2">Welcome to Rig N Dig</h2>
    <p class="text-gray-400 text-sm mb-6">This wizard will guide you through setting up your industrial B2B portal. Make sure you have your database credentials ready.</p>
    <div class="grid grid-cols-2 gap-4 mb-6">
      <?php $checks = [
        ['PHP 8+', version_compare(PHP_VERSION, '8.0.0', '>=')],
        ['PDO MySQL', extension_loaded('pdo_mysql')],
        ['Writable config/', is_writable(dirname(__DIR__) . '/config')],
        ['Writable uploads/', is_writable(dirname(__DIR__) . '/uploads')],
        ['FileInfo ext', extension_loaded('fileinfo')],
        ['cURL ext', extension_loaded('curl')],
      ]; foreach ($checks as [$label, $ok]): ?>
      <div class="flex items-center gap-2 p-3 rounded-lg" style="background:#0a0e1a">
        <span class="text-<?= $ok ? 'green' : 'red' ?>-400"><?= $ok ? '✓' : '✗' ?></span>
        <span class="text-sm"><?= $label ?></span>
        <span class="ml-auto text-xs text-<?= $ok ? 'green' : 'red' ?>-400"><?= $ok ? 'OK' : 'FAIL' ?></span>
      </div>
      <?php endforeach; ?>
    </div>
    <a href="?step=2" class="btn-orange block text-center">Continue →</a>

  <?php elseif ($step === 2): ?>
    <!-- STEP 2: DATABASE -->
    <h2 class="text-xl font-bold mb-1">Database Configuration</h2>
    <p class="text-gray-400 text-sm mb-6">Enter your MySQL database credentials from your cPanel.</p>
    <?php foreach ($errors as $e): ?><div class="error"><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
    <form method="POST">
      <div class="grid grid-cols-2 gap-4 mb-4">
        <div>
          <label>Database Host</label>
          <input name="db_host" value="localhost" required>
        </div>
        <div>
          <label>Port</label>
          <input name="db_port" value="3306" required>
        </div>
      </div>
      <div class="mb-4">
        <label>Database Name</label>
        <input name="db_name" placeholder="e.g. cpaneluser_rigndig" required>
      </div>
      <div class="grid grid-cols-2 gap-4 mb-6">
        <div>
          <label>Database Username</label>
          <input name="db_user" required>
        </div>
        <div>
          <label>Database Password</label>
          <input type="password" name="db_pass">
        </div>
      </div>
      <button type="submit" class="btn-orange w-full">Test & Continue →</button>
    </form>

  <?php elseif ($step === 3): ?>
    <!-- STEP 3: ADMIN SETUP -->
    <h2 class="text-xl font-bold mb-1">Site & Admin Setup</h2>
    <p class="text-gray-400 text-sm mb-6">Configure your site URL and create the administrator account.</p>
    <?php foreach ($errors as $e): ?><div class="error"><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
    <form method="POST">
      <div class="mb-4">
        <label>Site URL (no trailing slash)</label>
        <input name="site_url" value="https://rigndig.com" required>
      </div>
      <hr style="border-color:#2a3147" class="my-5">
      <p class="text-sm font-semibold mb-3 orange">Admin Account</p>
      <div class="mb-4">
        <label>Full Name</label>
        <input name="admin_name" placeholder="Admin Name" required>
      </div>
      <div class="grid grid-cols-2 gap-4 mb-4">
        <div>
          <label>Admin Email</label>
          <input type="email" name="admin_email" required>
        </div>
        <div>
          <label>Password</label>
          <input type="password" name="admin_pass" required minlength="8">
        </div>
      </div>
      <hr style="border-color:#2a3147" class="my-5">
      <p class="text-sm font-semibold mb-3 text-gray-300">Email / SMTP (optional)</p>
      <div class="grid grid-cols-2 gap-4 mb-4">
        <div><label>SMTP Host</label><input name="smtp_host" placeholder="mail.yourdomain.com"></div>
        <div><label>SMTP Port</label><input name="smtp_port" value="587"></div>
      </div>
      <div class="grid grid-cols-2 gap-4 mb-6">
        <div><label>SMTP Username</label><input name="smtp_user"></div>
        <div><label>SMTP Password</label><input type="password" name="smtp_pass"></div>
      </div>
      <button type="submit" class="btn-orange w-full">Install Rig N Dig →</button>
    </form>
  <?php endif; ?>

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