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

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

// Check if user has permission (admin or operations)
$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'];
}

// Restrict access to admin and 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();
}

// 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']) : '';
$status_filter = isset($_GET['status']) ? $conn->real_escape_string($_GET['status']) : '';
$bank_filter = isset($_GET['bank']) ? intval($_GET['bank']) : 0;
$date_from = isset($_GET['date_from']) ? $conn->real_escape_string($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? $conn->real_escape_string($_GET['date_to']) : '';

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

// Get banks list
$sql_banks = "SELECT id, bank_name FROM banks WHERE status = 'active' ORDER BY bank_name";
$result_banks = $conn->query($sql_banks);
$banks = [];
if ($result_banks && $result_banks->num_rows > 0) {
    while ($row = $result_banks->fetch_assoc()) {
        $banks[$row['id']] = $row['bank_name'];
    }
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Cheque Withdrawals')); ?>
    <?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" />
    
    <!-- Datepicker css -->
    <link rel="stylesheet" href="assets/libs/flatpickr/flatpickr.min.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-withdrawal {
            padding: 5px 8px;
            font-size: 12px;
        }
        .filters-container {
            background-color: #f8f9fa;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 20px;
        }
    </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' => 'Cheque Withdrawals')); ?>

                    <?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">Cheque Withdrawals</h5>
                                    <div>
                                        <a href="create_withdrawal.php" class="btn btn-primary">
                                            <i class="ri-add-line align-bottom"></i> New Withdrawal
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="filters-container">
                                        <form action="" method="GET" id="filter-form">
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Status</label>
                                                    <select class="form-select" name="status" id="status-filter">
                                                        <option value="">All Statuses</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>
                                                </div>
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Bank</label>
                                                    <select class="form-select" name="bank" id="bank-filter">
                                                        <option value="">All Banks</option>
                                                        <?php foreach ($banks as $id => $name): ?>
                                                        <option value="<?php echo $id; ?>" <?php echo $bank_filter === $id ? 'selected' : ''; ?>><?php echo $name; ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">From Date</label>
                                                    <input type="text" class="form-control flatpickr-input" id="date-from" name="date_from" placeholder="YYYY-MM-DD" value="<?php echo $date_from; ?>">
                                                </div>
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">To Date</label>
                                                    <input type="text" class="form-control flatpickr-input" id="date-to" name="date_to" placeholder="YYYY-MM-DD" value="<?php echo $date_to; ?>">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <div class="search-box">
                                                        <input type="text" name="search" class="form-control search" placeholder="Search purpose, cheque number..." value="<?php echo htmlspecialchars($search); ?>">
                                                        <i class="ri-search-line search-icon"></i>
                                                    </div>
                                                </div>
                                                <div class="col-md-6 mb-3 text-end">
                                                    <button type="submit" class="btn btn-primary">Apply Filters</button>
                                                    <a href="cheque_withdrawals.php" class="btn btn-secondary">Clear Filters</a>
                                                </div>
                                            </div>
                                        </form>
                                    </div>

                                    <div class="table-responsive">
                                        <table id="withdrawals-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>Amount</th>
                                                    <th>Purpose</th>
                                                    <th>Requester</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                // Build SQL query with filters
                                                $sql = "
                                                    SELECT 
                                                        w.id, 
                                                        w.withdrawal_date, 
                                                        w.currency,
                                                        w.amount,
                                                        w.purpose,
                                                        w.bank,
                                                        w.status,
                                                        w.cheque_number,
                                                        w.created_at,
                                                        u1.full_name as requester_name,
                                                        u2.full_name as approver_name
                                                    FROM 
                                                        cheque_withdrawals w
                                                    LEFT JOIN 
                                                        users u1 ON w.withdrawal_user_id = u1.user_id
                                                    LEFT JOIN 
                                                        users u2 ON w.approval_user_id = u2.user_id
                                                    WHERE 1=1
                                                ";
                                                
                                                $params = [];
                                                $param_types = "";
                                                
                                                // Add search condition if search parameter exists
                                                if (!empty($search)) {
                                                    $sql .= " AND (
                                                        w.purpose LIKE ? OR 
                                                        w.cheque_number LIKE ? OR
                                                        w.bank LIKE ?
                                                    )";
                                                    $search_param = "%" . $search . "%";
                                                    $params[] = $search_param;
                                                    $params[] = $search_param;
                                                    $params[] = $search_param;
                                                    $param_types .= "sss";
                                                }
                                                
                                                // Add status filter
                                                if (!empty($status_filter)) {
                                                    $sql .= " AND w.status = ?";
                                                    $params[] = $status_filter;
                                                    $param_types .= "s";
                                                }
                                                
                                                // Add bank filter
                                                if (!empty($bank_filter)) {
                                                    $sql .= " AND w.bank = ?";
                                                    $params[] = $banks[$bank_filter];
                                                    $param_types .= "s";
                                                }
                                                
                                                // Add date range filter
                                                if (!empty($date_from)) {
                                                    $sql .= " AND w.withdrawal_date >= ?";
                                                    $params[] = $date_from;
                                                    $param_types .= "s";
                                                }
                                                
                                                if (!empty($date_to)) {
                                                    $sql .= " AND w.withdrawal_date <= ?";
                                                    $params[] = $date_to;
                                                    $param_types .= "s";
                                                }
                                                
                                                $sql .= " ORDER BY w.created_at DESC";
                                                
                                                $stmt = $conn->prepare($sql);
                                                
                                                if (!empty($params)) {
                                                    $stmt->bind_param($param_types, ...$params);
                                                }
                                                
                                                $stmt->execute();
                                                $result = $stmt->get_result();
                                                
                                                if ($result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        $id = $row['id'];
                                                        $date = formatDate($row['withdrawal_date']);
                                                        $bank = $row['bank'];
                                                        $amount = $row['amount'];
                                                        $currency = $row['currency'];
                                                        $purpose = htmlspecialchars(substr($row['purpose'], 0, 50)) . (strlen($row['purpose']) > 50 ? '...' : '');
                                                        $requester = $row['requester_name'];
                                                        $status = $row['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>$id</td>";
                                                        echo "<td>$date</td>";
                                                        echo "<td>$bank</td>";
                                                        echo "<td>$currency " . number_format($amount, 2) . "</td>";
                                                        echo "<td>$purpose</td>";
                                                        echo "<td>$requester</td>";
                                                        echo "<td><span class='badge $status_badge_class'>".ucfirst($status)."</span></td>";
                                                        echo "<td class='text-center'>";
                                                        
                                                        // View button
                                                        echo "<a href='view_withdrawal.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 withdrawals
                                                        if ($status == 'pending') {
                                                            echo "<a href='edit_withdrawal.php?id=$id' class='btn btn-sm btn-warning action-btn' title='Edit'>";
                                                            echo "<i class='ri-edit-2-line'></i>";
                                                            echo "</a>";
                                                        }
                                                        
                                                        // Approve/Reject button - only for admins and pending withdrawals
                                                        if ($role_id == 1 && $status == 'pending') {
                                                            echo "<a href='approve_withdrawal.php?id=$id' class='btn btn-sm btn-success action-btn' title='Approve/Reject'>";
                                                            echo "<i class='ri-check-double-line'></i>";
                                                            echo "</a>";
                                                        }
                                                        
                                                        // Print button - for all withdrawals
                                                        echo "<a href='print_withdrawal.php?id=$id' class='btn btn-sm btn-secondary action-btn' title='Print'>";
                                                        echo "<i class='ri-printer-line'></i>";
                                                        echo "</a>";
                                                        
                                                        echo "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='8' class='text-center'>No withdrawals found</td></tr>";
                                                }
                                                
                                                $stmt->close();
                                                $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'; ?>
    
    <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>

    
    <!-- Datepicker js -->
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#withdrawals-table').DataTable({
                responsive: true,
                lengthChange: true,
                pageLength: 10,
                lengthMenu: [10, 25, 50, 100],
                dom: 'rtip', // Remove default search
                order: [[0, 'desc']], // Sort by ID by default
                language: {
                    emptyTable: "No withdrawals found",
                    zeroRecords: "No matching withdrawals found"
                }
            });
            
            // Initialize flatpickr date pickers
            flatpickr("#date-from", {
                dateFormat: "Y-m-d",
            });
            
            flatpickr("#date-to", {
                dateFormat: "Y-m-d",
            });
            
            // Use custom search box
            $('.search').on('keyup', function() {
                $('#withdrawals-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>