<?php
// config/database.php
define('DB_HOST',    'localhost');
define('DB_NAME',    'storism1_kadyati.dz');
define('DB_USER',    'storism1_lawyer');
define('DB_PASS',    'Lawyer4321');
define('DB_CHARSET', 'utf8mb4');

function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', DB_HOST, DB_NAME, DB_CHARSET);
        try {
            $pdo = new PDO($dsn, DB_USER, DB_PASS, [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
            ]);
        } catch (PDOException $e) {
            error_log('[DB ERROR] ' . $e->getMessage());
            http_response_code(500);
            die(json_encode(['error' => 'فشل الاتصال بقاعدة البيانات'], JSON_UNESCAPED_UNICODE));
        }
    }
    return $pdo;
}
