<?php
$conn = new mysqli('localhost', 'root', '', '');
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);

$sql = file_get_contents(__DIR__ . '/database.sql');

// Split by semicolon and run each statement
$statements = array_filter(array_map('trim', explode(';', $sql)));
$errors = [];
$success = 0;

foreach ($statements as $stmt) {
    if (empty($stmt)) continue;
    if ($conn->query($stmt)) {
        $success++;
    } else {
        $errors[] = htmlspecialchars($conn->error) . '<br><small>' . htmlspecialchars(substr($stmt, 0, 80)) . '...</small>';
    }
}

// Add account_status column if it doesn't exist (for existing installs)
$conn->query("ALTER TABLE lostfound_db.users ADD COLUMN IF NOT EXISTS account_status ENUM('pending','active','rejected') DEFAULT 'pending'");
$conn->query("ALTER TABLE lostfound_db.users ADD COLUMN IF NOT EXISTS google_id VARCHAR(100) DEFAULT NULL");
$conn->query("ALTER TABLE lostfound_db.users ADD COLUMN IF NOT EXISTS avatar VARCHAR(255) DEFAULT NULL");
$conn->query("ALTER TABLE lostfound_db.users MODIFY COLUMN password VARCHAR(255) NULL");
$conn->query("ALTER TABLE lostfound_db.found_items ADD COLUMN IF NOT EXISTS finder_photo VARCHAR(255) DEFAULT NULL");
$conn->query("INSERT IGNORE INTO lostfound_db.settings (setting_key,setting_value) VALUES ('google_client_id','')");
$conn->query("INSERT IGNORE INTO lostfound_db.settings (setting_key,setting_value) VALUES ('google_client_secret','')");
// Always ensure admin accounts are active
$conn->query("UPDATE lostfound_db.users SET account_status='active' WHERE role='admin'");
$conn->close();
?>
<!DOCTYPE html>
<html>
<head><title>RELINK Installer</title>
<style>body{font-family:sans-serif;max-width:700px;margin:40px auto;padding:20px}.ok{color:green}.err{color:red;background:#fee2e2;padding:8px;border-radius:4px;margin:4px 0;font-size:13px}</style>
</head>
<body>
<h2>🔗 RELINK - Database Installer</h2>
<?php if(empty($errors)): ?>
<p class="ok">✅ Database installed successfully! <?= $success ?> statements executed.</p>
<p><a href="/lostfound_relink/index.php">→ Go to RELINK</a></p>
<?php else: ?>
<p class="ok">✅ <?= $success ?> statements executed.</p>
<p class="err">⚠️ <?= count($errors) ?> error(s):</p>
<?php foreach($errors as $e): ?><div class="err"><?= $e ?></div><?php endforeach; ?>
<p><a href="/lostfound_relink/index.php">→ Go to RELINK anyway</a></p>
<?php endif; ?>
<p style="color:#999;font-size:12px;margin-top:20px">⚠️ Delete this file after installation.</p>
</body>
</html>
