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

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';

try {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Login required.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $auth = new Auth($conn);
    $role = strtolower((string)($_SESSION['role'] ?? ''));
    if (!in_array($role, ['admin', 'super_admin', 'warehouse'], true) && !$auth->isSuperAdmin($_SESSION['user_id']) && !$auth->isWarehousePersonnel($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized.']);
        exit;
    }

    $q = trim((string)($_GET['q'] ?? ''));
    if (mb_strlen($q) < 2) {
        echo json_encode(['success' => true, 'products' => []]);
        exit;
    }

    $like = '%' . $q . '%';
    $stmt = $conn->prepare("
        SELECT msp.product_code, msp.product_name, msp.description, msp.price,
               msp.unit_of_measure, msp.tax_rate_id, msp.levy_rate_id, msp.is_product,
               msp.site_id, met.terminal_label
        FROM mra_eis_site_products msp
        LEFT JOIN mra_eis_terminals met ON met.id = msp.terminal_local_id
        WHERE msp.product_code LIKE :q1 OR msp.product_name LIKE :q2 OR msp.description LIKE :q3
        ORDER BY msp.product_name ASC
        LIMIT 25
    ");
    $stmt->execute([':q1' => $like, ':q2' => $like, ':q3' => $like]);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'products' => $products]);
} catch (Throwable $e) {
    error_log('MRA EIS product search failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Unable to search MRA EIS products.']);
}
