<?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 and role
$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'];
} else {
    header('Location: login.php');
    exit();
}

// Determine if user can approve expenses
$can_approve = in_array($role_id, [1, 2, 3]); // Admin, General Manager, Operations

// Simple query to get all expenses with user information
$sql = "SELECT e.*, u.full_name as created_by 
        FROM expenses e 
        LEFT JOIN users u ON e.user_id = u.user_id 
        ORDER BY e.created_date DESC";

$result = $conn->query($sql);
$expenses = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $expenses[] = $row;
    }
}

// Calculate totals correctly for each currency
$total_usd = 0;
$total_tsh = 0;
foreach ($expenses as $expense) {
    // Convert to lowercase and trim for consistent comparison
    $currency = strtolower(trim($expense['currency']));
    
    // Handle various USD formats
    if ($currency == 'usd' || $currency == '$' || $currency == 'dollar') {
        $total_usd += (float)$expense['amount'];
    }
    // Handle various TSH formats
    else if ($currency == 'tsh' || $currency == 'tsh.' || $currency == 't' || 
             strpos($currency, 'tsh') !== false || strpos($currency, 'sh') !== false) {
        $total_tsh += (float)$expense['amount'];
    }
    
    // Debug info to console
    echo "<!-- Currency: '".$expense['currency']."', Amount: ".$expense['amount']." -->";
}

?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Expense List')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    
    <style>
        .status-badge {
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-pending { background-color: #fef3c7; color: #92400e; }
        .status-approved { background-color: #dcfce7; color: #166534; }
        .status-rejected { background-color: #fee2e2; color: #991b1b; }
        
        .dt-buttons .btn {
            margin-right: 5px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Expenses', 'title' => 'Expense List')); ?>

                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php 
                            echo $_SESSION['success_message'];
                            unset($_SESSION['success_message']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php 
                            echo $_SESSION['error_message'];
                            unset($_SESSION['error_message']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h4 class="card-title mb-0">Expense List</h4>
                                        <a href="capture_expense.php" class="btn btn-primary">
                                            <i class="ri-add-line align-middle me-1"></i> Add New Expense
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <!-- Summary -->
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <div class="card bg-light">
                                                <div class="card-body">
                                                    <h5 class="card-title">Total USD</h5>
                                                    <h3 class="text-primary">
                                                        USD <?php echo number_format($total_usd, 2); ?>
                                                    </h3>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="card bg-light">
                                                <div class="card-body">
                                                    <h5 class="card-title">Total TSH</h5>
                                                    <h3 class="text-primary">
                                                        TSH <?php echo number_format($total_tsh, 2); ?>
                                                    </h3>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Expenses Table -->
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-striped dt-responsive nowrap" id="expensesTable" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>Expense No</th>
                                                    <th>Description</th>
                                                    <th>Amount</th>
                                                    <th>File Number</th>
                                                    <th>Created By</th>
                                                    <th>Date</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($expenses as $expense): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($expense['exp_no']); ?></td>
                                                        <td><?php echo htmlspecialchars($expense['description']); ?></td>
                                                        <td>
                                                            <?php echo $expense['currency']; ?> 
                                                            <?php echo number_format($expense['amount'], 2); ?>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($expense['file_number'] ?? '-'); ?></td>
                                                        <td><?php echo htmlspecialchars($expense['created_by']); ?></td>
                                                        <td><?php echo date('d M Y', strtotime($expense['created_date'])); ?></td>
                                                        <td>
                                                            <span class="status-badge status-<?php echo strtolower($expense['status']); ?>">
                                                                <?php echo $expense['status']; ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <a href="view_expense.php?id=<?php echo $expense['id']; ?>" 
                                                               class="btn btn-sm btn-info">
                                                                <i class="ri-eye-line"></i>
                                                            </a>
                                                            
                                                            <?php if ($expense['status'] == 'Pending' && $can_approve): ?>
                                                                <button type="button" 
                                                                        class="btn btn-sm btn-success approve-expense" 
                                                                        data-id="<?php echo $expense['id']; ?>"
                                                                        data-exp-no="<?php echo htmlspecialchars($expense['exp_no']); ?>"
                                                                        data-amount="<?php echo $expense['currency'] . ' ' . number_format($expense['amount'], 2); ?>">
                                                                    <i class="ri-check-line"></i>
                                                                </button>
                                                                <button type="button" 
                                                                        class="btn btn-sm btn-danger reject-expense"
                                                                        data-id="<?php echo $expense['id']; ?>"
                                                                        data-exp-no="<?php echo htmlspecialchars($expense['exp_no']); ?>"
                                                                        data-amount="<?php echo $expense['currency'] . ' ' . number_format($expense['amount'], 2); ?>">
                                                                    <i class="ri-close-line"></i>
                                                                </button>
                                                            <?php endif; ?>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </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>
    <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>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.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/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.colVis.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>

    <!-- Datatable init js -->
    <script>
    <?php if (isset($_SESSION['success_message'])): ?>
        Swal.fire({
            title: 'Success!',
            text: '<?php echo addslashes($_SESSION['success_message']); ?>',
            icon: 'success',
            confirmButtonColor: '#28a745'
        });
        <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>
    
    // Handle error messages from PHP session
    <?php if (isset($_SESSION['error_message'])): ?>
        Swal.fire({
            title: 'Error!',
            text: '<?php echo addslashes($_SESSION['error_message']); ?>',
            icon: 'error',
            confirmButtonColor: '#dc3545'
        });
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>
        $(document).ready(function() {
            $('#expensesTable').DataTable({
                dom: '<"row"<"col-md-6"B><"col-md-6"f>>rtip',
                buttons: [
                    {
                        extend: 'copyHtml5',
                        text: '<i class="ri-file-copy-line me-1"></i> Copy',
                        className: 'btn btn-sm btn-secondary'
                    },
                    {
                        extend: 'excelHtml5',
                        text: '<i class="ri-file-excel-line me-1"></i> Excel',
                        className: 'btn btn-sm btn-success'
                    },
                    {
                        extend: 'pdfHtml5',
                        text: '<i class="ri-file-pdf-line me-1"></i> PDF',
                        className: 'btn btn-sm btn-danger'
                    },
                    {
                        extend: 'print',
                        text: '<i class="ri-printer-line me-1"></i> Print',
                        className: 'btn btn-sm btn-info'
                    },
                    {
                        extend: 'colvis',
                        text: '<i class="ri-list-check me-1"></i> Columns',
                        className: 'btn btn-sm btn-dark'
                    }
                ],
                pageLength: 10,
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                responsive: true,
                order: [[5, "desc"]], // Sort by date column by default
                columnDefs: [
                    {
                        targets: -1, // Actions column
                        orderable: false,
                        searchable: false
                    }
                ],
                language: {
                    search: "<span class='text-muted'>Search:</span>",
                    searchPlaceholder: "Enter search term",
                    lengthMenu: "<span class='text-muted'>Show:</span> _MENU_ entries",
                    info: "Showing _START_ to _END_ of _TOTAL_ entries",
                    paginate: {
                        first: '<i class="ri-arrow-left-double-line"></i>',
                        previous: '<i class="ri-arrow-left-s-line"></i>',
                        next: '<i class="ri-arrow-right-s-line"></i>',
                        last: '<i class="ri-arrow-right-double-line"></i>'
                    }
                }
            });
            // Handle Approve Expense
    $('.approve-expense').on('click', function() {
        const id = $(this).data('id');
        const expNo = $(this).data('exp-no');
        const amount = $(this).data('amount');

        Swal.fire({
            title: 'Approve Expense',
            html: `
                <div class="text-start">
                    <p>Are you sure you want to approve this expense?</p>
                    <div class="alert alert-info">
                        <strong>Expense No:</strong> ${expNo}<br>
                        <strong>Amount:</strong> ${amount}
                    </div>
                </div>
            `,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, approve it!',
            cancelButtonText: 'Cancel',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = `approve_expense.php?id=${id}`;
            }
        });
    });

    // Handle Reject Expense
    $('.reject-expense').on('click', function() {
        const id = $(this).data('id');
        const expNo = $(this).data('exp-no');
        const amount = $(this).data('amount');

        Swal.fire({
            title: 'Reject Expense',
            html: `
                <div class="text-start">
                    <div class="alert alert-warning">
                        <strong>Expense No:</strong> ${expNo}<br>
                        <strong>Amount:</strong> ${amount}
                    </div>
                    <div class="mb-3">
                        <label for="rejection_reason" class="form-label">Reason for Rejection</label>
                        <textarea id="rejection_reason" class="form-control" rows="3" 
                                placeholder="Enter rejection reason..."></textarea>
                    </div>
                </div>
            `,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Reject',
            cancelButtonText: 'Cancel',
            reverseButtons: true,
            preConfirm: () => {
                const reason = document.getElementById('rejection_reason').value;
                if (!reason.trim()) {
                    Swal.showValidationMessage('Please enter rejection reason');
                }
                return reason;
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Create form and submit
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = 'reject_expense.php';
                
                const idInput = document.createElement('input');
                idInput.type = 'hidden';
                idInput.name = 'expense_id';
                idInput.value = id;
                
                const reasonInput = document.createElement('input');
                reasonInput.type = 'hidden';
                reasonInput.name = 'rejection_reason';
                reasonInput.value = result.value;
                
                form.appendChild(idInput);
                form.appendChild(reasonInput);
                document.body.appendChild(form);
                form.submit();
            }
        });
    });
        });
    </script>
</body>
</html>