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

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

// Check if file ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No file ID provided";
    header('Location: file_list.php');
    exit();
}

$file_id = intval($_GET['id']);

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Get file details
$query = "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,
            c.first_name, c.last_name, c.phone_number, c.address, c.city, c.country, c.postal_code, c.email as client_email
          FROM files f 
          LEFT JOIN customers c ON f.customer = c.customer_id 
          WHERE f.id = ?";

$stmt = $conn->prepare($query);
$stmt->bind_param('i', $file_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "File not found";
    header('Location: file_list.php');
    exit();
}

$file = $result->fetch_assoc();
$file_type = $file['local/transit']; // 1 = Local, 2 = Transit
$file_number = $file['file_number'];

// Get counts of records in the proforma and pre_proforma tables
$query_count_proforma = "SELECT COUNT(*) AS num_records FROM proforma WHERE file_number = '$file_number'";
$result_count_proforma = $conn->query($query_count_proforma);
$num_proforma_records = 0;

if ($result_count_proforma && $result_count_proforma->num_rows > 0) {
    $row_count = $result_count_proforma->fetch_assoc();
    $num_proforma_records = $row_count['num_records'];
}

$query_count_pre_proforma = "SELECT COUNT(*) AS num_records FROM pre_proforma WHERE file_number = '$file_number'";
$result_count_pre_proforma = $conn->query($query_count_pre_proforma);
$num_pre_proforma_records = 0;

if ($result_count_pre_proforma && $result_count_pre_proforma->num_rows > 0) {
    $row_count = $result_count_pre_proforma->fetch_assoc();
    $num_pre_proforma_records = $row_count['num_records'];
}

// Logic to determine tab visibility
// When proforma exists, hide file charges and pre-proforma tabs
$show_file_charges_tab = $num_proforma_records == 0 && hasPermission($role_id, 'invoice');
$show_pre_proforma_tab = $num_pre_proforma_records > 0 && hasPermission($role_id, 'invoice');
$show_proforma_tab = $num_proforma_records > 0 && hasPermission($role_id, 'invoice');

// Fetch All In amount if it exists
$sql_all_in = "SELECT all_in_amount FROM pre_proforma WHERE file_number = '$file_number' AND all_in = 'Yes' LIMIT 1";
$result_all_in = $conn->query($sql_all_in);
$allIn = null;
if ($result_all_in && $result_all_in->num_rows > 0) {
    $row_all_in = $result_all_in->fetch_assoc();
    $allIn = $row_all_in['all_in_amount'];
}

// Get container details
$container_query = "SELECT * FROM container_details WHERE file_number = ? ORDER BY id ASC";
$container_stmt = $conn->prepare($container_query);
$container_stmt->bind_param('s', $file_number);
$container_stmt->execute();
$container_result = $container_stmt->get_result();
$containers = [];

if ($container_result->num_rows > 0) {
    while ($row = $container_result->fetch_assoc()) {
        $containers[] = $row;
    }
}

$c_type = $file['c_type'] ?? 'Container'; // Default to Container if not set

// Function to determine the cargo type
function getCargoType($c_type) {
    // Standardize the cargo type checking
    if ($c_type == 'Container' || $c_type == 'container') {
        return 'Container';
    } elseif ($c_type == '0' || $c_type == 'Loose Cargo' || $c_type == 'loose cargo') {
        return 'Loose Cargo';
    } elseif ($c_type == 'Bulk Cargo' || $c_type == 'bulk cargo') {
        return 'Bulk Cargo';
    } elseif ($c_type == 'Vehicle Cargo' || $c_type == 'vehicle cargo') {
        return 'Vehicle Cargo';
    }
}

// Get the standardized cargo type
$cargo_type = getCargoType($c_type);

// Get charges details
$charges_query = "SELECT * FROM charges WHERE file_number = ?";
$charges_stmt = $conn->prepare($charges_query);
$charges_stmt->bind_param('s', $file_number);
$charges_stmt->execute();
$charges_result = $charges_stmt->get_result();
$charges = $charges_result->fetch_assoc();

// Count files for this customer
$customer_id = $file['customer'];
$file_count_query = "SELECT COUNT(*) as count FROM files WHERE customer = ?";
$file_count_stmt = $conn->prepare($file_count_query);
$file_count_stmt->bind_param('i', $customer_id);
$file_count_stmt->execute();
$file_count_result = $file_count_stmt->get_result();
$file_count = $file_count_result->fetch_assoc()['count'];

// Check user permissions
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view', 'edit', 'delete', 'approve', 'invoice'], // Admin has all permissions
        '2' => ['view', 'edit', 'approve', 'invoice'], // General Manager
        '3' => ['view', 'edit', 'invoice'], // Operations
        '4' => ['view', 'invoice'], // Finance
        '5' => ['view', 'edit'], // Declaration Officer
        '6' => ['view'], // Shipping Line Clerk
        '7' => ['view'], // Transport Supervisor
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

// Access check helper
function hasAccess($user_role, $allowed_roles) {
    return in_array($user_role, $allowed_roles);
}

$can_edit = hasPermission($role_id, 'edit');
$can_delete = hasPermission($role_id, 'delete');
$can_invoice = hasPermission($role_id, 'invoice');
$can_approve = hasPermission($role_id, 'approve');

// Format date helper function
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('Y-m-d', strtotime($date));
}

// Check if invoice exists for this file
$invoice_query = "SELECT invoice_id, invoice_number, total_amount, status, issue_date FROM invoices 
                 WHERE file_number = ? 
                 LIMIT 1";
$invoice_stmt = $conn->prepare($invoice_query);
$invoice_stmt->bind_param('s', $file_number);
$invoice_stmt->execute();
$invoice_result = $invoice_stmt->get_result();
$invoice_exists = $invoice_result->num_rows > 0;
$invoice = $invoice_exists ? $invoice_result->fetch_assoc() : null;

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Shipment Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.css">
    <style>
        .file-details-card {
            margin-bottom: 1.5rem;
        }
        .file-header {
            padding: 1rem;
            border-bottom: 1px solid #e9e9ef;
            background-color: #f8f9fa;
        }
        .file-info-label {
            font-weight: 600;
            color: #495057;
        }
        .file-badge {
            font-size: 0.75rem;
            padding: 0.3rem 0.5rem;
        }
        .container-card {
            margin-bottom: 1rem;
            border-left: 3px solid #3498db;
        }
        .timeline-item {
            position: relative;
            padding-left: 40px;
            margin-bottom: 20px;
        }
        .timeline-item:before {
            content: '';
            position: absolute;
            left: 10px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e9e9ef;
        }
        .timeline-item .timeline-date {
            position: relative;
        }
        .timeline-item .timeline-date:before {
            content: '';
            position: absolute;
            left: -36px;
            top: 50%;
            transform: translateY(-50%);
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #3498db;
        }
        .timeline-item.completed .timeline-date:before {
            background: #20c997;
        }
        .timeline-item.pending .timeline-date:before {
            background: #ffc107;
        }
        .timeline-empty {
            color: #6c757d;
            font-style: italic;
        }
        .print-section {
            text-align: right;
            margin-bottom: 1rem;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            .container-fluid {
                width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            .card {
                border: none !important;
                box-shadow: none !important;
            }
        }
        .nav-tabs .nav-link {
            margin-right: 10px;
        }
        .tab-pane {
            padding: 20px 0;
        }
        .select2-container {
            width: 100% !important;
        }
        /* Timeline styles */
        .vertical-timeline {
            position: relative;
            padding: 2rem 0;
        }
        .timeline-item {
            position: relative;
            display: flex;
            margin-bottom: 2rem;
        }
        .timeline-item:last-child {
            margin-bottom: 0;
        }
        .timeline-item-date {
            flex: 0 0 120px;
            margin-right: 1.5rem;
            text-align: right;
            color: #6c757d;
            padding-top: 0.25rem;
        }
        .timeline-item-date small {
            display: block;
            font-size: 0.75rem;
            opacity: 0.7;
        }
        .timeline-item-content {
            position: relative;
            flex: 1;
            padding-left: 3rem;
        }
        .timeline-item-content:before {
            content: '';
            position: absolute;
            left: 0;
            top: 1.5rem;
            bottom: -2.5rem;
            width: 2px;
            background-color: #e9e9ef;
        }
        .timeline-item:last-child .timeline-item-content:before {
            display: none;
        }
        .timeline-item-icon {
            position: absolute;
            left: -10px;
            top: 0;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1;
        }
        .timeline-item-icon i {
            font-size: 11px;
        }
        .timeline-item-box {
            background-color: #f8f9fa;
            border-radius: 0.25rem;
            padding: 1rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        /* Cost container styles */
        .cost-row {
            position: relative;
            padding: 0.75rem;
            border-radius: 0.25rem;
            transition: background-color 0.2s;
        }
        .cost-row:hover {
            background-color: #f8f9fa;
        }
        .remove-row {
            margin-bottom: 1rem;
        }
        /* Select2 custom styling */
        .select2-container--default .select2-selection--single {
            height: 38px;
            border-color: #ced4da;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Shipment Management', 'title' => 'View Shipment Details')); ?>

                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h4 class="m-0">
                            <i class="ri-file-text-line me-1 text-primary"></i> File: <strong><?php echo htmlspecialchars($file_number); ?></strong>
                        </h4>
                        
                        <div class="print-section no-print">
                            <button type="button" class="btn btn-success" onclick="window.print()">
                                <i class="ri-printer-line align-bottom me-1"></i> Print Details
                            </button>
                            <a href="file_list.php" class="btn btn-primary">
                                <i class="ri-arrow-left-line align-bottom me-1"></i> Back to List
                            </a>
                            <?php if ($can_edit): ?>
                            <a href="edit_file.php?id=<?php echo $file_id; ?>" class="btn btn-info">
                                <i class="ri-edit-box-line align-bottom me-1"></i> Edit File
                            </a>
                            <?php endif; ?>
                            <?php if (($file['c_type'] == 'Bulk Cargo' || $file['c_type'] == 'Loose Cargo') && $file['trucks_remaining'] > 0): ?>
                            <a href="update_truck_assignment.php?file_number=<?php echo urlencode($file_number); ?>" class="btn btn-primary">
                                <i class="ri-truck-line align-bottom me-1"></i> Assign Trucks
                            </a>
                            <?php endif; ?>
                            <?php if ($can_invoice): ?>
                            <a href="create_invoice.php?file_id=<?php echo $file_id; ?>" class="btn btn-warning">
                                <i class="ri-bill-line align-bottom me-1"></i> Create Invoice
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Tab Navigation -->
                    <div class="card">
                        <div class="card-body py-0">
                            <ul class="nav nav-tabs" id="myTab" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="file-tab" data-bs-toggle="tab" data-bs-target="#file-details" type="button" role="tab" aria-controls="file-details" aria-selected="true">
                                        <i class="ti ti-file-text me-2"></i>File Details
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="client-tab" data-bs-toggle="tab" data-bs-target="#client-details" type="button" role="tab" aria-controls="client-details" aria-selected="false">
                                        <i class="ti ti-user me-2"></i>Client Details
                                    </button>
                                </li>
                                <?php if ($file_type == 1): // Transit shipment only ?>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="container-tab" data-bs-toggle="tab" data-bs-target="#container-details" type="button" role="tab" aria-controls="container-details" aria-selected="false">
                                        <?php if ($cargo_type == 'Container'): ?>
                                            <i class="ti ti-box me-2"></i>Container Details
                                        <?php elseif ($cargo_type == 'Loose Cargo'): ?>
                                            <i class="ti ti-car me-2"></i>Loose Cargo Details
                                        <?php elseif ($cargo_type == 'Bulk Cargo'): ?>
                                            <i class="ti ti-truck-loading me-2"></i>Bulk Cargo Details
                                        <?php elseif ($cargo_type == 'Vehicle Cargo'): ?>
                                            <i class="ti ti-package me-2"></i>Vehicle Cargo Details
                                        <?php endif; ?>
                                    </button>
                                </li>
                                <?php endif; ?>
                                <?php if (hasPermission($role_id, 'invoice')): ?>
                                    <?php if ($show_file_charges_tab): ?>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="charges-tab" data-bs-toggle="tab" data-bs-target="#file-charges" type="button" role="tab" aria-controls="file-charges" aria-selected="false">
                                            <i class="ti ti-cash me-2"></i>File Charges
                                        </button>
                                    </li>
                                    <?php endif; ?>
                                
                                    <?php if ($show_pre_proforma_tab && $num_proforma_records == 0): ?>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="pre-proforma-tab" data-bs-toggle="tab" data-bs-target="#pre-proforma" type="button" role="tab" aria-controls="pre-proforma" aria-selected="false">
                                            <i class="ti ti-receipt me-2"></i>Pre-Proforma Invoice
                                        </button>
                                    </li>
                                    <?php endif; ?>
                                
                                    <?php if ($show_proforma_tab): ?>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="proforma-tab" data-bs-toggle="tab" data-bs-target="#proforma" type="button" role="tab" aria-controls="proforma" aria-selected="false">
                                            <i class="ti ti-file-invoice me-2"></i>Proforma Invoice
                                        </button>
                                    </li>
                                    <?php endif; ?>
                                <?php endif; ?>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="timeline-tab" data-bs-toggle="tab" data-bs-target="#timeline" type="button" role="tab" aria-controls="timeline" aria-selected="false">
                                        <i class="ti ti-timeline me-2"></i>Timeline
                                    </button>
                                </li>
                            </ul>
                        </div>
                    </div>

                    <!-- Tab Content -->
                    <div class="tab-content" id="myTabContent">
                        <!-- File Details Tab -->
                        <div class="tab-pane fade show active" id="file-details" role="tabpanel" aria-labelledby="file-tab">
                            <div class="row">
                                <div class="col-xl-4 col-lg-5">
                                    <!-- File Summary Card -->
                                    <div class="card file-details-card">
                                        <div class="card-header file-header">
                                            <h4 class="card-title mb-0">
                                                Shipment #<?php echo htmlspecialchars($file_number); ?>
                                                <?php if ($file_type == 1): ?>
                                                    <span class="badge bg-success file-badge">Local Shipment</span>
                                                <?php else: ?>
                                                    <span class="badge bg-info file-badge">Transit Shipment</span>
                                                <?php endif; ?>
                                            </h4>
                                        </div>
                                        <div class="card-body">
                                            <div class="text-center mb-4">
                                                <div class="chat-avtar d-inline-flex mx-auto">
                                                    <img class="rounded-circle img-fluid wid-70" src="assets/images/user/avatar-1.jpg" alt="User image">
                                                </div>
                                                <h5 class="mb-0"><?php echo htmlspecialchars($file['first_name'] . ' ' . $file['last_name']); ?></h5>
                                                <p class="text-muted"><?php echo htmlspecialchars($file['client_email']); ?></p>
                                            </div>

                                            <div class="row g-3 text-center mb-3">
                                                <div class="col-4">
                                                    <h5 class="mb-0"><?php echo $file_count; ?></h5>
                                                    <small class="text-muted">Files</small>
                                                </div>
                                                
                                                <div class="col-4 border border-top-0 border-bottom-0">
                                                    <?php 
                                                    // Count invoices for this customer
                                                    $invoice_count_query = "SELECT COUNT(*) as count FROM invoices WHERE customer_id = ?";
                                                    $invoice_count_stmt = $conn->prepare($invoice_count_query);
                                                    $invoice_count_stmt->bind_param('i', $customer_id);
                                                    $invoice_count_stmt->execute();
                                                    $invoice_count_result = $invoice_count_stmt->get_result();
                                                    $invoice_count = $invoice_count_result->fetch_assoc()['count'];
                                                    ?>
                                                    <h5 class="mb-0"><?php echo $invoice_count; ?></h5>
                                                    <small class="text-muted">Invoices</small>
                                                </div>
                                                
                                                <div class="col-4">
                                                    <?php if ($allIn): ?>
                                                    <h5 class="mb-0"><?php echo $file['currency'] . ' ' . number_format($allIn, 2); ?></h5>
                                                    <small class="text-muted">All-In Fee</small>
                                                    <?php else: ?>
                                                    <h5 class="mb-0">-</h5>
                                                    <small class="text-muted">All-In Fee</small>
                                                    <?php endif; ?>
                                                </div>
                                            </div>

                                            <hr class="my-3 border border-secondary-subtle">
                                            
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="ti ti-calendar-event me-2 text-muted"></i>
                                                <div>
                                                    <p class="mb-0 text-muted">Created Date</p>
                                                    <h6 class="mb-0"><?php echo formatDate($file['created_date']); ?></h6>
                                                </div>
                                            </div>
                                            
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="ti ti-map-pin me-2 text-muted"></i>
                                                <div>
                                                    <p class="mb-0 text-muted">Destination</p>
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($file['destination']); ?></h6>
                                                </div>
                                            </div>
                                            
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="ti ti-building me-2 text-muted"></i>
                                                <div>
                                                    <p class="mb-0 text-muted">Consignee</p>
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($file['consignee_name']); ?></h6>
                                                </div>
                                            </div>
                                            
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="ti ti-file-invoice me-2 text-muted"></i>
                                                <div>
                                                    <p class="mb-0 text-muted">BL Number</p>
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($file['obl_no'] ?: 'N/A'); ?></h6>
                                                </div>
                                            </div>
                                            
                                            <?php if (!empty($file['transporter'])): ?>
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="ti ti-truck me-2 text-muted"></i>
                                                <div>
                                                    <p class="mb-0 text-muted">Transporter</p>
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($file['transporter']); ?></h6>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($file_type == 2): // Transit specific info ?>
                                            <hr class="my-3 border border-secondary-subtle">
                                            <h6 class="mb-3">Transit Details</h6>
                                            
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="ti ti-calendar me-2 text-muted"></i>
                                                <div>
                                                    <p class="mb-0 text-muted">ETA</p>
                                                    <h6 class="mb-0"><?php echo formatDate($file['eta']); ?></h6>
                                                </div>
                                            </div>
                                            
                                            <?php if (!empty($file['pre_alert_received_date'])): ?>
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="ti ti-bell me-2 text-muted"></i>
                                                <div>
                                                    <p class="mb-0 text-muted">Pre-Alert Received</p>
                                                    <h6 class="mb-0"><?php echo formatDate($file['pre_alert_received_date']); ?></h6>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($file['discharge_date'])): ?>
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="ti ti-anchor me-2 text-muted"></i>
                                                <div>
                                                    <p class="mb-0 text-muted">Discharge Date</p>
                                                    <h6 class="mb-0"><?php echo formatDate($file['discharge_date']); ?></h6>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($file['remarks'])): ?>
                                            <hr class="my-3 border border-secondary-subtle">
                                            <h6 class="mb-2">Remarks</h6>
                                            <p class="text-muted"><?php echo nl2br(htmlspecialchars($file['remarks'])); ?></p>
                                            <?php endif; ?>
                                            
                                            <?php if ($can_edit): ?>
                                            <div class="text-center mt-4">
                                                <a href="edit_file.php?id=<?php echo $file_id; ?>" class="btn btn-primary rounded-pill">
                                                    <i class="ri-edit-box-line align-bottom me-1"></i> Edit File
                                                </a>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <!-- End File Summary Card -->
                                    
                                    <?php if ($file_type == 2 && !empty($containers)): ?>
                                    <!-- Container Summary Card (Compact version for side panel) -->
                                    <div class="card file-details-card">
                                        <div class="card-header file-header">
                                            <h4 class="card-title mb-0">Containers (<?php echo count($containers); ?>)</h4>
                                        </div>
                                        <div class="card-body p-0">
                                            <ul class="list-group list-group-flush">
                                                <?php foreach ($containers as $index => $container): ?>
                                                <li class="list-group-item">
                                                    <div class="d-flex align-items-center">
                                                        <div class="flex-shrink-0">
                                                            <div class="avatar avatar-sm bg-light text-primary rounded">
                                                                <i class="ti ti-box"></i>
                                                            </div>
                                                        </div>
                                                        <div class="flex-grow-1 ms-3">
                                                            <h6 class="mb-0"><?php echo htmlspecialchars($container['container_code']); ?></h6>
                                                            <small class="text-muted"><?php echo htmlspecialchars($container['container_size']); ?>ft</small>
                                                        </div>
                                                        <div class="flex-shrink-0">
                                                            <a href="#container-details" data-bs-toggle="tab" onclick="document.getElementById('container-tab').click(); document.getElementById('container-collapse-<?php echo $index; ?>').classList.add('show');" class="btn btn-sm btn-soft-info">
                                                                <i class="ri-eye-line"></i>
                                                            </a>
                                                        </div>
                                                    </div>
                                                </li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="col-xl-8 col-lg-7">
                                    <!-- Main Details Card -->
                                    <div class="card file-details-card">
                                        <div class="card-header file-header d-flex align-items-center">
                                            <h4 class="card-title mb-0 flex-grow-1">Shipment Information</h4>
                                            <div class="flex-shrink-0">
                                                <?php if ($file_type == 2): ?>
                                               <a href="truck_assignment.php?file_id=<?php echo $file_id; ?>" class="btn btn-sm btn-primary">
                                                    <i class="ri-truck-line align-bottom me-1"></i> Truck Assignment
                                                </a>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <!-- Basic Shipment Information -->
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <label class="file-info-label">File Number:</label>
                                                        <p><?php echo htmlspecialchars($file_number); ?></p>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <label class="file-info-label">Shipment Type:</label>
                                                        <p><?php echo $file_type == 1 ? 'Local Shipment' : 'Transit Shipment'; ?></p>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <label class="file-info-label">Currency:</label>
                                                        <p><?php echo htmlspecialchars($file['currency']); ?></p>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <label class="file-info-label">Port:</label>
                                                        <p><?php echo htmlspecialchars($file['port'] ?: 'N/A'); ?></p>
                                                    </div>
                                                    
                                                    <?php if (!empty($file['vno'])): ?>
                                                    <div class="mb-3">
                                                        <label class="file-info-label">Vessel Number:</label>
                                                        <p><?php echo htmlspecialchars($file['vno']); ?></p>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                                
                                                <div class="col-md-6">
                                                    <?php if ($file_type == 2): // Transit specific fields ?>
                                                    <div class="mb-3">
                                                        <label class="file-info-label">ETA:</label>
                                                        <p><?php echo formatDate($file['eta']); ?></p>
                                                    </div>
                                                    
                                                    <?php if (!empty($file['initial_eta'])): ?>
                                                    <div class="mb-3">
                                                        <label class="file-info-label">Initial ETA:</label>
                                                        <p><?php echo formatDate($file['initial_eta']); ?></p>
                                                    </div>
                                                    <?php endif; ?>
                                                    
                                                    <?php if (!empty($file['free_detention'])): ?>
                                                    <div class="mb-3">
                                                        <label class="file-info-label">Free Detention Days:</label>
                                                        <p><?php echo htmlspecialchars($file['free_detention']); ?> days</p>
                                                    </div>
                                                    <?php endif; ?>
                                                    <?php else: // Local shipment specific fields ?>
                                                    <?php if (!empty($file['load_date'])): ?>
                                                    <div class="mb-3">
                                                        <label class="file-info-label">Load Date:</label>
                                                        <p><?php echo formatDate($file['load_date']); ?></p>
                                                    </div>
                                                    <?php endif; ?>
                                                    
                                                    <?php if (!empty($file['offload_date'])): ?>
                                                    <div class="mb-3">
                                                        <label class="file-info-label">Offload Date:</label>
                                                        <p><?php echo formatDate($file['offload_date']); ?></p>
                                                    </div>
                                                    <?php endif; ?>
                                                    <?php endif; ?>
                                                    
                                                    <?php if (!empty($file['trans_type'])): ?>
                                                    <div class="mb-3">
                                                        <label class="file-info-label">Transportation Type:</label>
                                                        <p><?php echo htmlspecialchars($file['trans_type']); ?></p>
                                                    </div>
                                                    <?php endif; ?>
                                                    
                                                    <?php if (!empty($allIn)): ?>
                                                    <div class="mb-3">
                                                        <label class="file-info-label">All-In Amount:</label>
                                                        <p><?php echo $file['currency'] . ' ' . number_format($allIn, 2); ?></p>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            
                                            <!-- Additional Shipment Information -->
                                            <div class="row mt-4">
                                                <div class="col-12">
                                                    <h5 class="border-bottom pb-2">Additional Information</h5>
                                                </div>
                                                
                                                <?php if (!empty($charges)): ?>
                                                <div class="col-md-6">
                                                    <div class="card border shadow-none mb-3">
                                                        <div class="card-header bg-soft-primary">
                                                            <h6 class="card-title mb-0">Charges Information</h6>
                                                        </div>
                                                        <div class="card-body">
                                                            <?php if (!empty($charges['port_charge'])): ?>
                                                            <div class="mb-2">
                                                                <div class="d-flex justify-content-between">
                                                                    <span>Port Charges:</span>
                                                                    <span><?php echo $file['currency'] . ' ' . number_format($charges['port_charge'], 2); ?></span>
                                                                </div>
                                                                <?php if (!empty($charges['port_charges_paid_date']) && $charges['port_charges_paid_date'] != '0000-00-00 00:00:00'): ?>
                                                                <small class="text-success">Paid on <?php echo formatDate($charges['port_charges_paid_date']); ?></small>
                                                                <?php else: ?>
                                                                <small class="text-warning">Not paid</small>
                                                                <?php endif; ?>
                                                            </div>
                                                            <?php endif; ?>
                                                            
                                                            <?php if (!empty($charges['wharfage_charge'])): ?>
                                                            <div class="mb-2">
                                                                <div class="d-flex justify-content-between">
                                                                    <span>Wharfage Charges:</span>
                                                                    <span><?php echo $file['currency'] . ' ' . number_format($charges['wharfage_charge'], 2); ?></span>
                                                                </div>
                                                                <?php if (!empty($charges['whafage_paid_date']) && $charges['whafage_paid_date'] != '0000-00-00 00:00:00'): ?>
                                                                <small class="text-success">Paid on <?php echo formatDate($charges['whafage_paid_date']); ?></small>
                                                                <?php else: ?>
                                                                <small class="text-warning">Not paid</small>
                                                                <?php endif; ?>
                                                            </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <div class="col-md-6">
                                                    <?php
                                                    // Check if invoice exists
                                                    $invoice_query = "SELECT i.invoice_id, i.invoice_number, i.total_amount, i.status, i.issue_date, i.due_date
                                                                    FROM invoices i 
                                                                    WHERE i.file_number = ? 
                                                                    ORDER BY i.issue_date DESC";
                                                    $invoice_stmt = $conn->prepare($invoice_query);
                                                    $invoice_stmt->bind_param('s', $file_number);
                                                    $invoice_stmt->execute();
                                                    $invoice_result = $invoice_stmt->get_result();
                                                    
                                                    if ($invoice_result->num_rows > 0):
                                                        $invoice = $invoice_result->fetch_assoc();
                                                    ?>
                                                    <div class="card border shadow-none mb-3">
                                                        <div class="card-header bg-soft-success">
                                                            <h6 class="card-title mb-0">Invoice Information</h6>
                                                        </div>
                                                        <div class="card-body">
                                                            <div class="mb-2 d-flex justify-content-between">
                                                                <span>Invoice Number:</span>
                                                                <a href="view_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" class="link-primary">
                                                                    <?php echo htmlspecialchars($invoice['invoice_number']); ?>
                                                                </a>
                                                            </div>
                                                            
                                                            <div class="mb-2 d-flex justify-content-between">
                                                                <span>Amount:</span>
                                                                <span><?php echo $file['currency'] . ' ' . number_format($invoice['total_amount'], 2); ?></span>
                                                            </div>
                                                            
                                                            <div class="mb-2 d-flex justify-content-between">
                                                                <span>Issue Date:</span>
                                                                <span><?php echo formatDate($invoice['issue_date']); ?></span>
                                                            </div>
                                                            
                                                            <div class="mb-2 d-flex justify-content-between">
                                                                <span>Due Date:</span>
                                                                <span><?php echo formatDate($invoice['due_date']); ?></span>
                                                            </div>
                                                            
                                                            <div class="mb-0 d-flex justify-content-between align-items-center">
                                                                <span>Status:</span>
                                                                <?php 
                                                                    $status_class = '';
                                                                    switch ($invoice['status']) {
                                                                        case 'pending':
                                                                            $status_class = 'bg-warning';
                                                                            break;
                                                                        case 'paid':
                                                                            $status_class = 'bg-success';
                                                                            break;
                                                                        case 'cancelled':
                                                                            $status_class = 'bg-danger';
                                                                            break;
                                                                    }
                                                                ?>
                                                                <span class="badge <?php echo $status_class; ?>">
                                                                    <?php echo ucfirst($invoice['status']); ?>
                                                                </span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- End Main Details Card -->
                                    
                                    <!-- Quick Actions Card -->
                                    <div class="card file-details-card">
                                        <div class="card-header file-header">
                                            <h4 class="card-title mb-0">Quick Actions</h4>
                                        </div>
                                        <div class="card-body">
                                            <div class="row g-3">
                                                <?php if ($can_edit): ?>
                                                <div class="col-md-4 col-sm-6">
                                                    <a href="edit_file.php?id=<?php echo $file_id; ?>" class="text-decoration-none">
                                                        <div class="card border text-center mb-0">
                                                            <div class="card-body">
                                                                <div class="avatar-md mx-auto mb-3">
                                                                    <div class="avatar-title bg-soft-primary text-primary fs-4 rounded">
                                                                        <i class="ri-edit-box-line"></i>
                                                                    </div>
                                                                </div>
                                                                <h5 class="fs-15">Edit File</h5>
                                                            </div>
                                                        </div>
                                                    </a>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <?php if ($file_type == 2): ?>
                                                <div class="col-md-4 col-sm-6">
                                                    <a href="truck_assignment.php?file_number=<?php echo $file_number; ?>" class="text-decoration-none">
                                                        <div class="card border text-center mb-0">
                                                            <div class="card-body">
                                                                <div class="avatar-md mx-auto mb-3">
                                                                    <div class="avatar-title bg-soft-success text-success fs-4 rounded">
                                                                        <i class="ri-truck-line"></i>
                                                                    </div>
                                                                </div>
                                                                <h5 class="fs-15">Truck Assignment</h5>
                                                            </div>
                                                        </div>
                                                    </a>
                                                </div>
                                                
                                                <div class="col-md-4 col-sm-6">
                                                    <a href="update_file_remarks.php?file_number=<?php echo $file_number; ?>" class="text-decoration-none">
                                                        <div class="card border text-center mb-0">
                                                            <div class="card-body">
                                                                <div class="avatar-md mx-auto mb-3">
                                                                    <div class="avatar-title bg-soft-info text-info fs-4 rounded">
                                                                        <i class="ri-message-2-line"></i>
                                                                    </div>
                                                                </div>
                                                                <h5 class="fs-15">Update Remarks</h5>
                                                            </div>
                                                        </div>
                                                    </a>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <?php if (hasPermission($role_id, 'invoice') && (!$num_proforma_records)): ?>
                                                <div class="col-md-4 col-sm-6">
                                                    <?php if ($num_pre_proforma_records == 0): ?>
                                                    <a href="#file-charges" onclick="document.getElementById('charges-tab').click();" class="text-decoration-none">
                                                    <?php else: ?>
                                                    <a href="#pre-proforma" onclick="document.getElementById('pre-proforma-tab').click();" class="text-decoration-none">
                                                    <?php endif; ?>
                                                        <div class="card border text-center mb-0">
                                                            <div class="card-body">
                                                                <div class="avatar-md mx-auto mb-3">
                                                                    <div class="avatar-title bg-soft-warning text-warning fs-4 rounded">
                                                                        <i class="ri-file-list-3-line"></i>
                                                                    </div>
                                                                </div>
                                                                <h5 class="fs-15">Manage Charges</h5>
                                                            </div>
                                                        </div>
                                                    </a>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <?php if ($can_invoice && $num_proforma_records > 0): ?>
                                                <div class="col-md-4 col-sm-6">
                                                    <a href="create_invoice.php?file_id=<?php echo $file_id; ?>" class="text-decoration-none">
                                                        <div class="card border text-center mb-0">
                                                            <div class="card-body">
                                                                <div class="avatar-md mx-auto mb-3">
                                                                    <div class="avatar-title bg-soft-danger text-danger fs-4 rounded">
                                                                        <i class="ri-bill-line"></i>
                                                                    </div>
                                                                </div>
                                                                <h5 class="fs-15">Create Invoice</h5>
                                                            </div>
                                                        </div>
                                                    </a>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <div class="col-md-4 col-sm-6">
                                                    <a href="javascript:void(0);" onclick="window.print();" class="text-decoration-none">
                                                        <div class="card border text-center mb-0">
                                                            <div class="card-body">
                                                                <div class="avatar-md mx-auto mb-3">
                                                                    <div class="avatar-title bg-soft-dark text-dark fs-4 rounded">
                                                                        <i class="ri-printer-line"></i>
                                                                    </div>
                                                                </div>
                                                                <h5 class="fs-15">Print Details</h5>
                                                            </div>
                                                        </div>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- End Quick Actions Card -->
                                </div>
                            </div>
                        </div>
                        
                        <!-- Client Details Tab -->
                        <div class="tab-pane fade" id="client-details" role="tabpanel" aria-labelledby="client-tab">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5>Personal Information</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-sm-12 text-center mb-3">
                                                    <div class="user-upload wid-75">
                                                        <img src="assets/images/user/avatar-1.jpg" alt="img" class="img-fluid rounded-circle" style="width: 120px; height: 120px; object-fit: cover;">
                                                    </div>
                                                </div>
                                                <div class="col-sm-6">
                                                    <div class="form-group mb-3">
                                                        <label class="form-label">First Name</label>
                                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['first_name'] ?? ''); ?>" readonly>
                                                    </div>
                                                </div>
                                                <div class="col-sm-6">
                                                    <div class="form-group mb-3">
                                                        <label class="form-label">Last Name</label>
                                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['last_name'] ?? ''); ?>" readonly>
                                                    </div>
                                                </div>
                                                <div class="col-sm-6">
                                                    <div class="form-group mb-3">
                                                        <label class="form-label">Country</label>
                                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['country'] ?? ''); ?>" readonly>
                                                    </div>
                                                </div>
                                                <div class="col-sm-6">
                                                    <div class="form-group mb-3">
                                                        <label class="form-label">City</label>
                                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['city'] ?? ''); ?>" readonly>
                                                    </div>
                                                </div>
                                                <div class="col-sm-6">
                                                    <div class="form-group mb-3">
                                                        <label class="form-label">Postal Code</label>
                                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['postal_code'] ?? ''); ?>" readonly>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5>Contact Information</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-sm-6">
                                                    <div class="form-group mb-3">
                                                        <label class="form-label">Contact Phone</label>
                                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['phone_number'] ?? ''); ?>" readonly>
                                                    </div>
                                                </div>
                                                <div class="col-sm-6">
                                                    <div class="form-group mb-3">
                                                        <label class="form-label">Email</label>
                                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['client_email'] ?? ''); ?>" readonly>
                                                    </div>
                                                </div>
                                                <div class="col-sm-12">
                                                    <div class="form-group mb-3">
                                                        <label class="form-label">Address</label>
                                                        <textarea class="form-control" rows="4" readonly><?php echo htmlspecialchars($file['address'] ?? ''); ?></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Client Files History -->
                                    <div class="card">
                                        <div class="card-header">
                                            <h5>Client File History</h5>
                                        </div>
                                        <div class="card-body">
                                            <?php
                                            // Get other files for this customer
                                            $client_files_query = "SELECT file_number, created_date, destination 
                                                                 FROM files 
                                                                 WHERE customer = ? AND file_number != ? 
                                                                 ORDER BY created_date DESC LIMIT 5";
                                            $client_files_stmt = $conn->prepare($client_files_query);
                                            $client_files_stmt->bind_param('is', $customer_id, $file_number);
                                            $client_files_stmt->execute();
                                            $client_files_result = $client_files_stmt->get_result();
                                            
                                            if ($client_files_result->num_rows > 0):
                                            ?>
                                            <div class="table-responsive">
                                                <table class="table table-hover table-sm mb-0">
                                                    <thead>
                                                        <tr>
                                                            <th>File Number</th>
                                                            <th>Created Date</th>
                                                            <th>Destination</th>
                                                            <th>Action</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php while($client_file = $client_files_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($client_file['file_number']); ?></td>
                                                            <td><?php echo formatDate($client_file['created_date']); ?></td>
                                                            <td><?php echo htmlspecialchars($client_file['destination']); ?></td>
                                                            <td>
                                                                <a href="view_file.php?id=<?php 
                                                                    // Get file ID from file_number
                                                                    $file_id_query = "SELECT id FROM files WHERE file_number = ?";
                                                                    $file_id_stmt = $conn->prepare($file_id_query);
                                                                    $file_id_stmt->bind_param('s', $client_file['file_number']);
                                                                    $file_id_stmt->execute();
                                                                    $file_id_result = $file_id_stmt->get_result();
                                                                    $file_id_row = $file_id_result->fetch_assoc();
                                                                    echo $file_id_row['id'];
                                                                ?>" class="btn btn-sm btn-soft-info">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                        <?php endwhile; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                            <?php else: ?>
                                            <p class="text-muted mb-0">No other files found for this client.</p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                       <!-- Container/Cargo Details Tab -->
                        <?php if ($file_type == 2): // Transit shipment only ?>
                        <div class="tab-pane fade" id="container-details" role="tabpanel" aria-labelledby="container-tab">
                            <div class="row">
                                <div class="col-12">
                                    <div class="card file-details-card">
                                        <div class="card-header file-header">
                                            <h4 class="card-title mb-0">
                                                <?php if ($cargo_type == 'Container'): ?>
                                                    Container Information
                                                <?php elseif ($cargo_type == 'Loose Cargo'): ?>
                                                    Loose Cargo Information
                                                <?php elseif ($cargo_type == 'Bulk Cargo'): ?>
                                                    Bulk Cargo Information
                                                <?php else: ?>
                                                    Cargo Information
                                                <?php endif; ?>
                                            </h4>
                                        </div>
                                        <div class="card-body">
                                            <?php if ($cargo_type == 'Container'): ?>
                                                <!-- Container Details Section -->
                                                <div class="accordion" id="containerAccordion">
                                                    <?php foreach ($containers as $index => $container): ?>
                                                    <div class="accordion-item container-card">
                                                        <h2 class="accordion-header" id="container-heading-<?php echo $index; ?>">
                                                            <button class="accordion-button <?php echo $index > 0 ? 'collapsed' : ''; ?>" type="button" 
                                                                    data-bs-toggle="collapse" data-bs-target="#container-collapse-<?php echo $index; ?>" 
                                                                    aria-expanded="<?php echo $index === 0 ? 'true' : 'false'; ?>" 
                                                                    aria-controls="container-collapse-<?php echo $index; ?>">
                                                                Container #<?php echo htmlspecialchars($container['container_code']); ?> 
                                                                <span class="ms-2 badge bg-secondary"><?php echo htmlspecialchars($container['container_size']); ?>ft</span>
                                                            </button>
                                                        </h2>
                                                        <div id="container-collapse-<?php echo $index; ?>" 
                                                             class="accordion-collapse collapse <?php echo $index === 0 ? 'show' : ''; ?>" 
                                                             aria-labelledby="container-heading-<?php echo $index; ?>" 
                                                             data-bs-parent="#containerAccordion">
                                                            <div class="accordion-body">
                                                                <div class="row">
                                                                    <div class="col-md-6">
                                                                        <?php if (!empty($container['transporter_name'])): ?>
                                                                        <div class="mb-3">
                                                                            <span class="file-info-label">Transporter:</span>
                                                                            <span><?php echo htmlspecialchars($container['transporter_name']); ?></span>
                                                                        </div>
                                                                        <?php endif; ?>
                                                                        
                                                                        <?php if (!empty($container['driver_name'])): ?>
                                                                        <div class="mb-3">
                                                                            <span class="file-info-label">Driver:</span>
                                                                            <span><?php echo htmlspecialchars($container['driver_name']); ?></span>
                                                                        </div>
                                                                        <?php endif; ?>
                                                                        
                                                                        <?php if (!empty($container['driver_phone_number'])): ?>
                                                                        <div class="mb-3">
                                                                            <span class="file-info-label">Driver Phone:</span>
                                                                            <span><?php echo htmlspecialchars($container['driver_phone_number']); ?></span>
                                                                        </div>
                                                                        <?php endif; ?>
                                                                        
                                                                        <?php if (!empty($container['driver_license'])): ?>
                                                                        <div class="mb-3">
                                                                            <span class="file-info-label">Driver License:</span>
                                                                            <span><?php echo htmlspecialchars($container['driver_license']); ?></span>
                                                                        </div>
                                                                        <?php endif; ?>
                                                                        
                                                                        <?php if (!empty($container['way_bill'])): ?>
                                                                        <div class="mb-3">
                                                                            <span class="file-info-label">Way Bill:</span>
                                                                            <span><?php echo htmlspecialchars($container['way_bill']); ?></span>
                                                                        </div>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                    
                                                                    <!-- Timeline for Transit Shipments -->
                                                                    <div class="col-md-6">
                                                                        <h5 class="mb-3">Shipping Timeline</h5>
                                                                        <div class="timeline">
                                                                            <?php
                                                                            $timelineItems = [
                                                                                'Delivery Order Applied' => $container['delivery_order_apply_date'],
                                                                                'Delivery Order Received' => $container['delivery_order_received_date'],
                                                                                'OBR/SCT Received' => $container['obr_sct_received_date'],
                                                                                'OBR/TI Validation' => $container['obr_ti_validation_date'],
                                                                                'T1/C2 Approval' => $container['t1_c2_approval_date'],
                                                                                'Port Charges Paid' => $container['port_charges_paid_date'],
                                                                                'Whafage Paid' => $container['whafage_paid_date'],
                                                                                'Loading Permit Applied' => $container['loading_permit_apply_date'],
                                                                                'Truck Exit' => $container['truck_exit_date'],
                                                                                'Truck at Border' => $container['truck_at_border_date'],
                                                                                'Border Crossing' => $container['border_crossing_date'],
                                                                                'Delivery' => $container['delivery_date'],
                                                                                'Empty Return' => $container['empty_return_date']
                                                                            ];
                                                                            
                                                                            $hasTimelineItems = false;
                                                                            foreach ($timelineItems as $label => $date):
                                                                                if (!empty($date) && $date != '0000-00-00' && $date != '0000-00-00 00:00:00'):
                                                                                    $hasTimelineItems = true;
                                                                            ?>
                                                                            <div class="timeline-item completed">
                                                                                <div class="timeline-date">
                                                                                    <strong><?php echo $label; ?>:</strong> 
                                                                                    <?php echo formatDate($date); ?>
                                                                                </div>
                                                                            </div>
                                                                            <?php 
                                                                                endif;
                                                                            endforeach;
                                                                            
                                                                            if (!$hasTimelineItems):
                                                                            ?>
                                                                            <div class="timeline-empty">
                                                                                No timeline data available for this container.
                                                                            </div>
                                                                            <?php endif; ?>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                
                                                                <?php if (!empty($container['remarks'])): ?>
                                                                <div class="row mt-3">
                                                                    <div class="col-12">
                                                                        <h6 class="border-bottom pb-2">Container Remarks</h6>
                                                                        <p><?php echo nl2br(htmlspecialchars($container['remarks'])); ?></p>
                                                                    </div>
                                                                </div>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php elseif ($cargo_type == 'Loose Cargo'): ?>
                                                <!-- Loose Cargo Information Section -->
                                                <?php
                                                // Get loose cargo items
                                                $loose_cargo_query = "SELECT * FROM loose_cargo_items WHERE file_number = ? ORDER BY id ASC";
                                                $loose_cargo_stmt = $conn->prepare($loose_cargo_query);
                                                $loose_cargo_stmt->bind_param('s', $file_number);
                                                $loose_cargo_stmt->execute();
                                                $loose_cargo_result = $loose_cargo_stmt->get_result();
                                                $loose_cargo_items = [];
                                                
                                                if ($loose_cargo_result->num_rows > 0) {
                                                    while ($row = $loose_cargo_result->fetch_assoc()) {
                                                        $loose_cargo_items[] = $row;
                                                    }
                                                }
                                                ?>
                                                
                                                <?php if (!empty($loose_cargo_items)): ?>
                                                    <div class="table-responsive">
                                                        <table class="table table-bordered table-hover">
                                                            <thead class="table-light">
                                                                <tr>
                                                                    <th>#</th>
                                                                    <th>Chassis/Item Number</th>
                                                                    <th>Car Model/Description</th>
                                                                    <th>CBM</th>
                                                                    <th>Transporter</th>
                                                                    <th>Driver</th>
                                                                    <th>Remarks</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php foreach ($loose_cargo_items as $index => $item): ?>
                                                                <tr>
                                                                    <td><?php echo $index + 1; ?></td>
                                                                    <td><?php echo htmlspecialchars($item['chassis_number']); ?></td>
                                                                    <td><?php echo htmlspecialchars($item['car_model']); ?></td>
                                                                    <td><?php echo number_format($item['cbm'], 2); ?></td>
                                                                    <td><?php echo htmlspecialchars($item['transporter']); ?></td>
                                                                    <td>
                                                                        <?php if (!empty($item['driver_name'])): ?>
                                                                            <?php echo htmlspecialchars($item['driver_name']); ?><br>
                                                                            <?php if (!empty($item['driver_phone'])): ?>
                                                                                <small><?php echo htmlspecialchars($item['driver_phone']); ?></small>
                                                                            <?php endif; ?>
                                                                        <?php else: ?>
                                                                            <span class="text-muted">Not assigned</span>
                                                                        <?php endif; ?>
                                                                    </td>
                                                                    <td><?php echo htmlspecialchars($item['remarks']); ?></td>
                                                                </tr>
                                                                <?php endforeach; ?>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    
                                                    <!-- Aggregate Information -->
                                                    <div class="card mt-4">
                                                        <div class="card-header bg-light">
                                                            <h5 class="mb-0">Cargo Summary</h5>
                                                        </div>
                                                        <div class="card-body">
                                                            <div class="row">
                                                                <div class="col-md-4">
                                                                    <div class="border rounded p-3 text-center">
                                                                        <h3><?php echo count($loose_cargo_items); ?></h3>
                                                                        <p class="mb-0 text-muted">Total Items</p>
                                                                    </div>
                                                                </div>
                                                                <div class="col-md-4">
                                                                    <div class="border rounded p-3 text-center">
                                                                        <?php
                                                                        $total_cbm = 0;
                                                                        foreach ($loose_cargo_items as $item) {
                                                                            $total_cbm += floatval($item['cbm']);
                                                                        }
                                                                        ?>
                                                                        <h3><?php echo number_format($total_cbm, 2); ?></h3>
                                                                        <p class="mb-0 text-muted">Total CBM</p>
                                                                    </div>
                                                                </div>
                                                                <div class="col-md-4">
                                                                    <div class="border rounded p-3 text-center">
                                                                        <?php
                                                                        $transporters = [];
                                                                        foreach ($loose_cargo_items as $item) {
                                                                            if (!empty($item['transporter']) && !in_array($item['transporter'], $transporters)) {
                                                                                $transporters[] = $item['transporter'];
                                                                            }
                                                                        }
                                                                        ?>
                                                                        <h3><?php echo count($transporters); ?></h3>
                                                                        <p class="mb-0 text-muted">Unique Transporters</p>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="alert alert-info">
                                                        <i class="ri-information-line me-2"></i>
                                                        No loose cargo items found for this shipment.
                                                    </div>
                                                <?php endif; ?>
                                            <?php elseif ($cargo_type == 'Bulk Cargo'): ?>
                                                <!-- Bulk Cargo Information Section -->
                                                <?php
                                                // Check if we have bulk cargo details in the files table
                                                $bulk_item_count = $file['bulk_item_count'] ?? 0;
                                                $bulk_cbm = $file['bulk_cbm'] ?? 0;
                                                
                                                // You might need to create this table or adapt existing ones based on your database structure
                                                $bulk_cargo_query = "SELECT * FROM bulk_cargo_details WHERE file_number = ? ORDER BY id ASC";
                                                $bulk_cargo_stmt = $conn->prepare($bulk_cargo_query);
                                                $bulk_cargo_stmt->bind_param('s', $file_number);
                                                $bulk_cargo_stmt->execute();
                                                $bulk_cargo_result = $bulk_cargo_stmt->get_result();
                                                $bulk_cargo_items = [];
                                                
                                                if ($bulk_cargo_result && $bulk_cargo_result->num_rows > 0) {
                                                    while ($row = $bulk_cargo_result->fetch_assoc()) {
                                                        $bulk_cargo_items[] = $row;
                                                    }
                                                }
                                                ?>
                                                
                                                <!-- Bulk Cargo Summary -->
                                                <div class="card mb-4">
                                                    <div class="card-header bg-light">
                                                        <h5 class="mb-0">Bulk Cargo Summary</h5>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="border rounded p-3 text-center">
                                                                    <h3><?php echo number_format($bulk_item_count); ?></h3>
                                                                    <p class="mb-0 text-muted">Total Items</p>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="border rounded p-3 text-center">
                                                                    <h3><?php echo number_format($bulk_cbm, 2); ?></h3>
                                                                    <p class="mb-0 text-muted">Total CBM</p>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <?php if (!empty($bulk_cargo_items)): ?>
                                                    <div class="table-responsive">
                                                        <table class="table table-bordered table-hover">
                                                            <thead class="table-light">
                                                                <tr>
                                                                    <th>#</th>
                                                                    <th>Item Description</th>
                                                                    <th>Quantity</th>
                                                                    <th>Weight (kg)</th>
                                                                    <th>CBM</th>
                                                                    <th>Transporter</th>
                                                                    <th>Remarks</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php foreach ($bulk_cargo_items as $index => $item): ?>
                                                                <tr>
                                                                    <td><?php echo $index + 1; ?></td>
                                                                    <td><?php echo htmlspecialchars($item['description']); ?></td>
                                                                    <td><?php echo number_format($item['quantity']); ?></td>
                                                                    <td><?php echo number_format($item['weight'], 2); ?></td>
                                                                    <td><?php echo number_format($item['cbm'], 2); ?></td>
                                                                    <td><?php echo htmlspecialchars($item['transporter'] ?? 'N/A'); ?></td>
                                                                    <td><?php echo htmlspecialchars($item['remarks'] ?? ''); ?></td>
                                                                </tr>
                                                                <?php endforeach; ?>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="alert alert-info">
                                                        <i class="ri-information-line me-2"></i>
                                                        No detailed bulk cargo items found for this shipment.
                                                    </div>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <!-- Other Cargo Types -->
                                                <div class="alert alert-info">
                                                    <div class="d-flex">
                                                        <div class="flex-shrink-0">
                                                            <i class="ri-information-line fs-24 align-middle me-2"></i>
                                                        </div>
                                                        <div class="flex-grow-1">
                                                            <p class="mb-0">Details for cargo type "<?php echo htmlspecialchars($c_type); ?>" are not available.</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (hasPermission($role_id, 'invoice')): ?>
                        <!-- File Charges Tab -->
                        <div class="tab-pane fade" id="file-charges" role="tabpanel" aria-labelledby="charges-tab">
                            <form action="save_pre_proforma.php" method="POST">
                                <input type="hidden" name="file_number" value="<?php echo $file_number; ?>">
                                <input type="hidden" name="file_id" value="<?php echo $file_id; ?>">
                                
                                <div class="row">
                                    <div class="col-lg-6">
                                        <div class="card">
                                            <div class="card-header">
                                                <h5>Operational Costs</h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="row">
                                                    <input type="hidden" name="currency" value="<?php echo $file['currency']; ?>">
                                                    <div class="col-sm-4">
                                                        <div class="form-group mb-3">
                                                            <label class="form-label">Agency Fees</label>
                                                            <input type="text" class="form-control" id="agency-fees" name="agency_fees" value="">
                                                        </div>
                                                    </div>
                                                    <div class="col-lg-4">
                                                        <label class="form-label">Vatable:</label>
                                                        <div class="row">
                                                            <div class="col-lg-6">
                                                                <div class="form-check">
                                                                    <input type="radio" class="form-check-input" id="customCheck1" name="vatable" value="Yes" onclick="toggleVat()">
                                                                    <label class="form-check-label" for="customCheck1">Yes</label>
                                                                </div>
                                                            </div>
                                                            <div class="col-lg-6">
                                                                <div class="form-check">
                                                                    <input type="radio" class="form-check-input" id="customCheck2" name="vatable" value="No" onclick="toggleVat()" checked>
                                                                    <label class="form-check-label" for="customCheck2">No</label>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="col-sm-4">
                                                        <div class="form-group mb-3">
                                                            <label class="form-label">VAT (18%)</label>
                                                            <input type="text" class="form-control" id="vat" name="vat" style="display:none;" readonly>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="col-lg-6">
                                        <div class="card">
                                            <div class="card-header">
                                                <h5>All In Charges</h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="row">
                                                    <div class="col-lg-5">
                                                        <label class="form-label">Available:</label>
                                                        <div class="row">
                                                            <div class="col-lg-6">
                                                                <div class="form-check">
                                                                    <input type="radio" class="form-check-input" id="customCheckA" name="allin" value="Yes" onclick="toggleAllIn()">
                                                                    <label class="form-check-label" for="customCheckA">Yes</label>
                                                                </div>
                                                            </div>
                                                            <div class="col-lg-6">
                                                                <div class="form-check">
                                                                    <input type="radio" class="form-check-input" id="customCheckB" name="allin" value="No" onclick="toggleAllIn()" checked>
                                                                    <label class="form-check-label" for="customCheckB">No</label>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="col-sm-7">
                                                        <div class="form-group mb-3">
                                                            <label class="form-label">All In Amount</label>
                                                            <input type="text" class="form-control" id="all-in" name="all_in_amount" style="display:none;" value="">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-lg-12">
                                        <div class="card">
                                            <div class="card-header d-flex justify-content-between align-items-center">
                                                <h5 class="mb-0">Non-Operational Costs</h5>
                                                <button type="button" class="btn btn-primary btn-sm" id="add-row-btn">
                                                    <i class="ri-add-line align-middle"></i> Add Row
                                                </button>
                                            </div>
                                            <div class="card-body">
                                                <div id="cost-container">
                                                    <div class="row mb-3 cost-row">
                                                        <div class="col-sm-6">
                                                            <label class="form-label">Select Non-Operational Cost</label>
                                                            <select class="form-control cost-reference" name="cost_reference[]">
                                                                <?php
                                                                include('layouts/dbconn.php');
                                                                // Reconnect to the database as the connection was closed earlier
                                                                //$conn = new mysqli($servername, $username, $password, $dbname);
                                                                //if ($conn->connect_error) {
                                                                //    die("Connection failed: " . $conn->connect_error);
                                                                //}

                                                                $sql = "SELECT code, description FROM cost_reference WHERE category = 'Non-Operational'";
                                                                $result = $conn->query($sql);

                                                                echo "<option value=''>Please Select Cost</option>"; // This line adds the initial option

                                                                if ($result->num_rows > 0) {
                                                                    while($row = $result->fetch_assoc()) {
                                                                        // Concatenate the code and description
                                                                        $option_label = $row['code'] . ' - ' . $row['description'];
                                                                        echo "<option value='" . $row['code'] . "'>" . $option_label . "</option>";
                                                                    }
                                                                } else {
                                                                    echo "<option value=''>No options found</option>";
                                                                }
                                                                $conn->close();
                                                                ?>
                                                            </select>
                                                        </div>
                                                        <div class="col-sm-4">
                                                            <div class="form-group">
                                                                <label class="form-label">Enter Charge</label>
                                                                <input type="text" class="form-control charge-input" placeholder="Enter value" name="charge[]">
                                                            </div>
                                                        </div>
                                                        <div class="col-sm-2 d-flex align-items-end">
                                                            <button type="button" class="btn btn-danger btn-sm remove-row" style="display: none;">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-12 text-end">
                                        <a href="file_list.php" class="btn btn-outline-secondary me-2">Cancel</a>
                                        <button type="submit" class="btn btn-primary">Save Charges</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                        
                        <?php if ($num_pre_proforma_records > 0): ?>
                        <!-- Pre-Proforma Invoice Tab -->
                        <div class="tab-pane fade" id="pre-proforma" role="tabpanel" aria-labelledby="pre-proforma-tab">
                            <div class="row">
                                <div class="col-12">
                                    <div class="card">
                                        <div class="card-header d-flex justify-content-between align-items-center">
                                            <h4 class="card-title mb-0">Pre-Proforma Invoice</h4>
                                            <div>
                                                <a href="edit_pre_proforma.php?file_number=<?php echo $file_number; ?>" class="btn btn-sm btn-info">
                                                    <i class="ri-edit-box-line me-1"></i> Edit Charges
                                                </a>
                                                <?php if ($can_approve && $num_proforma_records == 0): ?>
                                                <button id="sendToProforma" class="btn btn-sm btn-primary ms-2">
                                                    <i class="ri-file-transfer-line me-1"></i> Send to Proforma
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="table-responsive">
                                                <table class="table table-bordered table-hover">
                                                    <thead class="table-light">
                                                        <tr>
                                                            <th>Category</th>
                                                            <th>Cost Code</th>
                                                            <th>Description</th>
                                                            <th class="text-end">Charge</th>
                                                            <th>Vatable</th>
                                                            <th class="text-end">VAT Amount</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php
                                                        // Reconnect to the database
                                                        $conn = new mysqli($servername, $username, $password, $dbname);
                                                        if ($conn->connect_error) {
                                                            die("Connection failed: " . $conn->connect_error);
                                                        }
                                                        
                                                        $query = "SELECT * FROM pre_proforma WHERE file_number = '$file_number'";
                                                        $result = $conn->query($query);
                                                        
                                                        $total_charge = 0;
                                                        $total_vat = 0;
                                                        $all_in_amount = 0;
                                                        $currency = $file['currency'];
                                                        
                                                        if ($result->num_rows > 0) {
                                                            while ($row = $result->fetch_assoc()) {
                                                                if ($row['all_in'] == 'Yes') {
                                                                    $all_in_amount = $row['all_in_amount'];
                                                                }
                                                                echo "<tr>";
                                                                echo "<td>" . htmlspecialchars($row['category']) . "</td>";
                                                                echo "<td>" . htmlspecialchars($row['cost_code']) . "</td>";
                                                                echo "<td>" . htmlspecialchars($row['cost_description']) . "</td>";
                                                                echo "<td class='text-end'>" . $currency . " " . number_format($row['charge'], 2) . "</td>";
                                                                echo "<td>" . htmlspecialchars($row['vatable']) . "</td>";
                                                                echo "<td class='text-end'>" . $currency . " " . number_format($row['vat_amount'], 2) . "</td>";
                                                                echo "</tr>";
                                                                
                                                                $total_charge += $row['charge'];
                                                                $total_vat += $row['vat_amount'];
                                                            }
                                                        } else {
                                                            echo "<tr><td colspan='7' class='text-center'>No pre-proforma data found</td></tr>";
                                                        }
                                                        $conn->close();
                                                        ?>
                                                    </tbody>
                                                    <tfoot>
                                                        <tr class="table-light fw-bold">
                                                            <td colspan="3" class="text-end">Total:</td>
                                                            <td class="text-end"><?php echo $currency . " " . number_format($total_charge, 2); ?></td>
                                                            <td></td>
                                                            <td class="text-end"><?php echo $currency . " " . number_format($total_vat, 2); ?></td>
                                                        </tr>
                                                        <tr class="table-primary fw-bold">
                                                            <td colspan="3" class="text-end">Grand Total (incl. VAT):</td>
                                                            <td colspan="3" class="text-end"><?php echo $currency . " " . number_format($total_charge + $total_vat, 2); ?></td>
                                                        </tr>
                                                        <?php if ($all_in_amount > 0): ?>
                                                        <tr class="table-success fw-bold">
                                                            <td colspan="3" class="text-end">All-In Amount:</td>
                                                            <td colspan="3" class="text-end"><?php echo $currency . " " . number_format($all_in_amount, 2); ?></td>
                                                        </tr>
                                                        <?php endif; ?>
                                                    </tfoot>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($num_proforma_records > 0): ?>
                        <!-- Proforma Invoice Tab -->
                        <div class="tab-pane fade" id="proforma" role="tabpanel" aria-labelledby="proforma-tab">
                            <div class="row">
                                <div class="col-12">
                                    <div class="card">
                                        <div class="card-header d-flex justify-content-between align-items-center">
                                            <h4 class="card-title mb-0">Proforma Invoice</h4>
                                            <div>
                                                <a href="view_proforma.php?file_number=<?php echo $file_number; ?>" class="btn btn-sm btn-success">
                                                    <i class="ri-eye-line me-1"></i> View Proforma
                                                </a>
                                                <?php if ($can_invoice): ?>
    <?php if ($invoice_exists): ?>
    <a href="view_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" class="btn btn-info">
        <i class="ri-eye-line align-bottom me-1"></i> View Invoice #<?php echo $invoice['invoice_number']; ?>
    </a>
    <?php else: ?>
    <a href="create_invoice.php?file_id=<?php echo $file_id; ?>" class="btn btn-warning">
        <i class="ri-bill-line align-bottom me-1"></i> Create Invoice
    </a>
    <?php endif; ?>
<?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="table-responsive">
                                                <table class="table table-bordered table-hover">
                                                    <thead class="table-light">
                                                        <tr>
                                                            <th>Category</th>
                                                            <th>Cost Code</th>
                                                            <th>Description</th>
                                                            <th class="text-end">Charge</th>
                                                            <th>Vatable</th>
                                                            <th class="text-end">VAT Amount</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php
                                                        // Reconnect to the database
                                                        $conn = new mysqli($servername, $username, $password, $dbname);
                                                        if ($conn->connect_error) {
                                                            die("Connection failed: " . $conn->connect_error);
                                                        }
                                                        
                                                        $query = "SELECT * FROM proforma WHERE file_number = '$file_number'";
                                                        $result = $conn->query($query);
                                                        
                                                        $total_charge = 0;
                                                        $total_vat = 0;
                                                        $all_in_amount = 0;
                                                        $currency = $file['currency'];
                                                        
                                                        if ($result->num_rows > 0) {
                                                            while ($row = $result->fetch_assoc()) {
                                                                if ($row['all_in'] == 'Yes') {
                                                                    $all_in_amount = $row['all_in_amount'];
                                                                }
                                                                echo "<tr>";
                                                                echo "<td>" . htmlspecialchars($row['category']) . "</td>";
                                                                echo "<td>" . htmlspecialchars($row['cost_code']) . "</td>";
                                                                echo "<td>" . htmlspecialchars($row['cost_description']) . "</td>";
                                                                echo "<td class='text-end'>" . $currency . " " . number_format($row['charge'], 2) . "</td>";
                                                                echo "<td>" . htmlspecialchars($row['vatable']) . "</td>";
                                                                echo "<td class='text-end'>" . $currency . " " . number_format($row['vat_amount'], 2) . "</td>";
                                                                echo "</tr>";
                                                                
                                                                $total_charge += $row['charge'];
                                                                $total_vat += $row['vat_amount'];
                                                            }
                                                        } else {
                                                            echo "<tr><td colspan='7' class='text-center'>No proforma data found</td></tr>";
                                                        }
                                                        
                                                        // Check if an invoice exists for this file
                                                        $invoice_query = "SELECT invoice_id, invoice_number, total_amount, status FROM invoices WHERE file_number = '$file_number' LIMIT 1";
                                                        $invoice_result = $conn->query($invoice_query);
                                                        $invoice_exists = ($invoice_result && $invoice_result->num_rows > 0);
                                                        $invoice = $invoice_exists ? $invoice_result->fetch_assoc() : null;
                                                        
                                                        $conn->close();
                                                        ?>
                                                    </tbody>
                                                    <tfoot>
                                                        <tr class="table-light fw-bold">
                                                            <td colspan="3" class="text-end">Total:</td>
                                                            <td class="text-end"><?php echo $currency . " " . number_format($total_charge, 2); ?></td>
                                                            <td></td>
                                                            <td class="text-end"><?php echo $currency . " " . number_format($total_vat, 2); ?></td>
                                                        </tr>
                                                        <tr class="table-primary fw-bold">
                                                            <td colspan="3" class="text-end">Grand Total (incl. VAT):</td>
                                                            <td colspan="3" class="text-end"><?php echo $currency . " " . number_format($total_charge + $total_vat, 2); ?></td>
                                                        </tr>
                                                        <?php if ($all_in_amount > 0): ?>
                                                        <tr class="table-success fw-bold">
                                                            <td colspan="3" class="text-end">All-In Amount:</td>
                                                            <td colspan="3" class="text-end"><?php echo $currency . " " . number_format($all_in_amount, 2); ?></td>
                                                        </tr>
                                                        <?php endif; ?>
                                                    </tfoot>
                                                </table>
                                            </div>
                                            
                                            <?php if ($invoice_exists): ?>
                                            <div class="alert alert-info mt-4">
                                                <div class="d-flex">
                                                    <div class="flex-shrink-0">
                                                        <i class="ri-information-line fs-24 align-middle me-2"></i>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <h5 class="alert-heading">Invoice Information</h5>
                                                        <p class="mb-0">Invoice <a href="view_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" class="alert-link"><?php echo $invoice['invoice_number']; ?></a> has been created for this file with amount <?php echo $currency . ' ' . number_format($invoice['total_amount'], 2); ?>.</p>
                                                        <p class="mb-0">Status: <span class="badge bg-<?php echo $invoice['status'] == 'paid' ? 'success' : ($invoice['status'] == 'pending' ? 'warning' : 'danger'); ?>"><?php echo ucfirst($invoice['status']); ?></span></p>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php endif; ?>
                        
                        <!-- Timeline Tab -->
                        <div class="tab-pane fade" id="timeline" role="tabpanel" aria-labelledby="timeline-tab">
                            <div class="row">
                                <div class="col-12">
                                    <div class="card">
                                        <div class="card-header">
                                            <h4 class="card-title mb-0">File Timeline</h4>
                                        </div>
                                        <div class="card-body">
                                            <div class="vertical-timeline">
                                                <?php
                                                // Reconnect to database
                                                $conn = new mysqli($servername, $username, $password, $dbname);
                                                if ($conn->connect_error) {
                                                    die("Connection failed: " . $conn->connect_error);
                                                }
                                                
                                                // Get timeline events
                                                $events = [];
                                                
                                                // Add creation date
                                                $events[] = [
                                                    'date' => $file['created_date'],
                                                    'title' => 'File Created',
                                                    'description' => "File {$file_number} was created in the system.",
                                                    'icon' => 'ri-file-add-line',
                                                    'color' => 'primary'
                                                ];
                                                
                                                // Add pre-alert if exists
                                                if (!empty($file['pre_alert_received_date']) && $file['pre_alert_received_date'] != '0000-00-00 00:00:00') {
                                                    $events[] = [
                                                        'date' => $file['pre_alert_received_date'],
                                                        'title' => 'Pre-Alert Received',
                                                        'description' => "Pre-alert for shipment was received.",
                                                        'icon' => 'ri-notification-2-line',
                                                        'color' => 'info'
                                                    ];
                                                }
                                                
                                                // Add discharge date if exists
                                                if (!empty($file['discharge_date']) && $file['discharge_date'] != '0000-00-00 00:00:00') {
                                                    $events[] = [
                                                        'date' => $file['discharge_date'],
                                                        'title' => 'Cargo Discharged',
                                                        'description' => "Cargo was discharged at port.",
                                                        'icon' => 'ri-ship-line',
                                                        'color' => 'primary'
                                                    ];
                                                }
                                                
                                                // Add container events if transit
                                                if ($file_type == 2 && !empty($containers)) {
                                                    foreach ($containers as $container) {
                                                        // Delivery order events
                                                        if (!empty($container['delivery_order_apply_date']) && $container['delivery_order_apply_date'] != '0000-00-00') {
                                                            $events[] = [
                                                                'date' => $container['delivery_order_apply_date'],
                                                                'title' => 'Delivery Order Applied',
                                                                'description' => "Delivery order applied for container {$container['container_code']}.",
                                                                'icon' => 'ri-file-list-3-line',
                                                                'color' => 'dark'
                                                            ];
                                                        }
                                                        
                                                        if (!empty($container['delivery_order_received_date']) && $container['delivery_order_received_date'] != '0000-00-00') {
                                                            $events[] = [
                                                                'date' => $container['delivery_order_received_date'],
                                                                'title' => 'Delivery Order Received',
                                                                'description' => "Delivery order received for container {$container['container_code']}.",
                                                                'icon' => 'ri-file-check-line',
                                                                'color' => 'success'
                                                            ];
                                                        }
                                                        
                                                        // Transit specific events
                                                        if (!empty($container['truck_exit_date']) && $container['truck_exit_date'] != '0000-00-00') {
                                                            $events[] = [
                                                                'date' => $container['truck_exit_date'],
                                                                'title' => 'Truck Exit',
                                                                'description' => "Container {$container['container_code']} exited port on truck.",
                                                                'icon' => 'ri-truck-line',
                                                                'color' => 'warning'
                                                            ];
                                                        }
                                                        
                                                        if (!empty($container['truck_at_border_date']) && $container['truck_at_border_date'] != '0000-00-00') {
                                                            $events[] = [
                                                                'date' => $container['truck_at_border_date'],
                                                                'title' => 'Arrived at Border',
                                                                'description' => "Container {$container['container_code']} arrived at border.",
                                                                'icon' => 'ri-road-map-line',
                                                                'color' => 'info'
                                                            ];
                                                        }
                                                        
                                                        if (!empty($container['border_crossing_date']) && $container['border_crossing_date'] != '0000-00-00') {
                                                            $events[] = [
                                                                'date' => $container['border_crossing_date'],
                                                                'title' => 'Border Crossing',
                                                                'description' => "Container {$container['container_code']} crossed border.",
                                                                'icon' => 'ri-flag-line',
                                                                'color' => 'success'
                                                            ];
                                                        }
                                                        
                                                        if (!empty($container['delivery_date']) && $container['delivery_date'] != '0000-00-00') {
                                                            $events[] = [
                                                                'date' => $container['delivery_date'],
                                                                'title' => 'Delivery Completed',
                                                                'description' => "Container {$container['container_code']} delivered to destination.",
                                                                'icon' => 'ri-checkbox-circle-line',
                                                                'color' => 'success'
                                                            ];
                                                        }
                                                        
                                                        if (!empty($container['empty_return_date']) && $container['empty_return_date'] != '0000-00-00') {
                                                            $events[] = [
                                                                'date' => $container['empty_return_date'],
                                                                'title' => 'Empty Container Returned',
                                                                'description' => "Empty container {$container['container_code']} returned.",
                                                                'icon' => 'ri-arrow-go-back-line',
                                                                'color' => 'dark'
                                                            ];
                                                        }
                                                    }
                                                }
                                                
                                                // Add local shipment events
                                                if ($file_type == 1) {
                                                    if (!empty($file['load_date']) && $file['load_date'] != '0000-00-00 00:00:00') {
                                                        $events[] = [
                                                            'date' => $file['load_date'],
                                                            'title' => 'Load Date',
                                                            'description' => "Cargo was loaded.",
                                                            'icon' => 'ri-loader-line',
                                                            'color' => 'info'
                                                        ];
                                                    }
                                                    
                                                    if (!empty($file['offload_date']) && $file['offload_date'] != '0000-00-00 00:00:00') {
                                                        $events[] = [
                                                            'date' => $file['offload_date'],
                                                            'title' => 'Offload Date',
                                                            'description' => "Cargo was offloaded at destination.",
                                                            'icon' => 'ri-archive-line',
                                                            'color' => 'success'
                                                        ];
                                                    }
                                                }
                                                
                                                // Check if pre-proforma exists
                                                $pre_proforma_query = "SELECT MIN(created_at) as created_date FROM pre_proforma WHERE file_number = '$file_number'";
                                                $pre_proforma_result = $conn->query($pre_proforma_query);
                                                if ($pre_proforma_result && $pre_proforma_result->num_rows > 0) {
                                                    $pre_proforma_row = $pre_proforma_result->fetch_assoc();
                                                    if (!empty($pre_proforma_row['created_date'])) {
                                                        $events[] = [
                                                            'date' => $pre_proforma_row['created_date'],
                                                            'title' => 'Pre-Proforma Created',
                                                            'description' => "Pre-proforma invoice was created for this file.",
                                                            'icon' => 'ri-draft-line',
                                                            'color' => 'primary'
                                                        ];
                                                    }
                                                }
                                                
                                                // Check if proforma exists
                                                $proforma_query = "SELECT MIN(created_at) as created_date FROM proforma WHERE file_number = '$file_number'";
                                                $proforma_result = $conn->query($proforma_query);
                                                if ($proforma_result && $proforma_result->num_rows > 0) {
                                                    $proforma_row = $proforma_result->fetch_assoc();
                                                    if (!empty($proforma_row['created_date'])) {
                                                        $events[] = [
                                                            'date' => $proforma_row['created_date'],
                                                            'title' => 'Proforma Created',
                                                            'description' => "Proforma invoice was finalized for this file.",
                                                            'icon' => 'ri-file-list-line',
                                                            'color' => 'success'
                                                        ];
                                                    }
                                                }
                                                
                                                // Check if invoice exists
                                                $invoice_query = "SELECT invoice_number, issue_date, status FROM invoices WHERE file_number = '$file_number'";
                                                $invoice_result = $conn->query($invoice_query);
                                                if ($invoice_result && $invoice_result->num_rows > 0) {
                                                    $invoice_row = $invoice_result->fetch_assoc();
                                                    $events[] = [
                                                        'date' => $invoice_row['issue_date'],
                                                        'title' => 'Invoice Created',
                                                        'description' => "Invoice {$invoice_row['invoice_number']} was created.",
                                                        'icon' => 'ri-bill-line',
                                                        'color' => 'warning'
                                                    ];
                                                    
                                                   /* if ($invoice_row['status'] == 'paid') {
                                                        // Get payment date (this is hypothetical, you'll need to adjust based on your database structure)
                                                        $payment_query = "SELECT payment_date FROM payments WHERE invoice_number = '{$invoice_row['invoice_number']}' LIMIT 1";
                                                        $payment_result = $conn->query($payment_query);
                                                        $payment_date = null;
                                                        if ($payment_result && $payment_result->num_rows > 0) {
                                                            $payment_row = $payment_result->fetch_assoc();
                                                            $payment_date = $payment_row['payment_date'];
                                                        }
                                                        
                                                        $events[] = [
                                                            'date' => $payment_date ?? date('Y-m-d H:i:s'), // Fallback to current date if no payment date
                                                            'title' => 'Payment Received',
                                                            'description' => "Payment received for invoice {$invoice_row['invoice_number']}.",
                                                            'icon' => 'ri-money-dollar-circle-line',
                                                            'color' => 'success'
                                                        ];
                                                    }*/
                                                }
                                                
                                                // Sort events by date
                                                usort($events, function($a, $b) {
                                                    return strtotime($a['date']) - strtotime($b['date']);
                                                });
                                                
                                                $conn->close();
                                                
                                                // Display events
                                                if (!empty($events)):
                                                    foreach ($events as $index => $event):
                                                ?>
                                                <div class="timeline-item">
                                                    <div class="timeline-item-date">
                                                        <?php echo date('M d, Y', strtotime($event['date'])); ?>
                                                        <small><?php echo date('h:i A', strtotime($event['date'])); ?></small>
                                                    </div>
                                                    <div class="timeline-item-content">
                                                        <div class="timeline-item-icon bg-light-<?php echo $event['color']; ?>">
                                                            <i class="<?php echo $event['icon']; ?>"></i>
                                                        </div>
                                                        <div class="timeline-item-box">
                                                            <h4 class="mb-1"><?php echo $event['title']; ?></h4>
                                                            <p class="mb-0"><?php echo $event['description']; ?></p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <?php 
                                                    endforeach;
                                                else:
                                                ?>
                                                <div class="text-center py-5">
                                                    <div class="avatar-md mx-auto mb-3">
                                                        <div class="avatar-title bg-light text-primary rounded-circle">
                                                            <i class="ri-history-line fs-24"></i>
                                                        </div>
                                                    </div>
                                                    <h5 class="text-muted">No timeline events available</h5>
                                                    <p class="text-muted">This file doesn't have any recorded events yet.</p>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <!-- Delete Confirmation Modal -->
    <?php if ($can_delete): ?>
    <div class="modal fade" id="deleteFileModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-light p-3">
                    <h5 class="modal-title">Confirm Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete shipment file <strong><?php echo htmlspecialchars($file['file_number']); ?></strong>?</p>
                    <p class="text-danger"><strong>Warning:</strong> This action cannot be undone and will remove all associated data including containers, charges, and shipping records.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <form method="POST" action="delete_file.php">
                        <input type="hidden" name="file_id" value="<?php echo $file_id; ?>">
                        <button type="submit" class="btn btn-danger">Delete File</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <!-- Tab Navigation Script -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
    // Initialize Select2 and setup event listeners
    initializeSelect2Elements();
    setupEventListeners();
});

function initializeSelect2Elements() {
    $('.cost-reference').each(function() {
        if (!$(this).hasClass('select2-hidden-accessible')) {
            $(this).select2({
                placeholder: 'Select a cost reference',
                allowClear: true,
                width: '100%'
            });
        }
    });
}

function setupEventListeners() {
    // All In toggle
    const allinRadios = document.querySelectorAll('input[name="allin"]');
    allinRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            toggleAllIn();
            calculateAgencyFees();
        });
    });

    // All In amount change
    const allInInput = document.getElementById('all-in');
    if (allInInput) {
        allInInput.addEventListener('input', calculateAgencyFees);
    }

    // Add row button
    const addRowBtn = document.getElementById('add-row-btn');
    const container = document.getElementById('cost-container');
    if (addRowBtn && container) {
        addRowBtn.addEventListener('click', function() {
            addNewRow(container);
        });
        
        // Delegate event for removing rows
        container.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-row') || e.target.closest('.remove-row')) {
                const row = e.target.closest('.cost-row');
                removeRow(row, container);
                calculateAgencyFees();
            }
        });
        
        // Delegate for charge input changes
        container.addEventListener('input', function(e) {
            if (e.target.classList.contains('charge-input')) {
                calculateAgencyFees();
            }
        });
    }

    // Vatable radios
    const vatableRadios = document.querySelectorAll('input[name="vatable"]');
    vatableRadios.forEach(radio => {
        radio.addEventListener('change', toggleVat);
    });

    // Initial calculations
    toggleAllIn();
    toggleVat();
    calculateAgencyFees();
}

function toggleAllIn() {
    const allinTextbox = document.getElementById("all-in");
    const allinYes = document.getElementById("customCheckA");
    
    if (allinTextbox && allinYes) {
        allinTextbox.style.display = allinYes.checked ? "block" : "none";
    }
}

function toggleVat() {
    const vatTextbox = document.getElementById("vat");
    const vatableYes = document.getElementById("customCheck1");
    
    if (vatTextbox && vatableYes) {
        vatTextbox.style.display = vatableYes.checked ? "block" : "none";
        calculateVAT();
    }
}

function calculateVAT() {
    const agencyFeesInput = document.getElementById('agency-fees');
    const vatInput = document.getElementById('vat');
    const vatableYes = document.getElementById("customCheck1");
    
    if (vatableYes && vatableYes.checked && agencyFeesInput && vatInput && agencyFeesInput.value) {
        const agencyFeesValue = parseFloat(agencyFeesInput.value);
        if (!isNaN(agencyFeesValue)) {
            const vatValue = agencyFeesValue * 0.18;
            vatInput.value = vatValue.toFixed(2);
        }
    } else if (vatInput) {
        vatInput.value = '';
    }
}

function calculateAgencyFees() {
    const allInRadio = document.getElementById('customCheckA');
    const allInInput = document.getElementById('all-in');
    const agencyFeesInput = document.getElementById('agency-fees');
    
    if (!allInRadio || !allInRadio.checked || !allInInput || !agencyFeesInput) {
        return;
    }
    
    const allInValue = parseFloat(allInInput.value);
    if (isNaN(allInValue)) {
        agencyFeesInput.value = '';
        return;
    }
    
    // Calculate sum of non-operational costs
    let nonOpCostsTotal = 0;
    const chargeInputs = document.querySelectorAll('.charge-input');
    chargeInputs.forEach(input => {
        const value = parseFloat(input.value);
        if (!isNaN(value)) {
            nonOpCostsTotal += value;
        }
    });
    
    // Calculate agency fees: All In Amount - (sum of non-operational costs)
    const agencyFees = allInValue - nonOpCostsTotal;
    agencyFeesInput.value = agencyFees.toFixed(2);
    
    // Recalculate VAT if needed
    calculateVAT();
}

function addNewRow(container) {
    const firstRow = container.querySelector('.cost-row');
    if (!firstRow) return;
    
    // Clone the row
    const newRow = firstRow.cloneNode(true);
    
    // Reset values
    const inputs = newRow.querySelectorAll('input');
    inputs.forEach(input => input.value = '');
    
    const select = newRow.querySelector('select.cost-reference');
    if (select) {
        // Reset select
        select.innerHTML = firstRow.querySelector('select.cost-reference').innerHTML;
        select.selectedIndex = 0;
        
        // Clean up any existing Select2
        $(select).removeData();
        $(select).removeClass('select2-hidden-accessible');
        const selectContainer = newRow.querySelector('.select2-container');
        if (selectContainer) {
            selectContainer.parentNode.removeChild(selectContainer);
        }
    }
    
    // Show remove button
    const removeBtn = newRow.querySelector('.remove-row');
    if (removeBtn) {
        removeBtn.style.display = 'block';
    }
    
    // Add to container
    container.appendChild(newRow);
    
    // Initialize Select2
    const newSelect = newRow.querySelector('select.cost-reference');
    if (newSelect) {
        $(newSelect).select2({
            placeholder: 'Select a cost reference',
            allowClear: true,
            width: '100%'
        });
    }

    // Recalculate after adding row
    calculateAgencyFees();
}

function removeRow(row, container) {
    if (container.querySelectorAll('.cost-row').length > 1) {
        // Destroy Select2 if exists
        const select = row.querySelector('select.cost-reference');
        if (select && $(select).hasClass('select2-hidden-accessible')) {
            try {
                $(select).select2('destroy');
            } catch (err) {
                console.log('Error destroying Select2:', err);
                $(select).removeClass('select2-hidden-accessible');
                const selectContainer = row.querySelector('.select2-container');
                if (selectContainer) {
                    selectContainer.parentNode.removeChild(selectContainer);
                }
            }
        }
        row.remove();
    }
}
    </script>
    <script>
        // Function to handle the "Send to Proforma" button click
document.addEventListener('DOMContentLoaded', function() {
    const sendToProformaBtn = document.getElementById('sendToProforma');
    
    if (sendToProformaBtn) {
        sendToProformaBtn.addEventListener('click', function() {
            // Show confirmation dialog
            Swal.fire({
                title: 'Convert to Proforma?',
                text: "This will move pre-proforma data to final proforma. This action cannot be undone!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, convert it!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Get file number from the page
                    const fileNumber = document.querySelector('input[name="file_number"]') ? 
                                       document.querySelector('input[name="file_number"]').value : 
                                       window.location.href.split('file_number=')[1]?.split('&')[0];
                    
                    if (!fileNumber) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Could not determine file number!'
                        });
                        return;
                    }
                    
                    // Create and submit the form
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = 'send_to_proforma.php';
                    form.style.display = 'none';
                    
                    const fileNumberInput = document.createElement('input');
                    fileNumberInput.type = 'hidden';
                    fileNumberInput.name = 'file_number';
                    fileNumberInput.value = fileNumber;
                    
                    form.appendChild(fileNumberInput);
                    document.body.appendChild(form);
                    
                    // Show loading state
                    Swal.fire({
                        title: 'Processing...',
                        text: 'Converting pre-proforma to proforma invoice',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    // Submit the form
                    form.submit();
                }
            });
        });
    }
});
    </script>
    <script>
document.addEventListener('DOMContentLoaded', function() {
    // Check if there's a success message about proforma conversion
    <?php if (isset($_SESSION['success_message']) && 
              strpos($_SESSION['success_message'], 'pre-proforma successfully converted') !== false): ?>
    
    // Try to find and click the proforma tab
    const proformaTab = document.getElementById('proforma-tab');
    if (proformaTab) {
        // Use Bootstrap's tab API to show the tab
        const bsTab = new bootstrap.Tab(proformaTab);
        bsTab.show();
        
        // Scroll to the top of the page
        window.scrollTo(0, 0);
        
        // Add a highlight effect to the proforma section
        const proformaSection = document.getElementById('proforma');
        if (proformaSection) {
            proformaSection.classList.add('highlight-section');
            setTimeout(() => {
                proformaSection.classList.remove('highlight-section');
            }, 2000);
        }
    }
    <?php endif; ?>
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize all tabs
    var tabElements = document.querySelectorAll('button[data-bs-toggle="tab"]');
    tabElements.forEach(function(tabElement) {
        tabElement.addEventListener('click', function(event) {
            event.preventDefault();
            var tab = new bootstrap.Tab(this);
            tab.show();
        });
    });

    // Check if there's a tab to show from URL hash
    if (window.location.hash) {
        const hash = window.location.hash;
        const tab = document.querySelector('button[data-bs-target="' + hash + '"]');
        if (tab) {
            var bsTab = new bootstrap.Tab(tab);
            bsTab.show();
        }
    }

    // Add hash to URL when tab changes
    var tabs = document.querySelectorAll('button[data-bs-toggle="tab"]')
    tabs.forEach(function(tab) {
        tab.addEventListener('shown.bs.tab', function(event) {
            window.location.hash = event.target.getAttribute('data-bs-target').substring(1);
        });
    });
});

// Function to switch to a specific tab programmatically
function switchToTab(tabId) {
    const tab = document.querySelector('button[data-bs-target="#' + tabId + '"]');
    if (tab) {
        const bsTab = new bootstrap.Tab(tab);
        bsTab.show();
    }
}
</script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Show success message if present
        <?php if (isset($_SESSION['swal_success'])): ?>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: '<?php echo $_SESSION['swal_success']; ?>',
            confirmButtonColor: '#3085d6'
        });
        <?php unset($_SESSION['swal_success']); ?>
        <?php endif; ?>

        // Show error message if present
        <?php if (isset($_SESSION['swal_error'])): ?>
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: '<?php echo $_SESSION['swal_error']; ?>',
            confirmButtonColor: '#3085d6'
        });
        <?php unset($_SESSION['swal_error']); ?>
        <?php endif; ?>
    });
</script>
<style>
.highlight-section {
    animation: highlightSection 2s ease;
}

@keyframes highlightSection {
    0% { background-color: rgba(25, 135, 84, 0.1); }
    50% { background-color: rgba(25, 135, 84, 0.2); }
    100% { background-color: transparent; }
}
</style>
	<style>
        /* Timeline styles */
        .vertical-timeline {
            position: relative;
            padding: 2rem 0;
        }
        
        .timeline-item {
            position: relative;
            display: flex;
            margin-bottom: 2rem;
        }
        
        .timeline-item:last-child {
            margin-bottom: 0;
        }
        
        .timeline-item-date {
            flex: 0 0 120px;
            margin-right: 1.5rem;
            text-align: right;
            color: #6c757d;
            padding-top: 0.25rem;
        }
        
        .timeline-item-date small {
            display: block;
            font-size: 0.75rem;
            opacity: 0.7;
        }
        
        .timeline-item-content {
            position: relative;
            flex: 1;
            padding-left: 3rem;
        }
        
        .timeline-item-content:before {
            content: '';
            position: absolute;
            left: 0;
            top: 1.5rem;
            bottom: -2.5rem;
            width: 2px;
            background-color: #e9e9ef;
        }
        
        .timeline-item:last-child .timeline-item-content:before {
            display: none;
        }
        
        .timeline-item-icon {
            position: absolute;
            left: -10px;
            top: 0;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1;
        }
        
        .timeline-item-icon i {
            font-size: 11px;
        }
        
        .timeline-item-box {
            background-color: #f8f9fa;
            border-radius: 0.25rem;
            padding: 1rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        
        /* Cost container styles */
        .cost-row {
            position: relative;
            padding: 0.75rem;
            border-radius: 0.25rem;
            transition: background-color 0.2s;
        }
        
        .cost-row:hover {
            background-color: #f8f9fa;
        }
        
        .remove-row {
            margin-bottom: 1rem;
        }
        
        /* Select2 custom styling */
        .select2-container--default .select2-selection--single {
            height: 38px;
            border-color: #ced4da;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
    </style>
</body>
</html>