<?php
// index.php

session_start();

require_once 'config/database.php';

// Dynamic timezone alignment with MySQL database
try {
    $db = getDB();
    $offsetRow = $db->query("SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP()) as offset")->fetch();
    if ($offsetRow) {
        $offset = $offsetRow['offset'];
        $parts = explode(':', $offset);
        $hours = intval($parts[0]);
        $minutes = intval($parts[1]);
        
        $offset_seconds = (abs($hours) * 3600 + $minutes * 60);
        if ($hours < 0) {
            $offset_seconds = -$offset_seconds;
        }
        
        $tz_name = timezone_name_from_abbr("", $offset_seconds, 0);
        if ($tz_name === false) {
            $tz_name = timezone_name_from_abbr("", $offset_seconds, 1);
        }
        if ($tz_name !== false) {
            date_default_timezone_set($tz_name);
        } else {
            $sign = $hours < 0 ? '+' : '-';
            $absHours = abs($hours);
            $timezone = "Etc/GMT" . $sign . $absHours;
            date_default_timezone_set($timezone);
        }
    }
} catch (\Exception $e) {
    date_default_timezone_set('UTC');
}

require_once 'app/Helpers/Router.php';

// Autoloader for simple MVC
spl_autoload_register(function ($class_name) {
    $directories = [
        'app/Controllers/',
        'app/Models/',
        'app/Helpers/',
        'app/Middleware/',
        'app/Services/'
    ];

    foreach ($directories as $directory) {
        if (file_exists($directory . $class_name . '.php')) {
            require_once $directory . $class_name . '.php';
            return;
        }
    }
});

// Load routes
require_once 'routes/web.php';

// Dispatch
Router::dispatch($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);
