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

<?php
// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    $_SESSION['sweet_alert'] = [
        'title' => 'Access Denied',
        'text' => "You don't have permission to access this page",
        'icon' => 'error'
    ];
    header('Location: all_expenses.php');
    exit();
}

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

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Approve 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%;
        }
    </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' => 'Approve Expenses')); ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Pending Expenses for Approval</h4>
                                </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: ?>
                                    
                                    <?php if ($result && $result->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table id="pendingExpensesTable" 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>Reference</th>
                                                    <th>Created By</th>
                                                    <th>Description</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?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 echo htmlspecialchars($row['file_number'] ?? ''); ?></td>
                                                    <td><?php echo htmlspecialchars($row['created_by_name'] ?? 'Unknown'); ?></td>
                                                    <td>
                                                        <?php 
                                                        $desc = $row['description'] ?? '';
                                                        echo (strlen($desc) > 50) ? substr(htmlspecialchars($desc), 0, 50) . '...' : htmlspecialchars($desc);
                                                        ?>
                                                        <?php if (strlen($desc) > 50): ?>
                                                        <button type="button" class="btn btn-sm btn-link p-0 ms-1" 
                                                                data-bs-toggle="tooltip" data-bs-placement="top" 
                                                                title="<?php echo htmlspecialchars($desc); ?>">
                                                            <i class="ri-information-line"></i>
                                                        </button>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="action-buttons d-flex">
                                                            <button type="button" class="btn btn-sm btn-success" 
                                                                    onclick="approveExpense(<?php echo $row['id']; ?>, '<?php echo $row['exp_no']; ?>')">
                                                                <i class="ri-check-line"></i> Approve
                                                            </button>
                                                            <button type="button" class="btn btn-sm btn-danger" 
                                                                    onclick="rejectExpense(<?php echo $row['id']; ?>, '<?php echo $row['exp_no']; ?>')">
                                                                <i class="ri-close-line"></i> Reject
                                                            </button>
                                                            <a href="edit_expense.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-info">
                                                                <i class="ri-eye-line"></i> View
                                                            </a>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <div class="alert alert-info">
                                        <i class="ri-information-line me-2"></i>
                                        No pending expenses found for approval
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?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"></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>
    $(document).ready(function() {
        $('#pendingExpensesTable').DataTable({
            responsive: true,
            lengthChange: false,
            dom: 'Bfrtip',
            buttons: [
                'copy', 'csv', 'excel', 'pdf', 'print'
            ]
        });
        
        // Initialize tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl)
        });
    });

    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);
            }
        });
    }

    // Sweet Alert handling for session messages
    <?php if (isset($_SESSION['sweet_alert'])): ?>
    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'
        });
    });
    <?php unset($_SESSION['sweet_alert']); endif; ?>
    </script>
</body>
</html>