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

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

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

$request_id = isset($_POST['request_id']) ? (int)$_POST['request_id'] : 0;
$technician_id = isset($_POST['technician_id']) ? (int)$_POST['technician_id'] : 0;
$estimated_arrival_time = isset($_POST['estimated_arrival_time']) ? $_POST['estimated_arrival_time'] : null;
$estimated_arrival_date = isset($_POST['estimated_arrival_date']) ? trim($_POST['estimated_arrival_date']) : '';
$estimated_arrival_period = isset($_POST['estimated_arrival_period']) ? trim($_POST['estimated_arrival_period']) : '';

if (!empty($estimated_arrival_date)) {
    $period_upper = strtoupper($estimated_arrival_period);
    $time_part = ($period_upper === 'PM' || strpos($period_upper, 'AFTERNOON') !== false) ? '13:00:00' : ((strpos($period_upper, 'EVENING') !== false) ? '17:00:00' : '09:00:00');
    $estimated_arrival_time = $estimated_arrival_date . ' ' . $time_part;
}
$assignment_notes = isset($_POST['assignment_notes']) ? trim($_POST['assignment_notes']) : '';
$assignment_type = isset($_POST['assignment_type']) ? $_POST['assignment_type'] : 'primary';

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

try {
    $database = new Database();
    $db = $database->getConnection();
    ensureRequestLockTable($db);
    ensureChatTables($db);
    ensureCsrTeamTables($db);
    ensureUnifiedTicketWorkflow($db);
    requireCsrRequestAccessJson($db, (int)$_SESSION['csr_id'], $request_id);
    
    // Start transaction
    $db->beginTransaction();
    
    // Check if technician is already assigned to this request
    $query = "SELECT id, status FROM service_assignments 
              WHERE request_id = :request_id AND technician_id = :technician_id 
              AND status IN ('assigned', 'en_route', 'on_site')";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':request_id', $request_id);
    $stmt->bindParam(':technician_id', $technician_id);
    $stmt->execute();
    
    if ($stmt->rowCount() > 0) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => 'This technician is already assigned to this request.']);
        exit();
    }
    
    // Count existing active assignments for this request
    $query = "SELECT COUNT(*) as count FROM service_assignments 
              WHERE request_id = :request_id AND status IN ('assigned', 'en_route', 'on_site')";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':request_id', $request_id);
    $stmt->execute();
    $existing_assignments = $stmt->fetch(PDO::FETCH_ASSOC);
    $assignment_count = $existing_assignments['count'];
    
    // Determine assignment type based on count
    if ($assignment_count == 0) {
        $assignment_type = 'primary';
    } elseif ($assignment_count == 1) {
        $assignment_type = 'secondary';
    } else {
        $assignment_type = 'helper';
    }
    
    // Get CSR name
    $query = "SELECT CONCAT(first_name, ' ', last_name) as csr_name 
              FROM csr_users WHERE id = :csr_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':csr_id', $_SESSION['csr_id']);
    $stmt->execute();
    $csr = $stmt->fetch(PDO::FETCH_ASSOC);
    $csr_name = $csr ? $csr['csr_name'] : 'CSR';
    

    $lockResult = acquireRequestLock($db, $request_id, $_SESSION['csr_id'], $csr_name);
    if (!$lockResult['success']) {
        $db->rollBack();
        echo json_encode($lockResult);
        exit();
    }
    
    // Insert assignment
    $query = "INSERT INTO service_assignments 
              (request_id, technician_id, assigned_by, estimated_arrival_time, csr_notes, status, assignment_type, assigned_at) 
              VALUES 
              (:request_id, :technician_id, :assigned_by, :estimated_arrival, :notes, 'assigned', :assignment_type, NOW())";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':request_id', $request_id);
    $stmt->bindParam(':technician_id', $technician_id);
    $stmt->bindParam(':assigned_by', $_SESSION['csr_id']);
    $stmt->bindParam(':estimated_arrival', $estimated_arrival_time);
    $stmt->bindParam(':notes', $assignment_notes);
    $stmt->bindParam(':assignment_type', $assignment_type);
    $stmt->execute();
    $assignment_id = (int)$db->lastInsertId();
    
    // Update request status to 'Assigned' (job_status_id = 2) if it's the first assignment
    if ($assignment_count == 0) {
        $query = "UPDATE service_requests SET job_status_id = 2, last_updated_at = NOW() WHERE id = :request_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':request_id', $request_id);
        $stmt->execute();
    }
    
    // Mark technician as On Job
    $query = "UPDATE technicians SET status_id = 2 WHERE id = :technician_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':technician_id', $technician_id);
    $stmt->execute();

    // Get request details
    $query = "SELECT request_number, customer_id FROM service_requests WHERE id = :request_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':request_id', $request_id);
    $stmt->execute();
    $request = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get technician name
    $query = "SELECT CONCAT(first_name, ' ', last_name) as tech_name FROM technicians WHERE id = :technician_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':technician_id', $technician_id);
    $stmt->execute();
    $technician = $stmt->fetch(PDO::FETCH_ASSOC);
    $tech_name = $technician ? $technician['tech_name'] : 'Technician';
    
    // Determine role text
    $role_text = '';
    if ($assignment_type == 'primary') {
        $role_text = 'Lead Technician';
    } elseif ($assignment_type == 'secondary') {
        $role_text = 'Secondary Technician';
    } else {
        $role_text = 'Helper';
    }
    
    // Add status history (only for first assignment)
    if ($assignment_count == 0) {
        $history_notes = "Assigned to technician: {$tech_name} ({$role_text})";
        if (!empty($assignment_notes)) {
            $history_notes .= " - Notes: {$assignment_notes}";
        }
        
        $query = "INSERT INTO request_status_history 
                  (request_id, job_status_id, notes, changed_by, changed_at) 
                  VALUES 
                  (:request_id, 2, :notes, :changed_by, NOW())";
        
        $stmt = $db->prepare($query);
        $stmt->bindParam(':request_id', $request_id);
        $stmt->bindParam(':notes', $history_notes);
        $stmt->bindParam(':changed_by', $csr_name);
        $stmt->execute();
    }
    
    // Add an internal note about the assignment
    $note_content = "Added {$role_text}: {$tech_name} to this request.";
    if (!empty($assignment_notes)) {
        $note_content .= "\n\nAssignment notes: {$assignment_notes}";
    }
    
    $query = "INSERT INTO request_notes 
              (request_id, csr_id, note_type, note_content, created_at) 
              VALUES 
              (:request_id, :csr_id, 'internal', :note_content, NOW())";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':request_id', $request_id);
    $stmt->bindParam(':csr_id', $_SESSION['csr_id']);
    $stmt->bindParam(':note_content', $note_content);
    $stmt->execute();

    // Auto chat message + customer notification for technician assignment
    if (!empty($request['customer_id'])) {
        try {
            $estimatedText = formatEstimatedVisit($estimated_arrival_time, $estimated_arrival_period);
            $customerMsg = "Your technician {$tech_name} has been assigned.\n\nEstimated visit: {$estimatedText}";
            addSystemChatMessageForRequest($db, $request_id, $customerMsg, 'technician');
            createCustomerNotification($db, $request_id, 'Technician Assigned', $customerMsg, 'success');
        } catch (Exception $chatEx) {
            error_log('Technician chat/notification warning: ' . $chatEx->getMessage());
        }
    }
    
    // Commit transaction
    $db->commit();
    
    $message = "Technician assigned successfully as {$role_text}!";
    if ($assignment_count >= 1) {
        $message = "Additional technician assigned as {$role_text}. Total technicians: " . ($assignment_count + 1);
    }
    
    echo json_encode([
        'success' => true, 
        'message' => $message,
        'assignment_id' => $assignment_id,
        'assignment_type' => $assignment_type,
        'total_technicians' => $assignment_count + 1
    ]);
    
} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) { $db->rollBack(); }
    echo json_encode([
        'success' => false, 
        'message' => 'Failed to assign technician: ' . $e->getMessage()
    ]);
}
?>