<?php
session_start();

$lockFile = __DIR__ . '/../installed.lock';

// Prevent re-installation if lock file exists
if (file_exists($lockFile)) {
    die("<h2>Installation Blocked</h2><p>The system is already installed. If you need to re-install, please delete the <code>installed.lock</code> file from the root directory.</p>");
}

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

// Auto detect URL
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['SERVER_PORT'] == 443) ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$script = $_SERVER['SCRIPT_NAME'] ?? '';
// Strip /install/index.php to get the root path
$basePath = str_replace(['/install/index.php', '/install/'], '', $script);
$detectedUrl = rtrim($protocol . '://' . $host . $basePath, '/');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db_host = $_POST['db_host'] ?? 'localhost';
    $db_user = $_POST['db_user'] ?? '';
    $db_pass = $_POST['db_pass'] ?? '';
    $db_name = $_POST['db_name'] ?? '';

    $app_url = $_POST['app_url'] ?? $detectedUrl;
    $admin_email = $_POST['admin_email'] ?? '';
    $admin_pass = $_POST['admin_pass'] ?? '';
    $confirm_pass = $_POST['confirm_pass'] ?? '';

    if (empty($db_host) || empty($db_user) || empty($db_name) || empty($admin_email) || empty($admin_pass)) {
        $error = "Please fill in all required fields.";
    } elseif (!filter_var($admin_email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } elseif ($admin_pass !== $confirm_pass) {
        $error = "Admin passwords do not match.";
    } elseif (strlen($admin_pass) < 6) {
        $error = "Admin password must be at least 6 characters long.";
    } else {
        try {
            // Test DB Connection
            $pdo = new PDO("mysql:host=$db_host", $db_user, $db_pass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // Connect to DB
            $pdo->exec("USE `$db_name`");

            // Import SQL
            $sqlFile = __DIR__ . '/../database/tms_core.sql';
            if (file_exists($sqlFile)) {
                $sql = file_get_contents($sqlFile);
                $pdo->exec($sql);
            } else {
                throw new Exception("Core SQL file (database/tms_core.sql) is missing. Please re-upload the files.");
            }

            // Update Admin User Credentials
            $hashedPass = password_hash($admin_pass, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET email = ?, password = ? WHERE role = 'admin' LIMIT 1");
            $stmt->execute([$admin_email, $hashedPass]);
            
            // If no admin user existed (fallback), insert one
            if ($stmt->rowCount() === 0) {
                 $stmt = $pdo->prepare("INSERT INTO users (name, email, password, role) VALUES ('System Admin', ?, ?, 'admin')");
                 $stmt->execute([$admin_email, $hashedPass]);
            }

            // Write config/database.php
            $dbConfigContent = "<?php\n\nreturn [\n    'host' => '$db_host',\n    'user' => '$db_user',\n    'pass' => '$db_pass',\n    'dbname' => '$db_name'\n];\n";
            file_put_contents(__DIR__ . '/../config/database.php', $dbConfigContent);

            // Write config/app.php explicitly
            $app_url = rtrim($app_url, '/');
            $appConfigContent = "<?php\n\nreturn [\n    'url' => '$app_url',\n];\n";
            file_put_contents(__DIR__ . '/../config/app.php', $appConfigContent);

            // CREATE LOCK FILE TO PREVENT RE-INSTALLATION
            file_put_contents($lockFile, "Installed on: " . date('Y-m-d H:i:s'));

            $success = "Installation was successful! The installer has been automatically locked for your security.";

        } catch (PDOException $e) {
            $error = "Database Error: " . $e->getMessage() . "<br>Please ensure the database exists and credentials are correct.";
        } 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>TMS Core - Installation Wizard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        body { background: #f8fafc; font-family: 'Inter', system-ui, -apple-system, sans-serif; }
        .install-container { max-width: 800px; margin: 40px auto; padding: 20px; }
        .install-card { background: white; border-radius: 20px; box-shadow: 0 10px 25px rgba(0,0,0,0.05); overflow: hidden; border: 1px solid #e2e8f0; }
        .header { background: #2563eb; background: linear-gradient(135deg, #1e40af, #3b82f6); color: white; padding: 40px; text-align: center; }
        .header i { font-size: 48px; margin-bottom: 15px; opacity: 0.9; }
        .header h2 { font-weight: 800; margin: 0; letter-spacing: -0.5px; }
        .header p { opacity: 0.8; margin: 10px 0 0; font-size: 15px; }
        
        .form-section { padding: 40px; }
        .section-title { font-size: 18px; font-weight: 700; color: #1e293b; margin-bottom: 25px; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px; display: flex; align-items: center; gap: 10px; }
        
        .form-label { font-size: 13px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
        .form-control { border-radius: 12px; padding: 12px 16px; border-color: #e2e8f0; font-size: 15px; color: #0f172a; font-weight: 500; background: #f8fafc; }
        .form-control:focus { border-color: #2563eb; background: #fff; box-shadow: 0 0 0 4px rgba(37,99,235,0.1); }
        
        .btn-primary { background: #2563eb; border: none; padding: 16px 30px; border-radius: 14px; font-weight: 700; font-size: 16px; text-transform: uppercase; letter-spacing: 1px; width: 100%; transition: all 0.3s; }
        .btn-primary:hover { background: #1d4ed8; transform: translateY(-2px); box-shadow: 0 10px 20px -5px rgba(37,99,235,0.4); }
        
        .password-container { position: relative; }
        .password-toggle { cursor: pointer; position: absolute; right: 16px; top: 50%; transform: translateY(-50%); color: #94a3b8; padding: 5px; }
        .password-toggle:hover { color: #2563eb; }
        
        .alert { border-radius: 12px; border: none; font-weight: 500; }
        .alert-danger { background: #fef2f2; color: #991b1b; }
        .alert-success { background: #f0fdf4; color: #166534; }
    </style>
</head>
<body>

<div class="install-container">
    <div class="install-card">
        <div class="header">
            <i class="fa-solid fa-server"></i>
            <h2>TMS Setup Wizard</h2>
            <p>Configure your database and administrator account to get started.</p>
        </div>

        <div class="form-section">
            <?php if ($success): ?>
                <div class="alert alert-success p-4 mb-4">
                    <h5 class="alert-heading fw-bold mb-2"><i class="fa-solid fa-circle-check me-2"></i> Success!</h5>
                    <p class="mb-3"><?php echo $success; ?></p>
                    <a href="<?php echo $app_url; ?>" class="btn btn-success fw-bold px-4 rounded-pill">Go to Application</a>
                </div>
            <?php else: ?>

            <?php if ($error): ?>
                <div class="alert alert-danger p-3 mb-4">
                    <i class="fa-solid fa-circle-exclamation me-2"></i> <?php echo $error; ?>
                </div>
            <?php endif; ?>

            <form method="POST" id="installForm">
                
                <!-- System Config -->
                <h4 class="section-title"><i class="fa-solid fa-globe text-primary"></i> Application Settings</h4>
                <div class="mb-5">
                    <label class="form-label">Application URL</label>
                    <input type="url" name="app_url" class="form-control" value="<?php echo htmlspecialchars($_POST['app_url'] ?? $detectedUrl); ?>" required>
                    <div class="form-text mt-2 small text-muted">We have auto-detected your URL. Change it only if it is incorrect. Ensure it includes <code>http://</code> or <code>https://</code>.</div>
                </div>

                <!-- Database Details -->
                <h4 class="section-title"><i class="fa-solid fa-database text-primary"></i> Database Configuration</h4>
                <div class="row g-4 mb-5">
                    <div class="col-md-6">
                        <label class="form-label">Database Host</label>
                        <input type="text" name="db_host" class="form-control" value="<?php echo htmlspecialchars($_POST['db_host'] ?? 'localhost'); ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Database Name</label>
                        <input type="text" name="db_name" class="form-control" value="<?php echo htmlspecialchars($_POST['db_name'] ?? ''); ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Database Username</label>
                        <input type="text" name="db_user" class="form-control" value="<?php echo htmlspecialchars($_POST['db_user'] ?? ''); ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Database Password</label>
                        <div class="password-container">
                            <input type="password" name="db_pass" id="db_pass" class="form-control" value="<?php echo htmlspecialchars($_POST['db_pass'] ?? ''); ?>">
                            <i class="fa-solid fa-eye password-toggle" onclick="togglePassword('db_pass', this)"></i>
                        </div>
                        <div class="form-text mt-2 small text-muted">Leave blank if your local setup does not use a password.</div>
                    </div>
                </div>

                <!-- Admin Account -->
                <h4 class="section-title"><i class="fa-solid fa-user-shield text-primary"></i> Administrator Account</h4>
                <div class="mb-4">
                    <label class="form-label">Admin Email</label>
                    <input type="email" name="admin_email" class="form-control" value="<?php echo htmlspecialchars($_POST['admin_email'] ?? ''); ?>" required>
                </div>
                <div class="row g-4 mb-5">
                    <div class="col-md-6">
                        <label class="form-label">Admin Password</label>
                        <div class="password-container">
                            <input type="password" name="admin_pass" id="admin_pass" class="form-control" required minlength="6">
                            <i class="fa-solid fa-eye password-toggle" onclick="togglePassword('admin_pass', this)"></i>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Confirm Password</label>
                        <div class="password-container">
                            <input type="password" name="confirm_pass" id="confirm_pass" class="form-control" required minlength="6">
                            <i class="fa-solid fa-eye password-toggle" onclick="togglePassword('confirm_pass', this)"></i>
                        </div>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary" id="submitBtn">
                    <i class="fa-solid fa-rocket me-2"></i> Install & Setup Database
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    function togglePassword(inputId, iconElement) {
        const input = document.getElementById(inputId);
        if (input.type === "password") {
            input.type = "text";
            iconElement.classList.remove('fa-eye');
            iconElement.classList.add('fa-eye-slash');
        } else {
            input.type = "password";
            iconElement.classList.remove('fa-eye-slash');
            iconElement.classList.add('fa-eye');
        }
    }

    // Basic frontend validation match
    document.getElementById('installForm')?.addEventListener('submit', function(e) {
        const pass = document.getElementById('admin_pass').value;
        const confirm = document.getElementById('confirm_pass').value;
        if(pass !== confirm) {
            e.preventDefault();
            alert("Admin passwords do not match!");
        } else {
            document.getElementById('submitBtn').innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Installing...';
            document.getElementById('submitBtn').disabled = true;
        }
    });
</script>

</body>
</html>