<?php
define('DB_HOST',    'localhost');
define('DB_NAME',    'storism1_tahwisa_db');
define('DB_USER',    'storism1_tahwisauser');
define('DB_PASS',    'tahwisapassword');
define('DB_CHARSET', 'utf8mb4');

define('UPLOAD_DIR', __DIR__ . '/../uploads/');
define('UPLOAD_URL', 'uploads/');

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,
            ]);
        } catch (PDOException $e) {
            http_response_code(503);
            die('<!DOCTYPE html><html dir="rtl" lang="ar"><head><meta charset="UTF-8"><title>خطأ</title>
<style>body{font-family:Cairo,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#f5f0e8}
.b{background:#fff;padding:40px;border-radius:16px;text-align:center;box-shadow:0 4px 24px rgba(0,0,0,.1);max-width:480px}
h2{color:#c0392b}code{background:#f8f8f8;padding:4px 8px;border-radius:6px;font-size:.85rem}</style>
</head><body><div class="b"><h2>⚠️ خطأ في قاعدة البيانات</h2>
<p>تعذّر الاتصال. تحقق من <code>config/db.php</code></p>
<p style="font-size:.8rem;color:#999">DB: <code>' . DB_NAME . '</code></p>
</div></body></html>');
        }
    }
    return $pdo;
}

function upload_image(string $field, string $subfolder = 'places'): ?string {
    if (empty($_FILES[$field]['tmp_name'])) return null;
    $file = $_FILES[$field];
    $allowed = ['image/jpeg','image/png','image/webp','image/gif'];
    if (!in_array($file['type'], $allowed)) return null;
    if ($file['size'] > 5 * 1024 * 1024) return null;
    $ext  = pathinfo($file['name'], PATHINFO_EXTENSION);
    $name = uniqid($subfolder . '_', true) . '.' . $ext;
    $dir  = UPLOAD_DIR . $subfolder . '/';
    if (!is_dir($dir)) mkdir($dir, 0775, true);
    if (move_uploaded_file($file['tmp_name'], $dir . $name)) {
        return UPLOAD_URL . $subfolder . '/' . $name;
    }
    return null;
}
