<?php
// ============================================
// BAITARI (Vet-Net) Platform - Config
// NameHero Shared Hosting
// ============================================

define('DB_HOST',    'localhost');
define('DB_NAME',    'storism1_vet-net_db');
define('DB_USER',    'storism1_vet-net_user');
define('DB_PASS',    'vetnetpassword');
define('DB_CHARSET', 'utf8mb4');

define('APP_NAME',    'بيطري');
define('APP_URL',     'https://baitari.storismo.com');
define('APP_VERSION', '1.0.0');

define('UPLOAD_PATH', __DIR__ . '/../uploads/');
define('UPLOAD_URL',  APP_URL . '/uploads/');
define('MAX_UPLOAD_MB', 5);

// Session
define('SESSION_NAME',     'vetnet_sess');
define('SESSION_LIFETIME',  86400 * 7); // 7 days

// ============================================
// Database connection (PDO singleton)
// ============================================
function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $dsn  = 'mysql:host=' . DB_HOST
              . ';dbname=' . DB_NAME
              . ';charset=' . DB_CHARSET;
        $opts = [
            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, $opts);
        } catch (PDOException $e) {
            http_response_code(500);
            die(json_encode(['error' => 'DB connection failed']));
        }
    }
    return $pdo;
}

// ============================================
// Session init
// ============================================
function session_start_secure(): void {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.cookie_samesite', 'Lax');
    session_name(SESSION_NAME);
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
}

// ============================================
// Auth helpers
// ============================================
function current_user(): ?array {
    session_start_secure();
    return $_SESSION['user'] ?? null;
}

function require_login(): array {
    $user = current_user();
    if (!$user) {
        if (is_api_request()) {
            json_response(['error' => 'Unauthorized'], 401);
        }
        header('Location: /login.php');
        exit;
    }
    return $user;
}

function require_role(string ...$roles): array {
    $user = require_login();
    if (!in_array($user['role'], $roles)) {
        if (is_api_request()) {
            json_response(['error' => 'Forbidden'], 403);
        }
        header('Location: /index.php');
        exit;
    }
    return $user;
}

// ============================================
// Response helpers
// ============================================
function json_response(array $data, int $code = 200): void {
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

function is_api_request(): bool {
    return (
        (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
            && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
        || str_contains($_SERVER['REQUEST_URI'] ?? '', '/api/')
    );
}

// ============================================
// Security helpers
// ============================================
function h(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}

function sanitize_int($v): int {
    return (int) filter_var($v, FILTER_SANITIZE_NUMBER_INT);
}

function sanitize_str($v, int $max = 255): string {
    return mb_substr(trim(strip_tags((string)$v)), 0, $max, 'UTF-8');
}

function csrf_token(): string {
    session_start_secure();
    if (empty($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf'];
}

function verify_csrf(string $token): bool {
    session_start_secure();
    return hash_equals($_SESSION['csrf'] ?? '', $token);
}

// ============================================
// Distance helper (Haversine formula)
// ============================================
function haversine_km(float $lat1, float $lng1, float $lat2, float $lng2): float {
    $R    = 6371;
    $dLat = deg2rad($lat2 - $lat1);
    $dLng = deg2rad($lng2 - $lng1);
    $a    = sin($dLat/2)**2
          + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLng/2)**2;
    return $R * 2 * atan2(sqrt($a), sqrt(1 - $a));
}
