<?php
// deposit_list.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'];
}

// Check if user has access (admin or operations roles)
if ($role_id != 1 && $role_id != 3) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

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

// 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' => 'Bank Deposits')); ?>
    <?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-status {
            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' => 'Finance Management', 'title' => 'Bank Deposits')); ?>

                    <?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">Bank Deposits</h5>
                                    <div>
                                        <a href="create_deposit.php" class="btn btn-primary btn-sm">
                                            <i class="ri-add-line align-bottom"></i> Add New Deposit
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-8 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 purpose, bank, amount..." value="<?php echo htmlspecialchars($search); ?>">
                                                    <i class="ri-search-line search-icon"></i>
                                                </div>
                                                <select name="status" class="form-select me-2" style="width: auto;">
                                                    <option value="">All Status</option>
                                                    <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                    <option value="approved" <?php echo $status_filter == 'approved' ? 'selected' : ''; ?>>Approved</option>
                                                    <option value="rejected" <?php echo $status_filter == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                                </select>
                                                <button type="submit" class="btn btn-primary">Filter</button>
                                            </form>
                                        </div>
                                    </div>

                                    <div class="table-responsive">
                                        <table id="deposits-table" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>ID</th>
                                                    <th>Date</th>
                                                    <th>Bank</th>
                                                    <th>Currency</th>
                                                    <th>Amount</th>
                                                    <th>Purpose</th>
                                                    <th>Status</th>
                                                    <th>Created By</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                // Base query for deposits
                                                $sql = "
                                                    SELECT 
                                                        d.id, 
                                                        d.deposit_date, 
                                                        d.bank,
                                                        d.currency, 
                                                        d.amount,
                                                        d.purpose,
                                                        d.status,
                                                        d.created_at,
                                                        u1.full_name as created_by_name,
                                                        u2.full_name as deposit_user_name,
                                                        u3.full_name as approval_user_name
                                                    FROM 
                                                        deposits d
                                                    LEFT JOIN 
                                                        users u1 ON d.created_by = u1.user_id
                                                    LEFT JOIN 
                                                        users u2 ON d.deposit_user_id = u2.user_id
                                                    LEFT JOIN 
                                                        users u3 ON d.approval_user_id = u3.user_id
                                                    WHERE 1=1
                                                ";
                                                
                                                // Add search condition if search parameter exists
                                                if (!empty($search)) {
                                                    $sql .= " AND (
                                                        d.purpose LIKE '%$search%' OR 
                                                        d.bank LIKE '%$search%' OR 
                                                        d.amount LIKE '%$search%' OR
                                                        u1.full_name LIKE '%$search%' OR
                                                        u2.full_name LIKE '%$search%'
                                                    )";
                                                }
                                                
                                                // Add status filter if selected
                                                if (!empty($status_filter)) {
                                                    $sql .= " AND d.status = '$status_filter'";
                                                }
                                                
                                                $sql .= " ORDER BY d.created_at DESC";
                                                
                                                $result = $conn->query($sql);
                                                
                                                if ($result && $result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        $id = $row['id'];
                                                        $deposit_date = date('Y-m-d', strtotime($row['deposit_date']));
                                                        $bank = $row['bank'];
                                                        $currency = $row['currency'];
                                                        $amount = number_format($row['amount'], 2);
                                                        $purpose = substr($row['purpose'], 0, 50) . (strlen($row['purpose']) > 50 ? '...' : '');
                                                        $status = $row['status'];
                                                        $created_by = $row['created_by_name'];
                                                        
                                                        // 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>$id</td>";
                                                        echo "<td>$deposit_date</td>";
                                                        echo "<td>$bank</td>";
                                                        echo "<td>$currency</td>";
                                                        echo "<td>$amount</td>";
                                                        echo "<td>$purpose</td>";
                                                        echo "<td><span class='badge $status_badge_class'>$status</span></td>";
                                                        echo "<td>$created_by</td>";
                                                        echo "<td class='text-center'>";
                                                        
                                                        // View button
                                                        echo "<a href='view_deposit.php?id=$id' class='btn btn-sm btn-info action-btn' title='View Details'>";
                                                        echo "<i class='ri-eye-line'></i>";
                                                        echo "</a>";
                                                        
                                                        // Edit button - only for pending deposits and admin/operations
                                                        if ($status == 'pending' && ($role_id == 1 || $role_id == 3)) {
                                                            echo "<a href='edit_deposit.php?id=$id' class='btn btn-sm btn-warning action-btn' title='Edit Deposit'>";
                                                            echo "<i class='ri-edit-2-line'></i>";
                                                            echo "</a>";
                                                        } 
                                                        
                                                        // Approve/Reject button - only for admins and pending status
                                                        if ($status == 'pending' && $role_id == 1) {
                                                            echo "<a href='approve_deposit.php?id=$id' class='btn btn-sm btn-success action-btn' title='Approve/Reject'>";
                                                            echo "<i class='ri-check-double-line'></i>";
                                                            echo "</a>";
                                                        }
                                                        
                                                        echo "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='9' class='text-center'>No 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 -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <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>
<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>

    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#deposits-table').DataTable({
                responsive: true,
                lengthChange: true,
                pageLength: 10,
                lengthMenu: [10, 25, 50, 100],
                dom: 'rtip', // Remove default search
                language: {
                    emptyTable: "No deposits found",
                    zeroRecords: "No matching deposits found"
                }
            });
            
            // Use custom search box
            $('.search').on('keyup', function() {
                $('#deposits-table').DataTable().search($(this).val()).draw();
            });
        });
    </script>

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