<?php
/**
 * Drop this file at: api/erp/erp_auth.php inside the MJPOS project root
 * (same level as the `app`, `config`, `public`, `storage` folders).
 *
 * IMPORTANT: Set ERP_API_KEY below to a long random string, then enter the
 * SAME value in MJ ERP Hub > Settings > MJPOS > API Key field.
 */

define('ERP_API_KEY', 'Kx9mP2vLq8wR4tZ7nB3jF6hD1yG5sA0c');

header('Content-Type: application/json');

function erp_require_auth() {
    $headers = function_exists('getallheaders') ? getallheaders() : [];
    $key = $headers['X-Api-Key']
        ?? $headers['X-API-Key']
        ?? $_SERVER['HTTP_X_API_KEY']
        ?? null;

    if (!$key || !hash_equals(ERP_API_KEY, $key)) {
        http_response_code(401);
        echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
        exit;
    }
}

function erp_json_success($data) {
    echo json_encode(['status' => 'success', 'data' => $data]);
    exit;
}

function erp_json_error($message, $code = 400) {
    http_response_code($code);
    echo json_encode(['status' => 'error', 'message' => $message]);
    exit;
}

function erp_get_date_range() {
    $from = $_GET['from'] ?? date('Y-m-d', strtotime('-7 days'));
    $to = $_GET['to'] ?? date('Y-m-d');
    return [$from, $to];
}

/**
 * MJPOS's config.php only defines DB_HOST / DB_NAME / DB_USER / DB_PASS constants -
 * it does NOT expose a getDB() function. So we open our own independent PDO
 * connection here using those same constants, without touching MJPOS's internals.
 */
function erp_pdo() {
    static $pdo = null;
    if ($pdo === null) {
        try {
            $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . (defined('DB_CHARSET') ? DB_CHARSET : 'utf8mb4');
            $pdo = new PDO($dsn, DB_USER, DB_PASS, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]);
        } catch (PDOException $e) {
            erp_json_error('DB connection failed: ' . $e->getMessage(), 500);
        }
    }
    return $pdo;
}
