<?php
namespace App\Core;

use PDO;
use PDOException;

final class Database
{
    private static ?PDO $pdo = null;

    public static function connection(): PDO
    {
        if (self::$pdo instanceof PDO) {
            return self::$pdo;
        }

        $configPath = __DIR__ . '/../../config/app.php';
        if (!file_exists($configPath)) {
            $configPath = __DIR__ . '/../../config/app.example.php';
        }
        $config = require $configPath;
        $db = $config['database'];

        $dsn = sprintf(
            'mysql:host=%s;port=%s;dbname=%s;charset=%s',
            $db['host'],
            $db['port'],
            $db['name'],
            $db['charset']
        );

        try {
            self::$pdo = new PDO($dsn, $db['user'], $db['password'], [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);

            // Make MySQL NOW(), CURDATE(), timestamps and cron comparisons follow Lebanon time.
            // We use the current Asia/Beirut UTC offset because many shared hosts do not load
            // MySQL named timezone tables.
            try {
                $timezone = 'Asia/Beirut';
                date_default_timezone_set($timezone);
                $offset = (new \DateTimeImmutable('now', new \DateTimeZone($timezone)))->format('P');
                self::$pdo->prepare('SET time_zone = ?')->execute([$offset]);
            } catch (\Throwable $e) {
                // Do not break the app if a host blocks changing the session timezone.
            }
        } catch (PDOException $e) {
            http_response_code(500);
            header('Content-Type: application/json');
            echo json_encode([
                'ok' => false,
                'message' => 'Database connection failed. Check config/app.php.',
                'debug' => $e->getMessage(),
            ]);
            exit;
        }

        return self::$pdo;
    }
}
