<?php
declare(strict_types=1);

/**
 * LaporanWee shared API configuration.
 * Install as: public_html/api/config.php
 * This file is shared by all API modules.
 */

date_default_timezone_set('Asia/Jakarta');
error_reporting(0);
ini_set('display_errors', '0');

/* CORS */
$allowedOrigins = [
    'https://laporanwe.mkverse.my.id',
    'http://laporanwe.mkverse.my.id',
    'http://localhost:5173',
    'http://127.0.0.1:5173',
];

$requestOrigin = $_SERVER['HTTP_ORIGIN'] ?? '';

if ($requestOrigin !== '' && in_array($requestOrigin, $allowedOrigins, true)) {
    header('Access-Control-Allow-Origin: ' . $requestOrigin);
    header('Vary: Origin');
}

header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Accept, X-Auth-Token, X-Admin-Email');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Max-Age: 86400');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store');

/* Finish preflight before opening a database connection. */
if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

/* Shared JSON helper retained for existing API endpoints. */
if (!function_exists('response')) {
    function response(array $data, int $status = 200): void
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(
            $data,
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
        );
        exit;
    }
}

/* Database credentials: fill in the values from your hosting panel. */
$host = 'localhost';
$db   = 'mkversem_laporanwee';
$user = 'mkversem_laporanadmin';
$pass = 'Saragihjj';

try {
    $pdo = new PDO(
        "mysql:host={$host};dbname={$db};charset=utf8mb4",
        $user,
        $pass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
        ]
    );
} catch (Throwable $e) {
    error_log('[LaporanWee Database] ' . $e->getMessage());
    response([
        'success' => false,
        'message' => 'Database connection failed',
    ], 500);
}
