<?php
/**
 * WhatsApp CRM - 1-Click Database Installer & Setup Wizard
 * Can be run from CLI: php database/installer.php
 * Or accessed via Browser: http://localhost:8000/database/installer.php
 */

$isCli = (php_sapi_name() === 'cli');
$error = '';
$success = '';

// Load default parameters or POST parameters
$dbHost = $_POST['db_host'] ?? getenv('DB_HOST') ?: '127.0.0.1';
$dbPort = $_POST['db_port'] ?? getenv('DB_PORT') ?: '3306';
$dbName = $_POST['db_name'] ?? getenv('DB_DATABASE') ?: 'whatsapp_crm';
$dbUser = $_POST['db_user'] ?? getenv('DB_USERNAME') ?: 'root';
$dbPass = $_POST['db_pass'] ?? getenv('DB_PASSWORD') ?: '';
$appUrl = $_POST['app_url'] ?? 'http://localhost:8000';

$adminName  = $_POST['admin_name'] ?? 'System Administrator';
$adminEmail = $_POST['admin_email'] ?? 'admin@crm.local';
$adminPass  = $_POST['admin_pass'] ?? 'password123';

if ($isCli || ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['install_action']))) {
    try {
        // 1. Test Server Connection (without db name)
        $dsnServer = "mysql:host={$dbHost};port={$dbPort};charset=utf8mb4";
        $pdo = new PDO($dsnServer, $dbUser, $dbPass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
        ]);

        // 2. Create Database if not exists
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
        $pdo->exec("USE `{$dbName}`;");

        // 3. Run schema.sql
        $schemaFile = __DIR__ . '/schema.sql';
        if (!file_exists($schemaFile)) {
            throw new Exception("schema.sql not found at: {$schemaFile}");
        }
        $schemaSql = file_get_contents($schemaFile);
        $pdo->exec($schemaSql);

        // 4. Run seeds.sql
        $seedsFile = __DIR__ . '/seeds.sql';
        if (file_exists($seedsFile)) {
            $seedsSql = file_get_contents($seedsFile);
            $pdo->exec($seedsSql);
        }

        // 5. Update or insert custom admin account
        $adminHash = password_hash($adminPass, PASSWORD_BCRYPT);
        $stmt = $pdo->prepare("UPDATE `users` SET `name` = ?, `email` = ?, `password_hash` = ? WHERE `id` = 1");
        $stmt->execute([$adminName, $adminEmail, $adminHash]);

        // 6. Write / Update .env file in project root
        $envFile = dirname(__DIR__) . '/.env';
        $envContent = <<<ENV
APP_NAME="WhatsApp CRM"
APP_ENV=development
APP_URL={$appUrl}
APP_DEBUG=true

DB_CONNECTION=mysql
DB_HOST={$dbHost}
DB_PORT={$dbPort}
DB_DATABASE={$dbName}
DB_USERNAME={$dbUser}
DB_PASSWORD={$dbPass}

WHATSAPP_PHONE_NUMBER_ID=100609349424840
WHATSAPP_WABA_ID=105829482910482
WHATSAPP_ACCESS_TOKEN=EAAxxxxxxx_PLACEHOLDER_TOKEN
WHATSAPP_VERIFY_TOKEN=whatsapp_crm_secure_token_2026
WHATSAPP_APP_SECRET=abcdef1234567890abcdef1234567890
WHATSAPP_API_VERSION=v19.0
WHATSAPP_SIMULATOR_MODE=true

SESSION_LIFETIME=86400
TIMEZONE=Asia/Kolkata
ENV;

        file_put_contents($envFile, $envContent);

        $success = "WhatsApp CRM database successfully installed and configured!";

        if ($isCli) {
            echo "\n=======================================================\n";
            echo " [SUCCESS] {$success}\n";
            echo " Database: {$dbName}\n";
            echo " Admin Email: {$adminEmail}\n";
            echo " Admin Password: {$adminPass}\n";
            echo " .env configured at: {$envFile}\n";
            echo "=======================================================\n\n";
            exit(0);
        }
    } catch (Exception $e) {
        $error = "Installation Error: " . $e->getMessage();
        if ($isCli) {
            echo "\n[ERROR] {$error}\n\n";
            exit(1);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WhatsApp CRM - Setup Wizard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>body { font-family: 'Plus Jakarta Sans', sans-serif; }</style>
</head>
<body class="bg-slate-900 text-slate-100 min-h-screen flex items-center justify-center p-6">
    <div class="max-w-xl w-full bg-slate-800/80 backdrop-blur border border-slate-700/60 rounded-2xl shadow-2xl p-8">
        <div class="flex items-center space-x-3 mb-6">
            <div class="w-12 h-12 rounded-xl bg-emerald-500/20 border border-emerald-500/30 flex items-center justify-center text-emerald-400 font-bold text-2xl">
                💬
            </div>
            <div>
                <h1 class="text-2xl font-bold text-white">WhatsApp CRM Installer</h1>
                <p class="text-slate-400 text-sm">Database & Environment Auto-Configurator</p>
            </div>
        </div>

        <?php if ($success): ?>
            <div class="bg-emerald-500/10 border border-emerald-500/40 text-emerald-300 p-5 rounded-xl mb-6">
                <div class="font-bold flex items-center space-x-2 text-lg mb-2">
                    <span>✅ Installation Complete!</span>
                </div>
                <p class="text-sm mb-4"><?= htmlspecialchars($success) ?></p>
                <div class="bg-slate-900/80 p-3 rounded-lg text-xs space-y-1 font-mono text-slate-300">
                    <div><strong>Admin Email:</strong> <?= htmlspecialchars($adminEmail) ?></div>
                    <div><strong>Admin Password:</strong> <?= htmlspecialchars($adminPass) ?></div>
                </div>
                <div class="mt-5">
                    <a href="../public/index.php" class="inline-block w-full text-center bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-3 px-6 rounded-xl transition">
                        Launch CRM Dashboard &rarr;
                    </a>
                </div>
            </div>
        <?php else: ?>

            <?php if ($error): ?>
                <div class="bg-red-500/10 border border-red-500/40 text-red-300 p-4 rounded-xl mb-6 text-sm">
                    <strong>Error:</strong> <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <form method="POST" class="space-y-5">
                <input type="hidden" name="install_action" value="1">
                
                <div class="border-b border-slate-700 pb-3 mb-4">
                    <h2 class="text-sm uppercase tracking-wider font-semibold text-emerald-400">1. MySQL Database Settings</h2>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs text-slate-400 mb-1">Host</label>
                        <input type="text" name="db_host" value="<?= htmlspecialchars($dbHost) ?>" class="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-emerald-500" required>
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1">Port</label>
                        <input type="text" name="db_port" value="<?= htmlspecialchars($dbPort) ?>" class="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-emerald-500" required>
                    </div>
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1">Database Name</label>
                    <input type="text" name="db_name" value="<?= htmlspecialchars($dbName) ?>" class="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-emerald-500" required>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs text-slate-400 mb-1">Username</label>
                        <input type="text" name="db_user" value="<?= htmlspecialchars($dbUser) ?>" class="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-emerald-500" required>
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1">Password</label>
                        <input type="password" name="db_pass" value="<?= htmlspecialchars($dbPass) ?>" class="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-emerald-500" placeholder="(empty if root)">
                    </div>
                </div>

                <div class="border-b border-slate-700 pb-3 pt-3 mb-4">
                    <h2 class="text-sm uppercase tracking-wider font-semibold text-emerald-400">2. Administrator Account</h2>
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1">Admin Full Name</label>
                    <input type="text" name="admin_name" value="<?= htmlspecialchars($adminName) ?>" class="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-emerald-500" required>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs text-slate-400 mb-1">Admin Email</label>
                        <input type="email" name="admin_email" value="<?= htmlspecialchars($adminEmail) ?>" class="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-emerald-500" required>
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1">Admin Password</label>
                        <input type="text" name="admin_pass" value="<?= htmlspecialchars($adminPass) ?>" class="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-emerald-500" required>
                    </div>
                </div>

                <button type="submit" class="w-full mt-4 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-3 px-6 rounded-xl shadow-lg shadow-emerald-500/20 transition cursor-pointer">
                    Install & Initialize WhatsApp CRM &rarr;
                </button>
            </form>
        <?php endif; ?>
    </div>
</body>
</html>
