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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

// Get file number from query
$file_number = isset($_GET['file_number']) ? $_GET['file_number'] : '';

if (empty($file_number)) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'No file number provided']);
    exit();
}

try {
    // Get file details
    $file_query = "SELECT file_number, consignee_name, destination, obl_no, created_date 
                  FROM files 
                  WHERE file_number = ?";
    $file_stmt = $conn->prepare($file_query);
    $file_stmt->bind_param('s', $file_number);
    $file_stmt->execute();
    $file_result = $file_stmt->get_result();
    
    if ($file_result->num_rows === 0) {
        header('Content-Type: application/json');
        echo json_encode(['error' => 'File not found']);
        exit();
    }
    
    $file_details = $file_result->fetch_assoc();
    
    // Get containers for this file
    $container_query = "SELECT container_code, container_size 
                       FROM container_details 
                       WHERE file_number = ?";
    $container_stmt = $conn->prepare($container_query);
    $container_stmt->bind_param('s', $file_number);
    $container_stmt->execute();
    $container_result = $container_stmt->get_result();
    
    $containers = [];
    while ($row = $container_result->fetch_assoc()) {
        // Check if this container already has a truck assignment
        $check_query = "SELECT id FROM truck_details WHERE file_no = ? AND container_code = ?";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param('ss', $file_number, $row['container_code']);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        $row['has_assignment'] = ($check_result->num_rows > 0);
        $containers[] = $row;
    }
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode([
        'file_details' => $file_details,
        'containers' => $containers
    ]);
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode(['error' => $e->getMessage()]);
}
?>