<?php
// csr/ajax/get_available_technicians.php
require_once '../../config/database.php';
session_start();

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get available technicians (status_id = 1 for Available)
    $query = "SELECT t.id, 
                     CONCAT(t.first_name, ' ', t.last_name) as full_name, 
                     t.specialization,
                     t.phone_number,
                     t.email,
                     ts.status_name,
                     ts.color_code
              FROM technicians t
              LEFT JOIN technician_statuses ts ON t.status_id = ts.id
              WHERE t.is_active = 1 
                AND (t.status_id = 1 OR t.status_id IS NULL)  -- Available status
              ORDER BY t.first_name ASC";
    
    $stmt = $db->prepare($query);
    $stmt->execute();
    $technicians = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Also get technicians that are currently on break but might be available soon
    $query = "SELECT t.id, 
                     CONCAT(t.first_name, ' ', t.last_name) as full_name, 
                     t.specialization,
                     t.phone_number,
                     t.email,
                     ts.status_name,
                     ts.color_code
              FROM technicians t
              LEFT JOIN technician_statuses ts ON t.status_id = ts.id
              WHERE t.is_active = 1 
                AND t.status_id = 3  -- Break status
              ORDER BY t.first_name ASC
              LIMIT 5";
    
    $stmt = $db->prepare($query);
    $stmt->execute();
    $technicians_on_break = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'technicians' => $technicians,
        'technicians_on_break' => $technicians_on_break
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>