<?php
/**
 * Central Database Configuration for Multi-School Setup
 * This file handles connection to the central settings database
 * and manages school branch configurations
 */

// Central database configuration
define('CENTRAL_DB_HOST', 'localhost');
define('CENTRAL_DB_NAME', 'lwmacade_school_central_settings');
define('CENTRAL_DB_USER', 'lwmacade_school_central_settings'); // Change this to your database user
define('CENTRAL_DB_PASS', '@Word22*#'); // Change this to your database password

try {
    // Connect to central database
    $CENTRAL_DB = new PDO(
        "mysql:host=" . CENTRAL_DB_HOST . ";dbname=" . CENTRAL_DB_NAME . ";charset=utf8mb4",
        CENTRAL_DB_USER,
        CENTRAL_DB_PASS,
        array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        )
    );
} catch(PDOException $e) {
    die("Central Database Connection Failed: " . $e->getMessage());
}

/**
 * Get school branch settings by branch code
 * @param string $branchCode The branch code (e.g., '92ik', 'onye')
 * @return array|false School settings or false if not found
 */
function getSchoolSettings($branchCode) {
    global $CENTRAL_DB;
    
    $stmt = $CENTRAL_DB->prepare("SELECT * FROM school_branches WHERE branch_code = ? AND is_active = 1");
    $stmt->execute([$branchCode]);
    return $stmt->fetch();
}

/**
 * Get system setting by key
 * @param string $key The setting key
 * @return string|false Setting value or false if not found
 */
function getSystemSetting($key) {
    global $CENTRAL_DB;
    
    $stmt = $CENTRAL_DB->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    $result = $stmt->fetch();
    return $result ? $result['setting_value'] : false;
}

/**
 * Get all active school branches
 * @return array List of all active branches
 */
function getAllBranches() {
    global $CENTRAL_DB;
    
    $stmt = $CENTRAL_DB->query("SELECT * FROM school_branches WHERE is_active = 1 ORDER BY branch_name");
    return $stmt->fetchAll();
}

/**
 * Connect to specific school database
 * @param string $branchCode The branch code
 * @return PDO|false PDO connection or false on failure
 */
function connectSchoolDB($branchCode) {
    $settings = getSchoolSettings($branchCode);
    if (!$settings) {
        return false;
    }
    
    try {
        $schoolDB = new PDO(
            "mysql:host=" . CENTRAL_DB_HOST . ";dbname=" . $settings['database_name'] . ";charset=utf8mb4",
            CENTRAL_DB_USER,
            CENTRAL_DB_PASS,
            array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
            )
        );
        return $schoolDB;
    } catch(PDOException $e) {
        error_log("School Database Connection Failed for {$branchCode}: " . $e->getMessage());
        return false;
    }
}

/**
 * Get current branch code from URL or session
 * @return string|null Branch code or null if not found
 */
function getCurrentBranchCode() {
    // Check if branch is set in URL (e.g., ?branch=92ik)
    if (isset($_GET['branch']) && !empty($_GET['branch'])) {
        $_SESSION['current_branch'] = $_GET['branch'];
        return $_GET['branch'];
    }
    
    // Check if branch is set in session
    if (isset($_SESSION['current_branch']) && !empty($_SESSION['current_branch'])) {
        return $_SESSION['current_branch'];
    }
    
    // Try to determine from hostname/subdomain
    $host = $_SERVER['HTTP_HOST'];
    if (strpos($host, '92ik.') === 0) {
        return '92ik';
    } elseif (strpos($host, 'onye.') === 0) {
        return 'onye';
    }
    
    // Default to first active branch or null
    $branches = getAllBranches();
    return !empty($branches) ? $branches[0]['branch_code'] : null;
}

// Initialize current school settings if branch is available
$currentBranchCode = getCurrentBranchCode();
$schoolSettings = $currentBranchCode ? getSchoolSettings($currentBranchCode) : null;

// If school settings found, define constants for easy access
if ($schoolSettings) {
    define('SCHOOL_BRANCH_CODE', $schoolSettings['branch_code']);
    define('SCHOOL_BRANCH_NAME', $schoolSettings['branch_name']);
    define('SCHOOL_BRANCH_ADDRESS', $schoolSettings['branch_address']);
    define('SCHOOL_SHORT_NAME', $schoolSettings['branch_short_name']);
    define('SCHOOL_MOTTO', $schoolSettings['school_motto']);
    define('SCHOOL_LOGO', $schoolSettings['school_logo_path']);
    define('SCHOOL_FAVICON', $schoolSettings['school_favicon_path'] ?: $schoolSettings['school_logo_path']);
    define('SCHOOL_PHONE', $schoolSettings['contact_phone']);
    define('SCHOOL_EMAIL', $schoolSettings['contact_email']);
    define('SCHOOL_WEBSITE', $schoolSettings['website_url']);
    define('RESULT_PORTAL_URL', $schoolSettings['result_portal_url']);
    define('FOOTER_TEXT', $schoolSettings['footer_text']);
    define('FOOTER_COPYRIGHT', $schoolSettings['footer_copyright']);
    define('SCHOOL_DATABASE', $schoolSettings['database_name']);
    
    // Connect to the school's specific database
    $SCHOOL_DB = connectSchoolDB($currentBranchCode);
}

// Get system-wide settings
define('SUPPORT_PHONE', getSystemSetting('support_phone'));
define('SUPPORT_EMAIL', getSystemSetting('support_email'));
define('DEVELOPER_NAME', getSystemSetting('developer_name'));
define('DEVELOPER_WEBSITE', getSystemSetting('developer_website'));
?>