<?php
/**
 * Medicus POC - Database & App Configuration
 * Update the constants below with your cPanel MySQL details.
 * In cPanel these are usually prefixed, e.g. cpaneluser_medicus
 */

define('DB_HOST', 'localhost');
define('DB_NAME', 'medicus_poc');
define('DB_USER', 'root');
define('DB_PASS', '');

function get_db(): PDO
{
    static $pdo = null;
    if ($pdo === null) {
        $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
        $pdo = new PDO($dsn, DB_USER, DB_PASS, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
    }
    return $pdo;
}

// ---- Common headers for a JSON API served same-origin from cPanel ----
// If you serve the frontend from a different subdomain, replace '*' with
// that exact origin and set Access-Control-Allow-Credentials: true.
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

session_set_cookie_params([
    'lifetime' => 60 * 60 * 8,
    'path' => '/',
    'samesite' => 'Lax',
]);
session_start();

function json_input(): array
{
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function respond($data, int $status = 200): void
{
    http_response_code($status);
    echo json_encode($data);
    exit;
}

function require_auth(): array
{
    if (empty($_SESSION['user_id'])) {
        respond(['error' => 'Not authenticated'], 401);
    }
    return [
        'id' => $_SESSION['user_id'],
        'username' => $_SESSION['username'],
        'name' => $_SESSION['name'],
        'role' => $_SESSION['role'],
    ];
}
