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

// Check if the user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: login.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!";
    }
}

// Handle delete request
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM expenses WHERE id = ?");
    $stmt->execute([$id]);

    $_SESSION['message'] = "<div class='alert alert-success'>Expense deleted successfully!</div>";
    header("Location: add_expense.php");
    exit();
}

// Fetch expenses with optional filtering and search
$query = "SELECT * FROM expenses WHERE 1=1";
$params = [];

// Date Filter
if (!empty($_GET['start_date']) && !empty($_GET['end_date'])) {
    $query .= " AND expense_date BETWEEN ? AND ?";
    $params[] = $_GET['start_date'];
    $params[] = $_GET['end_date'];
}

// Search Filter
if (!empty($_GET['search'])) {
    $query .= " AND expense_description LIKE ?";
    $params[] = '%' . $_GET['search'] . '%';
}

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

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

include('../includes/side_bar.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Expense | Store Management</title>

    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f5f6fa;
            font-family: Arial, sans-serif;
            font-size: 14px;
        }

        .container {
            padding: 20px;
            scroll-padding-top: 70px;
        }

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

        .summary-card {
            padding: 20px;
            border-radius: 8px;
            color: white;
            margin-bottom: 20px;
        }

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

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

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

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

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

        @media (max-width: 768px) {
            .summary-card { margin-bottom: 15px; }
            .filter-btn { width: 100%; margin-bottom: 5px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Top Bar -->
        <div class="top-bar">
            <div class="d-flex justify-content-between align-items-center">
                <h2><i class="fas fa-plus-circle"></i> Add Expense</h2>
                <div>
                    <a href="admin_dashboard.php" class="btn btn-primary">
                        <i class="fas fa-arrow-left"></i> Dashboard
                    </a>
                    <a href="manage_espenses.php" class="btn btn-primary">
                        <i class="fas fa-list"></i> View All Expenses
                    </a>
                </div>
            </div>
        </div>

        <!-- Summary Card -->
        <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>

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

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

        <!-- Add Expense Form -->
        <div class="table-container mb-4">
            <h4 class="mb-3"><i class="fas fa-plus"></i> New Expense</h4>
            <form method="post">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Description</label>
                        <input type="text" name="description" class="form-control" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Amount (₦)</label>
                        <input type="number" name="amount" class="form-control" step="0.01" required>
                    </div>
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Expense
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- Filter Section -->
        <div class="table-container mb-4">
            <form method="get" class="row g-3">
                <div class="col-md-3">
                    <input type="date" name="start_date" class="form-control" 
                           value="<?= $_GET['start_date'] ?? '' ?>">
                </div>
                <div class="col-md-3">
                    <input type="date" name="end_date" class="form-control" 
                           value="<?= $_GET['end_date'] ?? '' ?>">
                </div>
                <div class="col-md-4">
                    <input type="text" name="search" class="form-control" 
                           placeholder="Search description..." 
                           value="<?= $_GET['search'] ?? '' ?>">
                </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>
                            <a href="add_expense.php?delete=<?= $expense['id'] ?>" 
                               class="btn btn-danger btn-sm" 
                               onclick="return confirm('Are you sure you want to delete this expense?')">
                                <i class="fas fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
</body>
</html>
