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

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

// Get user details for permission checks
$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'];
}

// Function to 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;
}

// Check if user has permission to view and edit all-in amounts
$can_view = hasPermission($role_id, 'view');
$can_edit = hasPermission($role_id, 'edit') || hasPermission($role_id, 'approve');

if (!$can_view) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// 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));
}

// Handle search parameters
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';

// 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' => 'All-In Amounts List')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="assets/libs/datatables/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/datatables/buttons.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/datatables/responsive.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .dataTables_filter {
            margin-bottom: 10px;
        }
        .search-box {
            position: relative;
        }
        .search-box .form-control {
            padding-left: 40px;
        }
        .search-box .search-icon {
            position: absolute;
            left: 13px;
            top: 50%;
            transform: translateY(-50%);
            color: #74788d;
        }
        .action-btn {
            margin-right: 5px;
        }
        .badge-all-in {
            padding: 5px 8px;
            font-size: 12px;
        }
    </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' => 'All-In Amounts List')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">Files with All-In Amounts</h5>
                                    <div>
                                        <a href="index.php" class="btn btn-primary btn-sm">
                                            <i class="ri-arrow-left-line align-bottom"></i> Back to Dashboard
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6 col-sm-12 mb-2 mb-md-0">
                                            <form action="" method="GET" class="d-flex">
                                                <div class="search-box flex-grow-1 me-2">
                                                    <input type="text" name="search" class="form-control search" placeholder="Search file number, customer, destination..." value="<?php echo htmlspecialchars($search); ?>">
                                                    <i class="ri-search-line search-icon"></i>
                                                </div>
                                                <button type="submit" class="btn btn-primary">Search</button>
                                            </form>
                                        </div>
                                        <div class="col-md-6 col-sm-12 text-md-end">
                                            <a href="update_all_in.php" class="btn btn-success">
                                                <i class="ri-add-line align-bottom"></i> Update All-In Amount
                                            </a>
                                        </div>
                                    </div>

                                    <div class="table-responsive">
                                        <table id="files-table" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>File Number</th>
                                                    <th>Customer</th>
                                                    <th>Destination</th>
                                                    <th>Created Date</th>
                                                    <th>All-In Amount</th>
                                                    <th>Agency Fee</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                // Base query for files with all-in amounts
                                                $sql = "
                                                    SELECT 
                                                        f.id, 
                                                        f.file_number, 
                                                        c.first_name AS customer_name,
                                                        f.destination, 
                                                        f.created_date,
                                                        f.currency,
                                                        p.all_in_amount,
                                                        COALESCE(pa.approved, 'Pending') AS approval_status,
                                                        (
                                                            SELECT pp.charge 
                                                            FROM pre_proforma pp 
                                                            WHERE pp.file_number = f.file_number 
                                                            AND pp.category = 'Operational' 
                                                            AND pp.cost_code = '1-101' 
                                                            LIMIT 1
                                                        ) AS agency_fee,
                                                        (
                                                            SELECT pp2.all_in 
                                                            FROM pre_proforma pp2 
                                                            WHERE pp2.file_number = f.file_number 
                                                            AND pp2.all_in = 'Yes' 
                                                            LIMIT 1
                                                        ) AS has_all_in,
                                                        (
                                                            SELECT COUNT(*) 
                                                            FROM proforma pr 
                                                            WHERE pr.file_number = f.file_number
                                                        ) AS has_proforma
                                                    FROM 
                                                        files f
                                                    LEFT JOIN 
                                                        customers c ON f.customer = c.customer_id
                                                    LEFT JOIN 
                                                        (SELECT file_number, all_in_amount FROM pre_proforma WHERE all_in = 'Yes' GROUP BY file_number) p 
                                                        ON f.file_number = p.file_number
                                                    LEFT JOIN
                                                        pending_approvals pa ON f.file_number = pa.file_number
                                                    WHERE 
                                                        p.all_in_amount IS NOT NULL
                                                ";
                                                
                                                // Add search condition if search parameter exists
                                                if (!empty($search)) {
                                                    $sql .= " AND (
                                                        f.file_number LIKE '%$search%' OR 
                                                        c.first_name LIKE '%$search%' OR 
                                                        f.destination LIKE '%$search%'
                                                    )";
                                                }
                                                
                                                $sql .= " ORDER BY f.created_date DESC";
                                                
                                                $result = $conn->query($sql);
                                                
                                                if ($result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        $file_id = $row['id'];
                                                        $file_number = $row['file_number'];
                                                        $customer_name = $row['customer_name'] ?: 'N/A';
                                                        $destination = $row['destination'];
                                                        $created_date = formatDate($row['created_date']);
                                                        $currency = $row['currency'];
                                                        $all_in_amount = $row['all_in_amount'];
                                                        $agency_fee = $row['agency_fee'];
                                                        $has_all_in = $row['has_all_in'] == 'Yes';
                                                        $has_proforma = $row['has_proforma'] > 0;
                                                        $status = $row['approval_status'];
                                                        
                                                        // Determine badge class for status
                                                        $status_badge_class = 'bg-warning';
                                                        if ($status == 'Approved') {
                                                            $status_badge_class = 'bg-success';
                                                        } elseif ($status == 'Rejected') {
                                                            $status_badge_class = 'bg-danger';
                                                        }
                                                        
                                                        echo "<tr>";
                                                        echo "<td><a href='view_file.php?id=$file_id' class='text-primary'>$file_number</a></td>";
                                                        echo "<td>$customer_name</td>";
                                                        echo "<td>$destination</td>";
                                                        echo "<td>$created_date</td>";
                                                        echo "<td>$currency " . number_format($all_in_amount, 2) . "</td>";
                                                        echo "<td>$currency " . number_format($agency_fee, 2) . "</td>";
                                                        echo "<td><span class='badge $status_badge_class'>$status</span></td>";
                                                        echo "<td class='text-center'>";
                                                        
                                                        // View button
                                                        echo "<a href='view_file.php?id=$file_id' class='btn btn-sm btn-info action-btn' title='View File'>";
                                                        echo "<i class='ri-eye-line'></i>";
                                                        echo "</a>";
                                                        
                                                        // Update button - only for admins and if not yet approved or has proforma
                                                        if ($can_edit && $status != 'Approved' && !$has_proforma) {
                                                            echo "<a href='update_all_in.php?file_number=$file_number' class='btn btn-sm btn-warning action-btn' title='Update All-In Amount'>";
                                                            echo "<i class='ri-edit-2-line'></i>";
                                                            echo "</a>";
                                                        }
                                                        
                                                        // Approve button - only for admins/managers and if pending
                                                        if (hasPermission($role_id, 'approve') && $status == 'Pending') {
                                                            echo "<a href='approve_all_in.php?file_number=$file_number' class='btn btn-sm btn-success action-btn' title='Approve All-In Amount'>";
                                                            echo "<i class='ri-check-line'></i>";
                                                            echo "</a>";
                                                        }
                                                        
                                                        echo "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='8' class='text-center'>No files with All-In amounts found</td></tr>";
                                                }
                                                
                                                $conn->close();
                                                ?>
                                            </tbody>
                                        </table>
                                    </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 -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Required datatable js -->
    <script src="assets/libs/datatables/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables/dataTables.bootstrap5.min.js"></script>
    <script src="assets/libs/datatables/dataTables.responsive.min.js"></script>
    <script src="assets/libs/datatables/responsive.bootstrap5.min.js"></script>
    
    <!-- Sweet Alerts js -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#files-table').DataTable({
                responsive: true,
                lengthChange: true,
                pageLength: 10,
                lengthMenu: [10, 25, 50, 100],
                dom: 'rtip', // Remove default search
                order: [[3, 'desc']], // Sort by created date by default
                language: {
                    emptyTable: "No files with All-In amounts found",
                    zeroRecords: "No matching files found"
                }
            });
            
            // Use custom search box
            $('.search').on('keyup', function() {
                $('#files-table').DataTable().search($(this).val()).draw();
            });
            
            // Show success message with SweetAlert 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']); endif; ?>
            
            // Show error message with SweetAlert 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']); endif; ?>
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>