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

<?php
// Execute query to fetch expenses
$query = "SELECT e.*, u.username as created_by_name 
          FROM expenses e 
          LEFT JOIN users u ON e.user_id = u.user_id 
          ORDER BY e.created_date DESC";
$result = $conn->query($query);

// Check if query executed successfully
if (!$result) {
    $error_message = "Database error: " . $conn->error;
}

// Check if user has admin rights
$isAdmin = false;
if (isset($_SESSION['role_id']) && $_SESSION['role_id'] == 1) {
    $isAdmin = true;
}
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All Expenses')); ?>

    <!--datatable css-->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" />
    <!--datatable responsive css-->
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css">
    
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        .action-buttons .btn {
            margin-right: 5px;
        }
        .badge {
            font-size: 85%;
        }
        .dropdown-item {
            cursor: pointer;
        }
    </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' => 'Expense Management', 'title' => 'All Expenses')); ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title mb-0">Expenses List</h4>
                                    <div>
                                        <?php if ($isAdmin): ?>
                                        <a href="approve_expenses.php" class="btn btn-success me-2">
                                            <i class="ri-check-double-line me-1"></i> Pending Approvals
                                        </a>
                                        <?php endif; ?>
                                        <a href="add_expense.php" class="btn btn-primary">
                                            <i class="ri-add-line me-1"></i> Add New Expense
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if (isset($error_message)): ?>
                                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                        <?php echo $error_message; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                    <?php else: ?>
                                    <table id="expensesTable" class="table table-bordered dt-responsive nowrap table-striped">
                                        <thead>
                                            <tr>
                                                <th>Expense No</th>
                                                <th>Date</th>
                                                <th>Type</th>
                                                <th>Amount</th>
                                                <th>Payment Method</th>
                                                <th>Status</th>
                                                <th>Reference</th>
                                                <th>Created By</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($result && $result->num_rows > 0): ?>
                                                <?php while($row = $result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($row['exp_no']); ?></td>
                                                    <td><?php echo date('d M Y', strtotime($row['created_date'])); ?></td>
                                                    <td><?php echo ucfirst(str_replace('_', ' ', $row['office_cost'])); ?></td>
                                                    <td><?php echo $row['currency'] . ' ' . number_format($row['amount'], 2); ?></td>
                                                    <td><?php echo ucfirst(str_replace('_', ' ', $row['pay_mode'])); ?></td>
                                                    <td>
                                                        <?php 
                                                        $status_class = '';
                                                        switch($row['status']) {
                                                            case 'Approved':
                                                                $status_class = 'badge bg-success';
                                                                break;
                                                            case 'Rejected':
                                                                $status_class = 'badge bg-danger';
                                                                break;
                                                            default:
                                                                $status_class = 'badge bg-warning';
                                                        }
                                                        ?>
                                                        <span class="<?php echo $status_class; ?>"><?php echo $row['status']; ?></span>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($row['file_number'] ?? ''); ?></td>
                                                    <td><?php echo htmlspecialchars($row['created_by_name'] ?? 'Unknown'); ?></td>
                                                    <td>
                                                        <div class="dropdown">
                                                            <button class="btn btn-sm btn-light dropdown-toggle" type="button" id="dropdownMenuButton<?php echo $row['id']; ?>" data-bs-toggle="dropdown" aria-expanded="false">
                                                                Actions
                                                            </button>
                                                            <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton<?php echo $row['id']; ?>">
                                                                <li>
                                                                    <a class="dropdown-item" href="edit_expense.php?id=<?php echo $row['id']; ?>">
                                                                        <i class="ri-pencil-fill me-2"></i> Edit
                                                                    </a>
                                                                </li>
                                                                
                                                                <?php if ($isAdmin): // Only admins can approve/reject ?>
                                                                <li>
                                                                    <a class="dropdown-item <?php echo ($row['status'] === 'Approved') ? 'disabled' : ''; ?>" 
                                                                       <?php if ($row['status'] !== 'Approved'): ?>
                                                                       onclick="approveExpense(<?php echo $row['id']; ?>, '<?php echo $row['exp_no']; ?>')"
                                                                       <?php endif; ?>>
                                                                        <i class="ri-check-line me-2 text-success"></i> Approve
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item <?php echo ($row['status'] === 'Rejected') ? 'disabled' : ''; ?>"
                                                                       <?php if ($row['status'] !== 'Rejected'): ?>
                                                                       onclick="rejectExpense(<?php echo $row['id']; ?>, '<?php echo $row['exp_no']; ?>')"
                                                                       <?php endif; ?>>
                                                                        <i class="ri-close-line me-2 text-danger"></i> Reject
                                                                    </a>
                                                                </li>
                                                                <?php if ($row['status'] !== 'Pending'): ?>
                                                                <li>
                                                                    <a class="dropdown-item" onclick="resetToPending(<?php echo $row['id']; ?>, '<?php echo $row['exp_no']; ?>')">
                                                                        <i class="ri-refresh-line me-2 text-warning"></i> Reset to Pending
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                                <li><hr class="dropdown-divider"></li>
                                                                <?php endif; ?>
                                                                
                                                                <li>
                                                                    <a class="dropdown-item text-danger" onclick="deleteExpense(<?php echo $row['id']; ?>, '<?php echo $row['exp_no']; ?>')">
                                                                        <i class="ri-delete-bin-line me-2"></i> Delete
                                                                    </a>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="9" class="text-center">No expenses found</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                    <?php endif; ?>
                                </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" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="assets/js/app.js"></script>
<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>
    <!--datatable js-->
    <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.2.9/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.print.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.html5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>

    <script>
    $(document).ready(function() {
        $('#expensesTable').DataTable({
            responsive: true,
            lengthChange: false,
            dom: 'Bfrtip',
            buttons: [
                'copy', 'csv', 'excel', 'pdf', 'print'
            ]
        });
    });

    function deleteExpense(id, expNo) {
        Swal.fire({
            title: 'Are you sure?',
            text: "You want to delete expense " + expNo + "?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'No, cancel!',
            confirmButtonClass: 'btn btn-success mt-2',
            cancelButtonClass: 'btn btn-danger ms-2 mt-2',
            buttonsStyling: false
        }).then(function(result) {
            if (result.isConfirmed) {
                window.location.href = 'delete_expense.php?id=' + id;
            }
        });
    }
    
    function approveExpense(expenseId, expNo) {
        Swal.fire({
            title: 'Approve Expense',
            text: `Are you sure you want to approve expense ${expNo}?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, approve it!',
            cancelButtonText: 'No, cancel!',
            confirmButtonClass: 'btn btn-success mt-2',
            cancelButtonClass: 'btn btn-danger ms-2 mt-2',
            buttonsStyling: false
        }).then(function(result) {
            if (result.isConfirmed) {
                window.location.href = 'change_expense_status.php?id=' + expenseId + '&status=Approved';
            }
        });
    }

    function rejectExpense(expenseId, expNo) {
        Swal.fire({
            title: 'Reject Expense',
            text: `Are you sure you want to reject expense ${expNo}?`,
            icon: 'warning',
            input: 'text',
            inputPlaceholder: 'Enter reason for rejection (optional)',
            inputAttributes: {
                autocapitalize: 'off'
            },
            showCancelButton: true,
            confirmButtonText: 'Yes, reject it!',
            cancelButtonText: 'No, cancel!',
            confirmButtonClass: 'btn btn-danger mt-2',
            cancelButtonClass: 'btn btn-secondary ms-2 mt-2',
            buttonsStyling: false
        }).then(function(result) {
            if (result.isConfirmed) {
                let rejectReason = result.value || '';
                window.location.href = 'change_expense_status.php?id=' + expenseId + '&status=Rejected&reason=' + encodeURIComponent(rejectReason);
            }
        });
    }
    
    function resetToPending(expenseId, expNo) {
        Swal.fire({
            title: 'Reset Status',
            text: `Are you sure you want to reset expense ${expNo} to pending status?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, reset it!',
            cancelButtonText: 'No, cancel!',
            confirmButtonClass: 'btn btn-warning mt-2',
            cancelButtonClass: 'btn btn-secondary ms-2 mt-2',
            buttonsStyling: false
        }).then(function(result) {
            if (result.isConfirmed) {
                window.location.href = 'change_expense_status.php?id=' + expenseId + '&status=Pending';
            }
        });
    }
    </script>

    <!-- SweetAlert script for notifications -->
    <?php if (isset($_SESSION['sweet_alert'])): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                title: "<?php echo $_SESSION['sweet_alert']['title']; ?>",
                text: "<?php echo $_SESSION['sweet_alert']['text']; ?>",
                icon: "<?php echo $_SESSION['sweet_alert']['icon']; ?>",
                confirmButtonText: 'OK',
                confirmButtonClass: 'btn btn-primary'
            });
        });
    </script>
    <?php unset($_SESSION['sweet_alert']); endif; ?>
</body>
</html>