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

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

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

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

if (empty($request_ids) || !$technician_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid request. No requests selected or no technician selected.']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    ensureCsrTeamTables($db);
    
    // Start transaction
    $db->beginTransaction();
    
    // 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';
    
    // 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';
    
    $assigned_count = 0;
    $failed_count = 0;
    $failed_requests = [];
    $double_job_count = 0;
    
    foreach ($request_ids as $request_id) {
        try {
            $request_id = (int)$request_id;
            if (!canCsrAccessRequest($db, (int)$_SESSION['csr_id'], $request_id)) {
                $failed_count++;
                $failed_requests[] = $request_id . ' - Access denied. This request is not assigned to you or your team.';
                continue;
            }
            $lockResult = blockIfRequestLockedByOtherCSR($db, $request_id, $_SESSION['csr_id']);
            if (!$lockResult['success']) {
                $failed_count++;
                $failed_requests[] = $request_id . ' - ' . $lockResult['message'];
                continue;
            }
            // Check if technician is already assigned
            $query = "SELECT id 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) {
                $failed_count++;
                $failed_requests[] = $request_id;
                continue;
            }
            
            // Count existing active assignments
            $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 = $stmt->fetch(PDO::FETCH_ASSOC);
            $assignment_count = $existing['count'];
            
            // Determine assignment type
            if ($assignment_count == 0) {
                $assignment_type = 'primary';
            } elseif ($assignment_count == 1) {
                $assignment_type = 'secondary';
                $double_job_count++;
            } else {
                $assignment_type = 'helper';
            }
            
            // Insert assignment
            $query = "INSERT INTO service_assignments 
                      (request_id, technician_id, assigned_by, csr_notes, status, assignment_type, assigned_at) 
                      VALUES 
                      (:request_id, :technician_id, :assigned_by, :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(':notes', $assignment_notes);
            $stmt->bindParam(':assignment_type', $assignment_type);
            $stmt->execute();
            
            // Update request status if it's the first assignment
            if ($assignment_count == 0) {
                $query = "UPDATE service_requests SET job_status_id = 2 WHERE id = :request_id";
                $stmt = $db->prepare($query);
                $stmt->bindParam(':request_id', $request_id);
                $stmt->execute();
                
                // Add status history for first assignment
                $history_notes = "Assigned to technician: {$tech_name} (Bulk Assignment - {$assignment_type})";
                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 note
            $role_text = ($assignment_type == 'primary') ? 'Lead Technician' : (($assignment_type == 'secondary') ? 'Secondary Technician' : 'Helper');
            $note_content = "Added {$role_text}: {$tech_name} to this request. (Bulk Assignment)";
            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();
            
            $assigned_count++;
            
        } catch (Exception $e) {
            $failed_count++;
            $failed_requests[] = $request_id;
        }
    }
    
    // Commit transaction
    $db->commit();
    
    $message = "Successfully assigned {$assigned_count} request(s) to technician.";
    if ($double_job_count > 0) {
        $message .= " {$double_job_count} request(s) now have multiple technicians (Double Job).";
    }
    if ($failed_count > 0) {
        $message .= " Failed to assign {$failed_count} request(s).";
    }
    
    echo json_encode([
        'success' => true,
        'message' => $message,
        'assigned_count' => $assigned_count,
        'double_job_count' => $double_job_count,
        'failed_count' => $failed_count,
        'failed_requests' => $failed_requests
    ]);
    
} catch (Exception $e) {
    $db->rollBack();
    echo json_encode([
        'success' => false,
        'message' => 'Failed to assign requests: ' . $e->getMessage()
    ]);
}
?>