<?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, 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'];
}

// Check if user is admin (for role-specific capabilities)
$is_admin = ($role_id == 1);

// 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 Refunds')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .badge-fixed, .badge-standard {
            text-transform: capitalize;
        }
        .badge-fixed {
            background-color: #6c757d;
        }
        .badge-standard {
            background-color: #0dcaf0;
        }
        .status-marker {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }
        .marker-available {
            background-color: #28a745;
        }
        .marker-zero {
            background-color: #dc3545;
        }
        .marker-fixed {
            background-color: #6c757d;
        }
        .balance-available {
            color: #28a745;
            font-weight: 500;
        }
        .balance-zero {
            color: #dc3545;
        }
        .balance-na {
            color: #6c757d;
            font-style: italic;
        }
        .remarks-cell {
            position: relative;
            max-width: 200px;
        }
        .remarks-preview {
            display: block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .remarks-full {
            display: none;
            position: absolute;
            top: 0;
            left: 100%;
            width: 300px;
            background-color: #fff;
            border: 1px solid #ddd;
            padding: 10px;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            z-index: 100;
        }
        .remarks-cell:hover .remarks-full {
            display: block;
        }
    </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' => 'Refund 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 Refunds</h4>
                                    <div>
                                        <a href="container_depo_list.php" class="btn btn-primary btn-sm me-2">
                                            <i class="ri-list-check"></i> All Deposits
                                        </a>
                                        <?php if ($is_admin): ?>
                                        <a href="refund_approvals.php" class="btn btn-success btn-sm">
                                            <i class="ri-check-double-line"></i> Pending Approvals
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="refund-list" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>BL</th>
                                                    <th>Container</th>
                                                    <th>Shipping Line</th>
                                                    <th>Date Deposited</th>
                                                    <th>Deposit</th>
                                                    <th>Refund Amount</th>
                                                    <th>Refund Date</th>
                                                    <th>Status</th>
                                                    <th>Requested By</th>
                                                    <th>Approved By</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                // Check if our columns exist
                                                $has_created_by = false;
                                                $has_approved_by = false;
                                                
                                                $column_check = $conn->query("SHOW COLUMNS FROM container_deposit LIKE 'created_by'");
                                                if ($column_check->num_rows > 0) {
                                                    $has_created_by = true;
                                                }
                                                
                                                $column_check = $conn->query("SHOW COLUMNS FROM container_deposit LIKE 'approved_by'");
                                                if ($column_check->num_rows > 0) {
                                                    $has_approved_by = true;
                                                }

                                                // Build query based on available columns
                                                $query = "SELECT cd.id, cd.bl, cd.shipping_line, cd.container, cd.type, 
                                                        cd.deposit, cd.date_deposited, cd.refund_amount, cd.balance, 
                                                        cd.refund_date, cd.remarks, cd.status";
                                                
                                                if ($has_created_by) {
                                                    $query .= ", u1.username as requested_by";
                                                }
                                                
                                                if ($has_approved_by) {
                                                    $query .= ", u2.username as approved_by";
                                                }
                                                
                                                $query .= " FROM container_deposit cd";
                                                
                                                if ($has_created_by) {
                                                    $query .= " LEFT JOIN users u1 ON cd.created_by = u1.user_id";
                                                }
                                                
                                                if ($has_approved_by) {
                                                    $query .= " LEFT JOIN users u2 ON cd.approved_by = u2.user_id";
                                                }
                                                
                                                // Only show records with refunds
                                                $query .= " WHERE cd.refund_amount > 0 ORDER BY cd.refund_date DESC";
                                                
                                                $result = $conn->query($query);
                                                
                                                if ($result && $result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        echo "<tr>";
                                                        echo "<td>" . htmlspecialchars($row['bl']) . "</td>";
                                                        echo "<td>" . htmlspecialchars($row['container']) . "</td>";
                                                        echo "<td>" . htmlspecialchars($row['shipping_line']) . "</td>";
                                                        echo "<td>" . ($row['date_deposited'] ? date('Y-m-d', strtotime($row['date_deposited'])) : '') . "</td>";
                                                        echo "<td class='text-end'>" . number_format($row['deposit'], 2) . "</td>";
                                                        echo "<td class='text-end'>" . number_format($row['refund_amount'] ?? 0, 2) . "</td>";
                                                        echo "<td>" . ($row['refund_date'] ? date('Y-m-d', strtotime($row['refund_date'])) : '') . "</td>";
                                                        
                                                        // Status column
                                                        echo "<td>";
                                                        $status = $row['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>";
                                                        }
                                                        echo "</td>";
                                                        
                                                        // Requested by
                                                        echo "<td>";
                                                        if ($has_created_by && !empty($row['requested_by'])) {
                                                            echo htmlspecialchars($row['requested_by']);
                                                        } else {
                                                            echo "-";
                                                        }
                                                        echo "</td>";
                                                        
                                                        // Approved by
                                                        echo "<td>";
                                                        if ($has_approved_by && !empty($row['approved_by'])) {
                                                            echo htmlspecialchars($row['approved_by']);
                                                        } else {
                                                            echo "-";
                                                        }
                                                        echo "</td>";
                                                        
                                                        // Actions
                                                        echo "<td class='text-center'>";
                                                        
                                                        // View details button
                                                        echo "<button type='button' class='btn btn-sm btn-info me-1 view-details' data-id='" . $row['id'] . "' title='View Details'>";
                                                        echo "<i class='ri-eye-line'></i></button>";
                                                        
                                                        // Admin-only: Approve/Reject if status is pending
                                                        if ($is_admin && $status === 'Pending') {
                                                            echo "<a href='refund_approvals.php?id=" . $row['id'] . "' class='btn btn-sm btn-success' title='Approve/Reject'>";
                                                            echo "<i class='ri-check-double-line'></i></a>";
                                                        }
                                                        
                                                        echo "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='11' class='text-center'>No refund records 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 -->

    <!-- View Details Modal -->
    <div class="modal fade" id="viewDetailsModal" tabindex="-1" aria-labelledby="viewDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewDetailsModalLabel">Refund Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewDetailsContent">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">Loading details...</p>
                    </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
        $('#refund-list').DataTable({
            responsive: true,
            lengthMenu: [10, 25, 50, 100],
            language: {
                search: "_INPUT_",
                searchPlaceholder: "Search..."
            },
            order: [[6, 'desc']] // Sort by refund date by default
        });
        
        // Handle View Details button
        $(document).on('click', '.view-details', function() {
            const id = $(this).data('id');
            $('#viewDetailsModal').modal('show');
            
            // You need to create this endpoint to fetch deposit details
            $.ajax({
                url: 'ajax/get_deposit_details.php',
                type: 'GET',
                data: {id: id},
                success: function(response) {
                    $('#viewDetailsContent').html(response);
                },
                error: function() {
                    $('#viewDetailsContent').html('<div class="alert alert-danger">Error fetching deposit details</div>');
                }
            });
        });
    });
    </script>
</body>
</html>