<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Setup extends Controller
{
    public function index()
    {
        // We will connect using raw mysqli to create the database if it doesn't exist
        $host = 'localhost';
        $user = 'devamsproteamco_booking';
        $pass = 'n?p=C@ziAP2HlRvJ'; 

        try {
            // First, connect without a specific database
            $conn = new \mysqli($host, $user, $pass);
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error . "<br>Please ensure MySQL is running (e.g., via XAMPP).");
            }

            // Create database (cPanel usually already has it, ignoring error if exists)
            $sql = "CREATE DATABASE IF NOT EXISTS `devamsproteamco_booking`";
            $conn->query($sql);

            // Select the database
            $conn->select_db('devamsproteamco_booking');

            // Read the SQL file we generated earlier
            $sqlFile = FCPATH . '../database.sql';
            if (!file_exists($sqlFile)) {
                die("SQL file not found at " . $sqlFile);
            }

            $query = file_get_contents($sqlFile);
            
            // Execute multi query
            if ($conn->multi_query($query)) {
                do {
                    // Store first result set
                    if ($result = $conn->store_result()) {
                        $result->free();
                    }
                } while ($conn->more_results() && $conn->next_result());
                echo "<div style='color:green; padding: 10px; font-family: sans-serif; font-weight: bold;'>Database Schema and Demo Data imported successfully!</div>";
                echo "<a href='" . base_url() . "' style='display:inline-block; padding: 10px 20px; background: #0d6efd; color: white; text-decoration: none; border-radius: 5px; font-family: sans-serif; margin-top: 10px;'>Go to Home Page</a>";
            } else {
                echo "Error executing SQL: " . $conn->error;
            }

            $conn->close();

        } catch (\Exception $e) {
            echo "An error occurred: " . $e->getMessage();
        }
    }
}
