<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (empty($_SESSION['user_id'])) {
    http_response_code(403);
    header('Content-Type: application/json');
    echo json_encode(['ok' => false, 'error' => 'Unauthorized']);
    exit;
}

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

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

$isAdmin  = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id']);
$branchId = $isAdmin ? null : $auth->getUserBranch($_SESSION['user_id']);

header('Content-Type: application/json; charset=utf-8');

$logger  = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$service = null;
try {
    $service = new CustomerService($conn, $logger);
} catch (Throwable $e) {
    echo json_encode(['ok' => false, 'error' => 'Service error: ' . $e->getMessage()]);
    exit;
}

$action = trim($_GET['action'] ?? '');

if ($action === 'customer_search') {
    $q = trim($_GET['q'] ?? '');
    if (strlen($q) < 2) {
        echo json_encode(['ok' => false, 'error' => 'Enter at least 2 characters to search.']);
        exit;
    }
    try {
        $results = $service->findSalesByCustomerName($q, $branchId);
        echo json_encode(['ok' => true, 'results' => $results]);
    } catch (Throwable $e) {
        echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

echo json_encode(['ok' => false, 'error' => 'Unknown action.']);
