<?php
// csr/ajax/get_requests.php
require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';
session_start();

if (!isset($_SESSION['csr_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$database = new Database();
$db = $database->getConnection();
ensureCsrTeamTables($db);
$scopeParams = [];
$visibilitySql = buildCsrRequestVisibilitySql($db, (int)$_SESSION['csr_id'], 'sr', $scopeParams, 'recent_scope');

// For recent requests in dashboard, we want to show latest 5-10 records
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;

// Get recent requests - MODIFIED to handle manual entries
$query = "SELECT sr.id, sr.request_number, sr.full_name, sr.requested_at,
            js.status_name, js.color_code as status_color,
            CASE 
                WHEN sr.appliance_type_id IS NULL THEN sr.manual_appliance_type 
                ELSE at.name 
            END as appliance_type,
            CASE 
                WHEN sr.brand_id IS NULL THEN sr.manual_brand 
                ELSE b.name 
            END as brand,
            -- Add flags for manual entries
            CASE WHEN sr.brand_id IS NULL THEN 1 ELSE 0 END as is_manual_brand,
            CASE WHEN sr.appliance_type_id IS NULL THEN 1 ELSE 0 END as is_manual_appliance
          FROM service_requests sr
          LEFT JOIN job_statuses js ON sr.job_status_id = js.id
          LEFT JOIN appliance_types at ON sr.appliance_type_id = at.id
          LEFT JOIN brands b ON sr.brand_id = b.id
          WHERE $visibilitySql
          ORDER BY sr.requested_at DESC
          LIMIT :limit";

$stmt = $db->prepare($query);
foreach ($scopeParams as $key => $value) {
    $stmt->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();

$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'success' => true,
    'recent_requests' => $requests
]);
?>