<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Set content type as JSON
header('Content-Type: application/json');

// Check if file_number is provided
if (!isset($_GET['file_number']) || empty($_GET['file_number'])) {
    echo json_encode([
        'success' => false,
        'message' => 'File number is required'
    ]);
    exit;
}

$file_number = $_GET['file_number'];

try {
    // Get file information
    $file_query = "SELECT f.*, 
                     DATE_FORMAT(f.created_date, '%Y-%m-%d') as formatted_date,
                     DATE_FORMAT(f.eta, '%Y-%m-%d') as formatted_eta
                   FROM files f 
                   WHERE f.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) {
        echo json_encode([
            'success' => false,
            'message' => 'File not found'
        ]);
        exit;
    }
    
    $file_data = $file_result->fetch_assoc();
    
    // Get customer information
    $customer_data = [
        'name' => 'Unknown',
        'phone_number' => 'N/A',
        'address' => 'N/A',
        'city' => 'N/A',
        'country' => 'N/A'
    ];
    
    if (!empty($file_data['customer'])) {
        $customer_query = "SELECT * FROM customers WHERE customer_id = ?";
        $customer_stmt = $conn->prepare($customer_query);
        $customer_stmt->bind_param('i', $file_data['customer']);
        $customer_stmt->execute();
        $customer_result = $customer_stmt->get_result();
        
        if ($customer_result->num_rows > 0) {
            $customer_row = $customer_result->fetch_assoc();
            $customer_data = [
                'name' => $customer_row['first_name'] . ' ' . $customer_row['last_name'],
                'phone_number' => $customer_row['phone_number'] ?? 'N/A',
                'address' => $customer_row['address'] ?? 'N/A',
                'city' => $customer_row['city'] ?? 'N/A',
                'country' => $customer_row['country'] ?? 'N/A'
            ];
        }
    }
    
    // Get container details if applicable
    $containers = [];
    if ($file_data['c_type'] === 'Container') {
        $container_query = "SELECT * 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();
        
        while ($container_row = $container_result->fetch_assoc()) {
            $containers[] = $container_row;
        }
    }
    
    // Get loose cargo items if applicable
    $loose_items = [];
    $loose_query = "SELECT * FROM loose_cargo_items WHERE file_number = ?";
    $loose_stmt = $conn->prepare($loose_query);
    $loose_stmt->bind_param('s', $file_number);
    $loose_stmt->execute();
    $loose_result = $loose_stmt->get_result();
    
    while ($loose_row = $loose_result->fetch_assoc()) {
        $loose_items[] = $loose_row;
    }
    
    // Get truck assignment details
    $truck_details = [];
    $truck_query = "SELECT * FROM truck_details WHERE file_no = ?";
    $truck_stmt = $conn->prepare($truck_query);
    $truck_stmt->bind_param('s', $file_number);
    $truck_stmt->execute();
    $truck_result = $truck_stmt->get_result();
    
    while ($truck_row = $truck_result->fetch_assoc()) {
        $truck_details[] = $truck_row;
    }
    
    // Get transporter information if available
    $transporter_info = null;
    if (!empty($file_data['transporter'])) {
        $transporter_query = "SELECT * FROM transporter_info WHERE id = ?";
        $transporter_stmt = $conn->prepare($transporter_query);
        $transporter_stmt->bind_param('i', $file_data['transporter']);
        $transporter_stmt->execute();
        $transporter_result = $transporter_stmt->get_result();
        
        if ($transporter_result->num_rows > 0) {
            $transporter_info = $transporter_result->fetch_assoc();
        }
    }
    
    // Format the data for response
    $response_data = [
        'success' => true,
        'data' => [
            'file' => [
                'file_number' => $file_data['file_number'],
                'created_date' => $file_data['formatted_date'] ?? 'N/A',
                'destination' => $file_data['destination'] ?? 'N/A',
                'c_type' => $file_data['c_type'] ?? 'Container',
                'obl_no' => $file_data['obl_no'] ?? 'N/A',
                'eta' => $file_data['formatted_eta'] ?? 'N/A',
                'consignee_name' => $file_data['consignee_name'] ?? 'N/A',
                'currency' => $file_data['currency'] ?? '$',
                'remarks' => $file_data['remarks'] ?? '',
                'vno' => $file_data['vno'] ?? '',
                'port' => $file_data['port'] ?? '',
                'close_file' => !empty($file_data['close_file'])
            ],
            'customer' => $customer_data,
            'containers' => $containers,
            'loose_items' => $loose_items,
            'truck_details' => $truck_details,
            'transporter' => $transporter_info
        ]
    ];
    
    echo json_encode($response_data);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred: ' . $e->getMessage()
    ]);
}
?>