<?php
// DigiMobiz - Installation Script
error_reporting(E_ALL);
ini_set('display_errors', 1);

$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'digimobiz';

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $host = trim($_POST['host'] ?: 'localhost');
    $user = trim($_POST['user'] ?: 'root');
    $pass = $_POST['pass'];
    $dbname = trim($_POST['dbname'] ?: 'digimobiz');

    try {
        // Connect without database
        $pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ]);

        // Create database if not exists
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbname` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        $pdo->exec("USE `$dbname`");

        // Execute schema.sql
        $schema = file_get_contents(__DIR__ . '/database/schema.sql');
        $statements = explode(';', $schema);
        foreach ($statements as $stmt) {
            $stmt = trim($stmt);
            if (!empty($stmt)) {
                $pdo->exec($stmt);
            }
        }

        // Execute seed.sql
        $seed = file_get_contents(__DIR__ . '/database/seed.sql');
        $seedStatements = explode(';', $seed);
        foreach ($seedStatements as $stmt) {
            $stmt = trim($stmt);
            if (!empty($stmt)) {
                $pdo->exec($stmt);
            }
        }

        // Write config/database.php with user credentials
        $configContent = "<?php
// Database Configuration
define('DB_HOST', " . var_export($host, true) . ");
define('DB_NAME', " . var_export($dbname, true) . ");
define('DB_USER', " . var_export($user, true) . ");
define('DB_PASS', " . var_export($pass, true) . ");

function getDB() {
    static \$pdo = null;
    if (\$pdo === null) {
        try {
            \$pdo = new PDO(\"mysql:host=\" . DB_HOST . \";dbname=\" . DB_NAME . \";charset=utf8mb4\", DB_USER, DB_PASS, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);
        } catch (PDOException \$e) {
            die(\"Database connection failed: \" . \$e->getMessage());
        }
    }
    return \$pdo;
}";
        file_put_contents(__DIR__ . '/config/database.php', $configContent);

        $success = "Database installed successfully!<br>
                     Default login:<br>
                     Email: <strong>admin@example.com</strong><br>
                     Password: <strong>admin123</strong><br><br>
                     <a href='auth/login.php' class='btn btn-primary'>Go to Login</a>";

    } catch (PDOException $e) {
        $error = 'Database Error: ' . $e->getMessage();
    } catch (Exception $e) {
        $error = 'Error: ' . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Install DigiMobiz</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f0f2f5; min-height: 100vh; display: flex; align-items: center; }
        .install-container { max-width: 600px; margin: auto; }
        .card { border: none; border-radius: 12px; box-shadow: 0 2px 20px rgba(0,0,0,0.08); }
        .card-header { background: #1a237e; color: #fff; border-radius: 12px 12px 0 0; padding: 20px; text-align: center; }
    </style>
</head>
<body>
    <div class="container">
        <div class="install-container">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-mobile-alt fa-3x mb-2"></i>
                    <h4 class="mb-0">DigiMobiz Installation</h4>
                    <small>Mobile Shop Management System</small>
                </div>
                <div class="card-body p-4">
                    <?php if ($success): ?>
                    <div class="alert alert-success"><?= $success ?></div>
                    <?php else: ?>
                    <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label">Database Host</label>
                            <input type="text" name="host" class="form-control" value="<?= htmlspecialchars($host) ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Username</label>
                            <input type="text" name="user" class="form-control" value="<?= htmlspecialchars($user) ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Password</label>
                            <input type="password" name="pass" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Database Name</label>
                            <input type="text" name="dbname" class="form-control" value="<?= htmlspecialchars($dbname) ?>">
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-1"></i>This will create the database, tables, and seed data. Existing data may be lost.
                        </div>
                        <button type="submit" class="btn btn-primary btn-lg w-100"><i class="fas fa-database me-1"></i>Install Database</button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
