<?php
/**
 * Installation Script
 * Patel E-Mitra & Aadhaar Seva Kendra CMS
 * 
 * IMPORTANT: Delete this file after installation for security!
 */

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

// Check if already installed
if (file_exists(__DIR__ . '/config/database.php')) {
    $content = file_get_contents(__DIR__ . '/config/database.php');
    if (strpos($content, 'patel_emitra') !== false && strpos($content, 'DB_NAME') !== false) {
        // Check if database tables exist
        try {
            require_once __DIR__ . '/config/config.php';
            $db = getDB();
            $stmt = $db->query("SHOW TABLES LIKE 'users'");
            if ($stmt->rowCount() > 0) {
                header('Location: admin/login.php');
                exit();
            }
        } catch (Exception $e) {
            // Database not configured yet, continue with installation
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step === 1) {
        // Step 1: Database Configuration
        $db_host = trim($_POST['db_host'] ?? 'localhost');
        $db_name = trim($_POST['db_name'] ?? '');
        $db_user = trim($_POST['db_user'] ?? '');
        $db_pass = $_POST['db_pass'] ?? '';
        
        if (empty($db_name) || empty($db_user)) {
            $error = 'Please fill in all required fields';
        } else {
            // Test database connection
            try {
                $pdo = new PDO("mysql:host=$db_host;charset=utf8mb4", $db_user, $db_pass);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                
                // Create database if not exists
                $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
                
                // Save configuration
                $config_content = "<?php\n";
                $config_content .= "/**\n * Database Configuration\n * Generated by installer\n */\n\n";
                $config_content .= "define('DB_HOST', '$db_host');\n";
                $config_content .= "define('DB_NAME', '$db_name');\n";
                $config_content .= "define('DB_USER', '$db_user');\n";
                $config_content .= "define('DB_PASS', '$db_pass');\n";
                $config_content .= "define('DB_CHARSET', 'utf8mb4');\n\n";
                $config_content .= "try {\n";
                $config_content .= "    \$pdo = new PDO(\n";
                $config_content .= "        \"mysql:host=\" . DB_HOST . \";dbname=\" . DB_NAME . \";charset=\" . DB_CHARSET,\n";
                $config_content .= "        DB_USER,\n";
                $config_content .= "        DB_PASS,\n";
                $config_content .= "        [\n";
                $config_content .= "            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n";
                $config_content .= "            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n";
                $config_content .= "            PDO::ATTR_EMULATE_PREPARES => false,\n";
                $config_content .= "            PDO::MYSQL_ATTR_INIT_COMMAND => \"SET NAMES utf8mb4\"\n";
                $config_content .= "        ]\n";
                $config_content .= "    );\n";
                $config_content .= "} catch (PDOException \$e) {\n";
                $config_content .= "    die(\"Database connection failed: \" . \$e->getMessage());\n";
                $config_content .= "}\n\n";
                $config_content .= "function getDB() {\n";
                $config_content .= "    global \$pdo;\n";
                $config_content .= "    return \$pdo;\n";
                $config_content .= "}\n";
                $config_content .= "?>\n";
                
                file_put_contents(__DIR__ . '/config/database.php', $config_content);
                
                header('Location: install.php?step=2');
                exit();
                
            } catch (PDOException $e) {
                $error = 'Database connection failed: ' . $e->getMessage();
            }
        }
    } elseif ($step === 2) {
        // Step 2: Import Database
        try {
            require_once __DIR__ . '/config/config.php';
            $db = getDB();
            
            // Read SQL file
            $sql_file = __DIR__ . '/database/patel_emitra.sql';
            if (!file_exists($sql_file)) {
                $error = 'SQL file not found';
            } else {
                $sql = file_get_contents($sql_file);
                
                // Execute SQL
                $db->exec($sql);
                
                header('Location: install.php?step=3');
                exit();
            }
        } catch (Exception $e) {
            $error = 'Database import failed: ' . $e->getMessage();
        }
    } elseif ($step === 3) {
        // Step 3: Admin Account
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        $full_name = trim($_POST['full_name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        
        if (empty($username) || empty($email) || empty($password) || empty($full_name)) {
            $error = 'Please fill in all required fields';
        } elseif ($password !== $confirm_password) {
            $error = 'Passwords do not match';
        } elseif (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters long';
        } else {
            try {
                require_once __DIR__ . '/config/config.php';
                $db = getDB();
                
                // Hash password
                $password_hash = password_hash($password, PASSWORD_DEFAULT);
                
                // Check if user already exists
                $stmt = $db->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
                $stmt->execute([$username, $email]);
                
                if ($stmt->fetch()) {
                    // Update existing user
                    $stmt = $db->prepare("UPDATE users SET username = ?, email = ?, password = ?, full_name = ?, phone = ?, role = 'admin' WHERE username = ? OR email = ?");
                    $stmt->execute([$username, $email, $password_hash, $full_name, $phone, $username, $email]);
                } else {
                    // Insert new user
                    $stmt = $db->prepare("INSERT INTO users (username, email, password, full_name, phone, role, status) VALUES (?, ?, ?, ?, ?, 'admin', 'active')");
                    $stmt->execute([$username, $email, $password_hash, $full_name, $phone]);
                }
                
                $success = 'Installation completed successfully!';
                header('Location: install.php?step=4');
                exit();
                
            } catch (Exception $e) {
                $error = 'Failed to create admin account: ' . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installation - Patel E-Mitra CMS</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gradient-to-br from-blue-900 via-purple-900 to-blue-900 min-h-screen flex items-center justify-center p-4">
    <div class="max-w-2xl w-full">
        <!-- Header -->
        <div class="text-center mb-8">
            <div class="inline-flex items-center justify-center w-20 h-20 bg-white rounded-full mb-4">
                <i class="fa-solid fa-building-columns text-blue-900 text-4xl"></i>
            </div>
            <h1 class="text-3xl font-bold text-white mb-2">CMS Installation</h1>
            <p class="text-blue-200">Patel E-Mitra & Aadhaar Seva Kendra</p>
        </div>
        
        <!-- Progress Bar -->
        <div class="bg-white bg-opacity-20 rounded-full h-2 mb-8">
            <div class="bg-white h-2 rounded-full transition-all" style="width: <?php echo ($step / 4) * 100; ?>%"></div>
        </div>
        
        <!-- Installation Steps -->
        <div class="bg-white rounded-2xl shadow-2xl p-8">
            <?php if ($error): ?>
                <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded">
                    <i class="fa-solid fa-circle-exclamation mr-2"></i>
                    <?php echo $error; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($step === 1): ?>
                <!-- Step 1: Database Configuration -->
                <h2 class="text-2xl font-bold text-gray-800 mb-6">
                    <span class="bg-blue-600 text-white w-8 h-8 rounded-full inline-flex items-center justify-center mr-2">1</span>
                    Database Configuration
                </h2>
                
                <form method="POST" action="install.php?step=1" class="space-y-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Database Host *</label>
                        <input type="text" name="db_host" value="localhost" required 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Database Name *</label>
                        <input type="text" name="db_name" value="patel_emitra" required 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Database Username *</label>
                        <input type="text" name="db_user" value="root" required 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Database Password</label>
                        <input type="password" name="db_pass" 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <button type="submit" class="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition">
                        Continue <i class="fa-solid fa-arrow-right ml-2"></i>
                    </button>
                </form>
                
            <?php elseif ($step === 2): ?>
                <!-- Step 2: Import Database -->
                <h2 class="text-2xl font-bold text-gray-800 mb-6">
                    <span class="bg-blue-600 text-white w-8 h-8 rounded-full inline-flex items-center justify-center mr-2">2</span>
                    Import Database
                </h2>
                
                <p class="text-gray-600 mb-6">Click the button below to import the database schema and default data.</p>
                
                <form method="POST" action="install.php?step=2">
                    <button type="submit" class="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition">
                        <i class="fa-solid fa-database mr-2"></i>
                        Import Database
                    </button>
                </form>
                
            <?php elseif ($step === 3): ?>
                <!-- Step 3: Admin Account -->
                <h2 class="text-2xl font-bold text-gray-800 mb-6">
                    <span class="bg-blue-600 text-white w-8 h-8 rounded-full inline-flex items-center justify-center mr-2">3</span>
                    Create Admin Account
                </h2>
                
                <form method="POST" action="install.php?step=3" class="space-y-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Full Name *</label>
                        <input type="text" name="full_name" required 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Username *</label>
                        <input type="text" name="username" required 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Email *</label>
                        <input type="email" name="email" required 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Phone</label>
                        <input type="tel" name="phone" 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Password *</label>
                        <input type="password" name="password" required minlength="6" 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Confirm Password *</label>
                        <input type="password" name="confirm_password" required minlength="6" 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none">
                    </div>
                    
                    <button type="submit" class="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition">
                        Create Admin Account <i class="fa-solid fa-arrow-right ml-2"></i>
                    </button>
                </form>
                
            <?php elseif ($step === 4): ?>
                <!-- Step 4: Installation Complete -->
                <div class="text-center">
                    <div class="inline-flex items-center justify-center w-20 h-20 bg-green-100 rounded-full mb-4">
                        <i class="fa-solid fa-check text-green-600 text-4xl"></i>
                    </div>
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">Installation Complete!</h2>
                    <p class="text-gray-600 mb-6">Your CMS has been successfully installed. You can now login to the admin panel.</p>
                    
                    <div class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-800 p-4 mb-6 rounded text-left">
                        <p class="font-semibold mb-2"><i class="fa-solid fa-exclamation-triangle mr-2"></i>Important Security Steps:</p>
                        <ol class="list-decimal list-inside space-y-1 text-sm">
                            <li>Delete <code>install.php</code> file for security</li>
                            <li>Change default admin password</li>
                            <li>Configure site settings in admin panel</li>
                        </ol>
                    </div>
                    
                    <a href="admin/login.php" class="inline-block bg-blue-600 text-white font-bold py-3 px-8 rounded-lg hover:bg-blue-700 transition">
                        <i class="fa-solid fa-right-to-bracket mr-2"></i>
                        Login to Admin Panel
                    </a>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Footer -->
        <div class="text-center mt-6 text-blue-200 text-sm">
            <p>&copy; <?php echo date('Y'); ?> Patel E-Mitra & Aadhaar Seva Kendra</p>
        </div>
    </div>
</body>
</html>
