<?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
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email 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'];
} else {
    // Handle case if user details are not found
}

// Set system name from settings
$sql = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $system_name = $row['setting_value'];
} else {
    $system_name = "Royal Freight"; // Fallback if not found
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Container Deposit List')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="assets/libs/datatables.net-bs4/css/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css">
    <link href="assets/libs/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css" rel="stylesheet" type="text/css">
    <link href="assets/libs/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" rel="stylesheet" type="text/css">
    
    <style>
        /* Type badges */
        .badge-fixed {
            background-color: #6c757d;
            color: white;
        }
        .badge-normal {
            background-color: #28a745;
            color: white;
        }
        .badge-additional {
            background-color: #007bff;
            color: white;
        }
        
        /* Balance text colors */
        .balance-available {
            color: #28a745;
            font-weight: bold;
        }
        .balance-zero {
            color: #dc3545;
            font-weight: bold;
        }
        .balance-na {
            color: #6c757d;
        }
        
        /* Status markers */
        .status-marker {
            display: inline-block;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .marker-available {
            background-color: #28a745; /* Green */
        }
        .marker-zero {
            background-color: #dc3545; /* Red */
        }
        .marker-fixed {
            background-color: #000000; /* Black */
        }
        
        /* Legend styles */
        .deposit-legend {
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            background-color: #f8f9fa;
        }
        .legend-item {
            display: inline-flex;
            align-items: center;
            margin-right: 20px;
            margin-bottom: 5px;
        }
        .legend-marker {
            display: inline-block;
            width: 12px;
            height: 12px;
            margin-right: 5px;
            border-radius: 50%;
        }
        
        /* Remarks tooltip */
        .remarks-tooltip {
            position: relative;
            cursor: pointer;
        }
        .remarks-tooltip .tooltip-text {
            visibility: hidden;
            width: 300px;
            background-color: #333;
            color: #fff;
            text-align: left;
            border-radius: 6px;
            padding: 8px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            transform: translateX(-50%);
            opacity: 0;
            transition: opacity 0.3s;
            white-space: normal;
            word-wrap: break-word;
        }
        .remarks-tooltip:hover .tooltip-text {
            visibility: visible;
            opacity: 1;
        }
        
        /* Table cell styling */
        .table td.actions-cell {
            white-space: nowrap;
        }
        .table td.remarks-cell {
            max-width: 150px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        /* Export button styling */
        .export-buttons {
            margin-bottom: 15px;
        }
        .export-buttons .btn {
            margin-right: 5px;
        }
    </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' => 'Container Deposit', 'title' => 'Deposit List')); ?>

                    <!-- Alert for messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title mb-0">Container Deposit List</h4>
                                    <a href="container_deposit.php" class="btn btn-primary">
                                        <i class="ri-add-line align-bottom"></i> Add New Deposit
                                    </a>
                                </div>
                                <div class="card-body">
                                    <!-- Status Legend -->
                                    <div class="deposit-legend">
                                        <div class="legend-title fw-bold mb-2">Legend:</div>
                                        <div class="d-flex flex-wrap">
                                            <div class="legend-item">
                                                <span class="legend-marker marker-available"></span>
                                                <span>Balance is available</span>
                                            </div>
                                            <div class="legend-item">
                                                <span class="legend-marker marker-zero"></span>
                                                <span>Balance is zero or not yet provided</span>
                                            </div>
                                            <div class="legend-item">
                                                <span class="legend-marker marker-fixed"></span>
                                                <span>Type is fixed</span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Export Buttons -->
                                    <div class="export-buttons">
                                        <button type="button" class="btn btn-sm btn-secondary" id="export-copy">
                                            <i class="ri-file-copy-2-line"></i> Copy
                                        </button>
                                        <button type="button" class="btn btn-sm btn-secondary" id="export-excel">
                                            <i class="ri-file-excel-2-line"></i> Excel
                                        </button>
                                        <button type="button" class="btn btn-sm btn-secondary" id="export-pdf">
                                            <i class="ri-file-pdf-line"></i> PDF
                                        </button>
                                        <button type="button" class="btn btn-sm btn-secondary" id="export-print">
                                            <i class="ri-printer-line"></i> Print
                                        </button>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table id="container-deposits-table" class="table table-bordered dt-responsive nowrap table-striped align-middle">
                                            <thead>
                                                <tr>
                                                    <th width="40">Status</th>
                                                    <th>Shipping Line</th>
                                                    <th>Type</th>
                                                    <th>BL</th>
                                                    <th>Container</th>
                                                    <th>Date Deposited</th>
                                                    <th>Deposit</th>
                                                    <th>Refund Amount</th>
                                                    <th>Balance</th>
                                                    <th>Refund Date</th>
                                                    <th>Status</th>
                                                    <th>Remarks</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                // Fetch all container deposits
                                                $query = "SELECT * FROM container_deposit ORDER BY created_date DESC";
                                                $result = $conn->query($query);
                                                
                                                if ($result && $result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        // Determine deposit amount based on type
                                                        $depositAmount = 0;
                                                        if (strtolower($row['type']) === 'fixed' && !empty($row['fixed_amount'])) {
                                                            $depositAmount = $row['fixed_amount'];
                                                        } else {
                                                            $depositAmount = $row['deposit'];
                                                        }
                                                        
                                                        // Calculate balance
                                                        $balance = $row['balance'];
                                                        if ($balance === null) {
                                                            $balance = $depositAmount - ($row['refund_amount'] ?? 0);
                                                        }
                                                        
                                                        // Determine status marker and balance class
                                                        $markerClass = '';
                                                        $balanceClass = '';
                                                        
                                                        if (strtolower($row['type']) === 'fixed') {
                                                            $markerClass = 'marker-fixed';
                                                            
                                                            if ($balance > 0) {
                                                                $balanceClass = 'balance-available';
                                                            } else {
                                                                $balanceClass = 'balance-zero';
                                                            }
                                                        } else {
                                                            if ($depositAmount > 0) {
                                                                if ($balance > 0) {
                                                                    $markerClass = 'marker-available';
                                                                    $balanceClass = 'balance-available';
                                                                } else {
                                                                    $markerClass = 'marker-zero';
                                                                    $balanceClass = 'balance-zero';
                                                                }
                                                            } else {
                                                                $markerClass = 'marker-zero';
                                                                $balanceClass = 'balance-na';
                                                            }
                                                        }
                                                        
                                                        echo "<tr>";
                                                        echo "<td class='text-center'><span class='status-marker {$markerClass}'></span></td>";
                                                        echo "<td>" . htmlspecialchars($row['shipping_line']) . "</td>";
                                                        
                                                        // Type badge
                                                        $typeBadge = 'badge-normal';
                                                        if (strtolower($row['type']) === 'fixed') {
                                                            $typeBadge = 'badge-fixed';
                                                        } elseif (strtolower($row['type']) === 'additional') {
                                                            $typeBadge = 'badge-additional';
                                                        }
                                                        echo "<td><span class='badge {$typeBadge}'>" . ucfirst($row['type']) . "</span></td>";
                                                        
                                                        echo "<td>" . htmlspecialchars($row['bl']) . "</td>";
                                                        echo "<td>" . htmlspecialchars($row['container'] ?? 'N/A') . "</td>";
                                                        echo "<td>" . ($row['date_deposited'] ? date('Y-m-d', strtotime($row['date_deposited'])) : 'N/A') . "</td>";
                                                        echo "<td class='text-end'>" . number_format($depositAmount, 2) . "</td>";
                                                        echo "<td class='text-end'>" . number_format($row['refund_amount'] ?? 0, 2) . "</td>";
                                                        echo "<td class='text-end {$balanceClass}'>" . number_format($balance, 2) . "</td>";
                                                        echo "<td>" . ($row['refund_date'] ? date('Y-m-d', strtotime($row['refund_date'])) : 'N/A') . "</td>";
                                                        
                                                        // Status column
                                                        echo "<td>";
                                                        if (!empty($row['refund_amount']) && $row['refund_amount'] > 0) {
                                                            $status = $row['payment_status'] ?? 'N/A';
                                                            if ($status === 'Pending') {
                                                                echo "<span class='badge bg-warning'>Pending</span>";
                                                            } elseif ($status === 'Approved') {
                                                                echo "<span class='badge bg-success'>Approved</span>";
                                                            } elseif ($status === 'Rejected') {
                                                                echo "<span class='badge bg-danger'>Rejected</span>";
                                                            } else {
                                                                echo "<span class='badge bg-secondary'>N/A</span>";
                                                            }
                                                        } else {
                                                            echo "-";
                                                        }
                                                        echo "</td>";
                                                        
                                                        // Remarks with tooltip
                                                        echo "<td class='remarks-cell'>";
                                                        if (!empty($row['remarks'])) {
                                                            echo "<div class='remarks-tooltip'>";
                                                            echo htmlspecialchars(substr($row['remarks'], 0, 30)) . (strlen($row['remarks']) > 30 ? '...' : '');
                                                            echo "<span class='tooltip-text'>" . htmlspecialchars($row['remarks']) . "</span>";
                                                            echo "</div>";
                                                        } else {
                                                            echo "-";
                                                        }
                                                        echo "</td>";
                                                        
                                                        // Actions
                                                        echo "<td class='actions-cell'>";
                                                        
                                                        // Only show refund button if there's a balance available
                                                        if ($balance > 0 && (!isset($row['payment_status']) || $row['payment_status'] !== 'Pending')) {
                                                            echo "<a href='container_deposit_refund.php?id=" . $row['id'] . "' class='btn btn-sm btn-primary me-1' title='Process Refund'>";
                                                            echo "<i class='ri-money-dollar-circle-line'></i></a>";
                                                        }
                                                        
                                                        echo "<a href='container_deposit_edit.php?id=" . $row['id'] . "' class='btn btn-sm btn-info me-1' title='Edit Deposit'>";
                                                        echo "<i class='ri-edit-2-line'></i></a>";
                                                        
                                                        echo "<button type='button' class='btn btn-sm btn-secondary view-details' data-id='" . $row['id'] . "' title='View Details'>";
                                                        echo "<i class='ri-eye-line'></i></button>";
                                                        
                                                        echo "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='13' class='text-center'>No container deposits found</td></tr>";
                                                }
                                                ?>
                                            </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 -->

    <!-- Details Modal -->
    <div class="modal fade" id="detailsModal" tabindex="-1" aria-labelledby="detailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="detailsModalLabel">Container Deposit Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="container-fluid" id="depositDetails">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2">Loading deposit details...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <?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>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.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>

    <script>
    $(document).ready(function() {
        // Initialize DataTable with export buttons
        var table = $('#container-deposits-table').DataTable({
            lengthChange: false,
            responsive: true,
            ordering: true,
            pageLength: 25,
            language: {
                search: "_INPUT_",
                searchPlaceholder: "Search deposits..."
            },
            columnDefs: [
                { orderable: false, targets: [0, 12] } // Disable sorting for status marker and actions columns
            ],
            buttons: [
                { extend: 'copy', className: 'btn-sm' },
                { extend: 'excel', className: 'btn-sm' },
                { extend: 'pdf', className: 'btn-sm' },
                { extend: 'print', className: 'btn-sm' }
            ]
        });
        
        // Custom export buttons
        $('#export-copy').on('click', function() {
            table.button('.buttons-copy').trigger();
        });
        
        $('#export-excel').on('click', function() {
            table.button('.buttons-excel').trigger();
        });
        
        $('#export-pdf').on('click', function() {
            table.button('.buttons-pdf').trigger();
        });
        
        $('#export-print').on('click', function() {
            table.button('.buttons-print').trigger();
        });

        // View Details Modal
        $('.view-details').on('click', function() {
            var depositId = $(this).data('id');
            $('#detailsModal').modal('show');
            
            // Fetch deposit details via AJAX
            $.ajax({
                url: 'get_deposit_details.php',
                type: 'GET',
                data: { id: depositId },
                success: function(response) {
                    $('#depositDetails').html(response);
                },
                error: function(xhr, status, error) {
                    $('#depositDetails').html('<div class="alert alert-danger">Error loading deposit details. Please try again.</div>');
                    console.error("AJAX Error: " + status + " - " + error);
                }
            });
        });
    });
    </script>
</body>
</html>