<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit();
}

// Get user ID for tracking
$user_id = $_SESSION['user_id'];

try {
    $conn->begin_transaction();
    
    $file_number = $_POST['file_number'];
    $trucks_to_assign = intval($_POST['trucks_to_assign']);
    
    // Get current file details
    $sql = "SELECT f.*, 
            COALESCE(f.total_trucks_required, 0) as total_trucks_required,
            COALESCE(f.trucks_assigned, 0) as trucks_assigned,
            COALESCE(f.trucks_remaining, 0) as trucks_remaining,
            f.c_type
            FROM files f
            WHERE f.file_number = ?";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $file_number);
    $stmt->execute();
    $result = $stmt->get_result();
    $file = $result->fetch_assoc();
    
    if (!$file) {
        throw new Exception("File not found");
    }
    
    if ($trucks_to_assign > $file['trucks_remaining']) {
        throw new Exception("Cannot assign more trucks than remaining");
    }
    
    // Update file counts
    $new_assigned = $file['trucks_assigned'] + $trucks_to_assign;
    $new_remaining = $file['trucks_remaining'] - $trucks_to_assign;
    
    $update_sql = "UPDATE files 
                   SET trucks_assigned = ?, 
                       trucks_remaining = ?,
                       updated_at = NOW(),
                       updated_by = ?
                   WHERE file_number = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param('iiis', $new_assigned, $new_remaining, $user_id, $file_number);
    
    if (!$update_stmt->execute()) {
        throw new Exception("Failed to update truck assignments");
    }
    
    // Get next assignment batch number based on cargo type
    if ($file['c_type'] === 'Bulk Cargo') {
        $batch_sql = "SELECT COALESCE(MAX(assignment_batch), 0) + 1 as next_batch 
                     FROM bulk_cargo_details 
                     WHERE file_number = ?";
    } else {
        $batch_sql = "SELECT COALESCE(MAX(assignment_batch), 0) + 1 as next_batch 
                     FROM loose_cargo_details 
                     WHERE file_number = ?";
    }
    
    $batch_stmt = $conn->prepare($batch_sql);
    $batch_stmt->bind_param('s', $file_number);
    $batch_stmt->execute();
    $batch_result = $batch_stmt->get_result();
    $batch_row = $batch_result->fetch_assoc();
    $next_batch = $batch_row['next_batch'];
    
    // Create truck detail entries based on cargo type
    if ($file['c_type'] === 'Bulk Cargo') {
        // Insert placeholder records for bulk cargo trucks
        $bulk_sql = "INSERT INTO bulk_cargo_details (
                        file_number, 
                        truck_reg,
                        transporter,
                        driver_name,
                        tonnage,
                        assignment_batch,
                        created_at,
                        created_by
                    ) VALUES (?, 'Pending', NULL, NULL, 0, ?, NOW(), ?)";
                    
        $bulk_stmt = $conn->prepare($bulk_sql);
        
        for ($i = 0; $i < $trucks_to_assign; $i++) {
            $bulk_stmt->bind_param('sii', $file_number, $next_batch, $user_id);
            if (!$bulk_stmt->execute()) {
                throw new Exception("Failed to create bulk cargo truck records");
            }
        }
    } else {
        // Insert placeholder records for loose cargo trucks
        $loose_sql = "INSERT INTO loose_cargo_details (
                        file_number,
                        truck_reg,
                        transporter,
                        driver_name,
                        cbm,
                        assignment_batch,
                        created_at,
                        created_by
                    ) VALUES (?, 'Pending', NULL, NULL, 0, ?, NOW(), ?)";
                    
        $loose_stmt = $conn->prepare($loose_sql);
        
        for ($i = 0; $i < $trucks_to_assign; $i++) {
            $loose_stmt->bind_param('sii', $file_number, $next_batch, $user_id);
            if (!$loose_stmt->execute()) {
                throw new Exception("Failed to create loose cargo truck records");
            }
        }
    }
    
    // Create notification
    $notif_message = "Additional {$trucks_to_assign} trucks assigned to file {$file_number}";
    $sql_notif = "INSERT INTO notifications (
                    file_id, 
                    file_number, 
                    notif_message, 
                    notif_message_id,
                    created_by,
                    created_at
                  ) VALUES (
                    (SELECT id FROM files WHERE file_number = ?),
                    ?,
                    ?,
                    2,
                    ?,
                    NOW()
                  )";
    
    $notif_stmt = $conn->prepare($sql_notif);
    $notif_stmt->bind_param('sssi', $file_number, $file_number, $notif_message, $user_id);
    
    if (!$notif_stmt->execute()) {
        // Log notification error but don't fail the transaction
        error_log("Failed to create notification for file: $file_number");
    }
    
    // Commit transaction
    $conn->commit();
    
    $_SESSION['success_message'] = "Successfully assigned {$trucks_to_assign} additional trucks";
    header("Location: update_truck_assignment.php?file_number=" . urlencode($file_number));
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header("Location: update_truck_assignment.php?file_number=" . urlencode($file_number));
    exit();
}
?> 