<?php
require_once dirname(__DIR__) . '/api/konak.php';

$errors = [];
$success = [];

// Create admin_users table
$sql1 = "CREATE TABLE IF NOT EXISTS admin_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)";
if (mysqli_query($koneksi, $sql1)) $success[] = "Table admin_users OK";
else $errors[] = "admin_users: " . mysqli_error($koneksi);

// Create admin_settings table (SMTP + app settings)
$sql2 = "CREATE TABLE IF NOT EXISTS admin_settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(100) NOT NULL UNIQUE,
    setting_value TEXT,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if (mysqli_query($koneksi, $sql2)) $success[] = "Table admin_settings OK";
else $errors[] = "admin_settings: " . mysqli_error($koneksi);

// Insert default SMTP settings if not exist
$defaults = [
    'smtp_host'       => 'smtp.gmail.com',
    'smtp_port'       => '587',
    'smtp_username'   => '',
    'smtp_password'   => '',
    'smtp_encryption' => 'tls',
    'smtp_from_email' => '',
    'smtp_from_name'  => 'System',
    'site_name'       => 'Admin Panel',
];
foreach ($defaults as $k => $v) {
    $k = mysqli_real_escape_string($koneksi, $k);
    $v = mysqli_real_escape_string($koneksi, $v);
    mysqli_query($koneksi, "INSERT IGNORE INTO admin_settings (setting_key, setting_value) VALUES ('$k','$v')");
}
$success[] = "Default settings inserted";

// Insert default admin user (admin / admin123) - change after first login!
$defaultPass = password_hash('admin123', PASSWORD_BCRYPT);
$q = mysqli_query($koneksi, "SELECT id FROM admin_users WHERE username='admin'");
if (mysqli_num_rows($q) == 0) {
    $dp = mysqli_real_escape_string($koneksi, $defaultPass);
    if (mysqli_query($koneksi, "INSERT INTO admin_users (username,password) VALUES ('admin','$dp')"))
        $success[] = "Default admin created (user: admin / pass: admin123)";
    else $errors[] = "Admin user: " . mysqli_error($koneksi);
} else {
    $success[] = "Admin user already exists";
}
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Setup</title>
<style>body{font-family:sans-serif;max-width:600px;margin:40px auto;padding:20px}
.ok{color:#16a34a}.er{color:#dc2626}pre{background:#f3f4f6;padding:15px;border-radius:8px}</style>
</head><body>
<h2>🔧 Admin Panel Setup</h2>
<?php foreach($success as $s): ?><p class="ok">✓ <?= htmlspecialchars($s) ?></p><?php endforeach; ?>
<?php foreach($errors as $e): ?><p class="er">✗ <?= htmlspecialchars($e) ?></p><?php endforeach; ?>
<hr>
<p>✅ Setup complete! <a href="index.php">Go to Admin Login</a></p>
<p style="color:#ef4444"><strong>⚠ Delete this file (setup.php) after first use!</strong></p>
</body></html>
