<?php
// cms_migration.php
require_once 'config.php';

echo "<h2>SaniBook CMS Migration</h2>";

if (!$conn) {
    die("<p style='color:red'>Error: Database connection failed.</p>");
}

// 1. Create users table
$sql_users = "CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    org_name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if ($conn->query($sql_users)) {
    echo "<p style='color:green'>✓ Users table verified/created.</p>";
} else {
    die("<p style='color:red'>Error creating users table: " . $conn->error . "</p>");
}

// 2. Create content table
$sql_content = "CREATE TABLE IF NOT EXISTS content (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    category_id INT NOT NULL,
    type ENUM('story', 'chronicle') NOT NULL,
    title VARCHAR(255) NOT NULL,
    body MEDIUMTEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (category_id) REFERENCES categories(id)
)";

if ($conn->query($sql_content)) {
    echo "<p style='color:green'>✓ Content table verified/created.</p>";
} else {
    die("<p style='color:red'>Error creating content table: " . $conn->error . "</p>");
}

// 3. Seed Default User
$org_name = "WaSHVoice";
$email = "admin@washvoice.org";
// Assuming a default secure password since none was provided. Using 'password123' hashed.
// In a real scenario, this would be more secure or prompted.
$password = password_hash("password123", PASSWORD_DEFAULT);

// Check if user exists
$check_user = $conn->prepare("SELECT id FROM users WHERE email = ?");
$check_user->bind_param("s", $email);
$check_user->execute();
$check_user->store_result();

if ($check_user->num_rows == 0) {
    $stmt = $conn->prepare("INSERT INTO users (org_name, email, password) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $org_name, $email, $password);
    if ($stmt->execute()) {
        echo "<p style='color:green'>✓ Default user 'WaSHVoice' created.</p>";
    } else {
        echo "<p style='color:red'>Error creating default user: " . $stmt->error . "</p>";
    }
} else {
    echo "<p style='color:blue'>i Default user 'WaSHVoice' already exists.</p>";
}

echo "<hr><p><b>Migration Complete.</b></p>";
?>
