<?php
// This script is for one-time setup only. DELETE IT AFTER USE.
error_reporting(E_ALL);
ini_set('display_errors', 1);

include_once 'config/Database.php';

echo "--- Starting Database Initialization ---\n";

$database = new Database();
$db = $database->connect();

if (!$db) {
    die("Database connection failed. Please check your config/Database.php file.\n");
}

// Table Creation Queries
$queries = [
    "DROP TABLE IF EXISTS messages, contents, users;",
    "CREATE TABLE users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(255) NOT NULL UNIQUE,
        password VARCHAR(255) NOT NULL,
        role ENUM('admin', 'staff') DEFAULT 'staff',
        createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=INNODB;",
    "CREATE TABLE contents (
        section VARCHAR(255) PRIMARY KEY,
        data JSON NOT NULL,
        updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=INNODB;",
    "CREATE TABLE messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(255) NOT NULL,
        message TEXT NOT NULL,
        status ENUM('unread', 'read', 'archived') DEFAULT 'unread',
        createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=INNODB;"
];

// Execute Table Creation
foreach ($queries as $query) {
    try {
        $db->exec($query);
        echo "Successfully executed query: " . substr($query, 0, 40) . "...\n";
    } catch (PDOException $e) {
        die("Error executing query: " . $e->getMessage() . "\n");
    }
}
echo "--- Tables created successfully ---\n";

// Seed Admin User
$adminEmail = 'admin@salene.co.ke';
$adminPass = password_hash('adminpassword', PASSWORD_DEFAULT);
$adminName = 'Admin User';

$stmt = $db->prepare("INSERT INTO users (name, email, password, role) VALUES (?, ?, ?, 'admin')");
if ($stmt->execute([$adminName, $adminEmail, $adminPass])) {
    echo "--- Admin user created successfully ---\n";
} else {
    echo "--- Failed to create admin user ---\n";
}

// Seed Content
$seedDir = __DIR__ . '/data_for_seed';
$files = scandir($seedDir);
$seedCount = 0;
foreach ($files as $file) {
    if (pathinfo($file, PATHINFO_EXTENSION) === 'json') {
        $section = pathinfo($file, PATHINFO_FILENAME);
        $data = file_get_contents($seedDir . '/' . $file);
        
        $stmt = $db->prepare("INSERT INTO contents (section, data) VALUES (?, ?)");
        if ($stmt->execute([$section, $data])) {
            $seedCount++;
        }
    }
}
echo "--- Seeded " . $seedCount . " content sections successfully ---\n";
echo "--- Initialization Complete. REMEMBER TO DELETE THIS FILE! ---\n";
?>