<?php
declare(strict_types=1);

if (!function_exists('db')) {
  function db(): PDO {
    static $pdo = null;
    if ($pdo instanceof PDO) return $pdo;

    // قيَم الاستضافة الصحيحة
    $DB_HOST = getenv('DB_HOST') ?: 'localhost';
    $DB_NAME = getenv('DB_NAME') ?: 'alzaahra_alkindi';
    $DB_USER = getenv('DB_USER') ?: 'alzaahra_alkindi';
    $DB_PASS = getenv('DB_PASS') ?: 'Bqay@536696';
    $DB_CHAR = 'utf8mb4';

    $dsn = "mysql:host={$DB_HOST};dbname={$DB_NAME};charset={$DB_CHAR}";
    $opt = [
      PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
      PDO::ATTR_EMULATE_PREPARES   => false,
    ];

    try {
      $pdo = new PDO($dsn, $DB_USER, $DB_PASS, $opt);
      return $pdo;
    } catch (Throwable $e) {
      error_log('DB connect failed: '.$e->getMessage());
      http_response_code(500);
      exit('Database connection error.');
    }
  }
}
