<?php
// csr/ajax/update_technician_status.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();
}

$technician_id = isset($_POST['technician_id']) ? (int)$_POST['technician_id'] : 0;
$status_id = isset($_POST['status_id']) ? (int)$_POST['status_id'] : 0;
$notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';

if (!$technician_id || !$status_id) {
    echo json_encode(['success' => false, 'message' => 'Missing technician or status.']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();

    $query = "SELECT id FROM technician_statuses WHERE id = :status_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':status_id', $status_id);
    $stmt->execute();

    if (!$stmt->fetch(PDO::FETCH_ASSOC)) {
        echo json_encode(['success' => false, 'message' => 'Invalid technician status.']);
        exit();
    }

    $query = "UPDATE technicians SET status_id = :status_id WHERE id = :technician_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':status_id', $status_id);
    $stmt->bindParam(':technician_id', $technician_id);
    $stmt->execute();

    echo json_encode(['success' => true, 'message' => 'Technician status updated successfully.']);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Failed to update technician status: ' . $e->getMessage()]);
}
?>
