<?php
/**
 * Database Setup Script
 * Run this to create the database if it doesn't exist
 */

// Database configuration
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'ruhondo_hms';

echo "<h1>Database Setup</h1>";

try {
    // Connect without database selected
    $pdo = new PDO("mysql:host=$db_host", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "<p>Connected to MySQL successfully</p>";
    
    // Check if database exists
    $stmt = $pdo->query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$db_name'");
    $db_exists = $stmt->fetch();
    
    if (!$db_exists) {
        // Create database
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        echo "<p style='color: green'>✓ Database '$db_name' created successfully</p>";
        
        // Select the database
        $pdo->exec("USE `$db_name`");
        
        // You can add your SQL dump here or import from file
        echo "<p>Now you need to import your database schema</p>";
        echo "<p>Run: mysql -u root -p $db_name < your_database_dump.sql</p>";
        
    } else {
        echo "<p style='color: green'>✓ Database '$db_name' already exists</p>";
    }
    
    // Test connection to the database
    $pdo->exec("USE `$db_name`");
    $tables = $pdo->query("SHOW TABLES")->fetchAll();
    echo "<p>Found " . count($tables) . " tables in database</p>";
    
} catch (PDOException $e) {
    echo "<p style='color: red'>Error: " . $e->getMessage() . "</p>";
}