<?php
session_start();
include '../config/db.php';

// Check if the user is logged in
if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}

// Add delete handler at the top of the file after session check
if (isset($_POST['delete_id'])) {
    $delete_id = $_POST['delete_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM expenses WHERE id = ?");
        $stmt->execute([$delete_id]);
        $_SESSION['success'] = "Expense deleted successfully!";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Failed to delete expense";
    }
    header("Location: manage_espenses.php");
    exit();
}

// Add edit handler
if (isset($_POST['edit_expense'])) {
    $id = $_POST['expense_id'];
    $description = trim($_POST['edit_description']);
    $amount = trim($_POST['edit_amount']);
    
    try {
        $stmt = $pdo->prepare("UPDATE expenses SET expense_description = ?, amount = ? WHERE id = ?");
        $stmt->execute([$description, $amount, $id]);
        $_SESSION['success'] = "Expense updated successfully!";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Failed to update expense";
    }
    header("Location: manage_espenses.php");
    exit();
}

// Handle form submission for adding an expense
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $description = trim($_POST['description']);
    $amount = trim($_POST['amount']);
    $username = $_SESSION['username'];

    if (!empty($description) && !empty($amount)) {
        $stmt = $pdo->prepare("INSERT INTO expenses (expense_description, amount, added_by) VALUES (?, ?, ?)");
        $stmt->execute([$description, $amount, $username]);

        $_SESSION['success'] = "Expense added successfully!";
        header("Location: manage_espenses.php");
        exit();
    } else {
        $_SESSION['error'] = "All fields are required!";
    }
}

// Initialize filter variables
$searchTerm = $_GET['search'] ?? '';
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';

// Build the query with filters
$query = "SELECT * FROM expenses WHERE 1=1";
$params = [];

if (!empty($searchTerm)) {
    $query .= " AND (expense_description LIKE ? OR added_by LIKE ?)";
    $params[] = "%$searchTerm%";
    $params[] = "%$searchTerm%";
}

if (!empty($startDate) && !empty($endDate)) {
    $query .= " AND DATE(expense_date) BETWEEN ? AND ?";
    $params[] = $startDate;
    $params[] = $endDate;
}

$query .= " ORDER BY expense_date DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$expenses = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate total expenses
$total_expenses = array_sum(array_column($expenses, 'amount'));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Expenses | Store Management</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <style>
        body {
            background-color: #f5f6fa;
            font-family: Arial, sans-serif;
            font-size: 14px;
            overflow-x: hidden;
        }

        .content {
            margin-left: 240px;
            padding: 15px;
            transition: all 0.3s ease;
        }

        .mobile-toggle {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1050;
            background: #3498db;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            color: white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        .container {
            padding: 0;
            scroll-padding-top: 70px;
            width: 100%;
            max-width: none;
        }

        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .top-bar h2 {
            font-size: 1.5rem;
            margin: 0;
        }

        .summary-card {
            padding: 20px;
            border-radius: 8px;
            color: white;
            transition: all 0.3s ease;
        }

        .expenses-card {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
        }

        .table-container {
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
        }

        .table thead th {
            background-color: #2c3e50;
            color: #fff;
            padding: 12px;
        }

        .filter-btn {
            margin: 5px;
            transition: all 0.3s ease;
        }

        .filter-btn:hover {
            transform: translateY(-2px);
        }

        .btn-primary {
            background: linear-gradient(135deg, #2c3e50, #3498db);
            border: none;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
        }

        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 10px;
            }

            .mobile-toggle {
                display: block;
            }

            .top-bar {
                margin-top: 40px;
            }

            .top-bar .d-flex {
                flex-direction: column;
                gap: 10px;
            }

            .top-bar .btn-group {
                width: 100%;
                display: flex;
                gap: 5px;
            }

            .top-bar .btn {
                flex: 1;
                white-space: nowrap;
            }

            .table-container {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            .table {
                min-width: 800px;
            }

            .modal-dialog {
                margin: 10px;
            }

            .summary-card {
                margin-bottom: 15px;
            }

            .filter-form .col-md-4,
            .filter-form .col-md-3,
            .filter-form .col-md-2 {
                width: 100%;
                margin-bottom: 10px;
            }

            .filter-btn {
                width: 100%;
            }
        }

        @media (max-width: 576px) {
            .top-bar h2 {
                font-size: 1.2rem;
            }

            .btn {
                padding: 0.375rem 0.5rem;
                font-size: 0.875rem;
            }

            .summary-card h3 {
                font-size: 1.5rem;
            }
        }

        .modal-header {
            background: #2c3e50;
            color: white;
        }

        .modal-content {
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .btn-close {
            color: white;
        }
    </style>
</head>
<body>
    <?php include '../includes/side_bar.php'; ?>

    <div class="content">
        <!-- Move existing container content here -->
        <div class="container">
            <!-- Top Bar -->
            <div class="top-bar">
                <div class="d-flex justify-content-between align-items-center">
                    <h2><i class="fas fa-money-bill-wave"></i> Manage Expenses</h2>
                    <div>
                        <a href="admin_dashboard.php" class="btn btn-primary">
                            <i class="fas fa-arrow-left"></i> Dashboard
                        </a>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addExpenseModal">
                            <i class="fas fa-plus"></i> Add Expense
                        </button>
                    </div>
                </div>
            </div>

            <!-- Summary Cards -->
            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="summary-card expenses-card">
                        <h5><i class="fas fa-money-bill-wave"></i> Total Expenses</h5>
                        <h3>₦<?= number_format($total_expenses, 2) ?></h3>
                    </div>
                </div>
            </div>

            <!-- Alert Messages -->
            <?php if (isset($_SESSION['success']) || isset($_SESSION['error'])): ?>
                <div class="alert alert-<?= isset($_SESSION['success']) ? 'success' : 'danger' ?> alert-dismissible fade show" role="alert">
                    <i class="fas fa-<?= isset($_SESSION['success']) ? 'check' : 'exclamation' ?>-circle"></i> 
                    <?= $_SESSION['success'] ?? $_SESSION['error'] ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php unset($_SESSION['success'], $_SESSION['error']); ?>
            <?php endif; ?>

            <!-- Filter Options -->
            <div class="text-center mb-4">
                <!-- Change the form method to GET -->
                <form method="GET" class="row g-3">
                    <div class="col-md-4">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" name="search" class="form-control" 
                                placeholder="Search expenses..." value="<?= htmlspecialchars($searchTerm) ?>">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-calendar"></i></span>
                            <input type="date" name="start_date" class="form-control" 
                                value="<?= htmlspecialchars($startDate) ?>">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-calendar"></i></span>
                            <input type="date" name="end_date" class="form-control" 
                                value="<?= htmlspecialchars($endDate) ?>">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100 filter-btn">
                            <i class="fas fa-filter"></i> Filter
                        </button>
                    </div>
                </form>
            </div>

            <!-- Expenses Table -->
            <div class="table-container">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th><i class="fas fa-hashtag"></i> ID</th>
                            <th><i class="fas fa-file-alt"></i> Description</th>
                            <th><i class="fas fa-money-bill"></i> Amount (₦)</th>
                            <th><i class="fas fa-user"></i> Added By</th>
                            <th><i class="fas fa-calendar"></i> Date</th>
                            <th><i class="fas fa-cogs"></i> Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($expenses as $expense): ?>
                            <tr>
                                <td><?= htmlspecialchars($expense['id']) ?></td>
                                <td><?= htmlspecialchars($expense['expense_description']) ?></td>
                                <td>₦<?= number_format($expense['amount'], 2) ?></td>
                                <td><?= htmlspecialchars($expense['added_by']) ?></td>
                                <td><?= date('d M Y, h:i A', strtotime($expense['expense_date'])) ?></td>
                                <td>
                                    <button class="btn btn-warning btn-sm" data-bs-toggle="modal" 
                                            data-bs-target="#editExpenseModal" data-id="<?= $expense['id'] ?>">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-danger btn-sm delete-expense" 
                                            data-id="<?= $expense['id'] ?>">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add Expense Modal -->
    <div class="modal fade" id="addExpenseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus"></i> Add New Expense</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addExpenseForm" method="post">
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <input type="text" name="description" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Amount (₦)</label>
                            <input type="number" name="amount" class="form-control" step="0.01" required>
                        </div>
                        <div class="text-end">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Save Expense
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Expense Modal -->
    <div class="modal fade" id="editExpenseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> Edit Expense</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form method="post">
                        <input type="hidden" name="edit_expense" value="1">
                        <input type="hidden" name="expense_id" id="edit_expense_id">
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <input type="text" name="edit_description" id="edit_description" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Amount (₦)</label>
                            <input type="number" name="edit_amount" id="edit_amount" class="form-control" step="0.01" required>
                        </div>
                        <div class="text-end">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Update Expense
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script>
        // Show success message and refresh page after adding expense
        <?php if (isset($_SESSION['success'])): ?>
            var toast = new bootstrap.Toast(document.querySelector('.alert-success'));
            toast.show();
        <?php endif; ?>

        // Handle edit button click
        $(document).on('click', '.btn-warning', function() {
            var id = $(this).data('id');
            var description = $(this).closest('tr').find('td:eq(1)').text();
            var amount = $(this).closest('tr').find('td:eq(2)').text().replace('₦', '').replace(',', '');
            
            $('#edit_expense_id').val(id);
            $('#edit_description').val(description);
            $('#edit_amount').val(parseFloat(amount));
        });

        // Handle delete button click
        $(document).on('click', '.delete-expense', function() {
            if (confirm('Are you sure you want to delete this expense?')) {
                var id = $(this).data('id');
                var form = $('<form method="post"><input type="hidden" name="delete_id" value="' + id + '"></form>');
                $('body').append(form);
                form.submit();
            }
        });

        // Show success/error messages
        var alertElement = document.querySelector('.alert');
        if (alertElement) {
            setTimeout(function() {
                var alert = bootstrap.Alert.getInstance(alertElement);
                if (alert) {
                    alert.close();
                }
            }, 3000);
        }
    </script>
</body>
</html>
