<?php
declare(strict_types=1);

/**
 * /public_html/test_erp/api/_core.php
 * Core API bootstrap — TEST environment
 * Updated: 2026-07-22
 */

ini_set('display_errors', '0');
error_reporting(E_ALL);

require_once __DIR__ . '/../config/session.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/response.php';
require_once __DIR__ . '/_csrf_guard.php';

/**
 * False = compatibility mode: missing token is allowed only when the browser
 * proves the request is same-origin. Supplied invalid tokens are rejected.
 * Change to true only after erp_csrf.js is loaded on every write-capable page.
 */
if (!defined('ERP_CSRF_STRICT')) {
    define('ERP_CSRF_STRICT', false);
}

// Automatically protects POST/PUT/PATCH/DELETE APIs that include _core.php.
erp_csrf_required(!ERP_CSRF_STRICT);

function cors_headers(): void
{
    $origin = (string)($_SERVER['HTTP_ORIGIN'] ?? '');
    $allowed = [
        'https://test.jewellersbd.com',
        'https://rs2026.thefirstserver.com',
        'http://test.jewellersbd.com',
        'http://rs2026.thefirstserver.com',
    ];

    if ($origin !== '' && in_array($origin, $allowed, true)) {
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Expose-Headers: X-CSRF-Token');
    }

    header('Content-Type: application/json; charset=UTF-8');
    header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-CSRF-Token');
    header('Vary: Origin');

    if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? '')) === 'OPTIONS') {
        http_response_code(200);
        echo json_encode([
            'status'  => true,
            'success' => true,
            'message' => 'preflight ok',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

function db_connect()
{
    global $conn;
    return $conn;
}

function respond($status, $message, $data = null, $http = 200): void
{
    http_response_code((int)$http);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode([
        'status'  => (bool)$status,
        'success' => (bool)$status,
        'message' => $message,
        'data'    => $data,
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

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