<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');
include('../../includes/footer.php');

$f_store = $_GET['store_id'] ?? '';
$f_type = $_GET['expense_type'] ?? '';
$f_start = $_GET['start_date'] ?? '';
$f_end = $_GET['end_date'] ?? '';

$where = ["e.deleted_at IS NULL"];
$params = [];
$types = '';

if ($f_store !== '') { $where[] = "e.store_id=?"; $params[] = $f_store; $types .= 'i'; }
if ($f_type !== '')  { $where[] = "e.expense_type=?"; $params[] = $f_type; $types .= 's'; }
if ($f_start)        { $where[] = "e.expense_date >= ?"; $params[] = $f_start; $types .= 's'; }
if ($f_end)          { $where[] = "e.expense_date <= ?"; $params[] = $f_end; $types .= 's'; }

$sql = "SELECT e.*, s.store_name, u.first_name, u.last_name
        FROM expenses e
        LEFT JOIN stores s ON e.store_id = s.id
        LEFT JOIN users u ON e.added_by = u.id
        WHERE " . implode(" AND ", $where) . "
        ORDER BY e.expense_date DESC";

$stmt = $conn->prepare($sql);
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$expenses = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$totalAll = $totalMonth = 0;
foreach ($expenses as $e) {
    $totalAll += $e['amount'];
    if (substr($e['expense_date'], 0, 7) === date('Y-m')) {
        $totalMonth += $e['amount'];
    }
}
$totalCount = count($expenses);

$stores = $conn->query("SELECT id, store_name FROM stores ORDER BY store_name");
$typesArr = ['Utility', 'Transport', 'Supplies', 'Other'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Expenses</title>
<link rel="stylesheet" href="../../css/dashboard.css">
<style>
        body, html {
            margin: 0; padding: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover; color: white;
        }
        .overlay {
            position: fixed; top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }
        .content {
            margin: 100px auto 40px auto;
            max-width: 1250px;
            padding: 30px 40px;
            background: rgba(255,255,255,0.08);
            backdrop-filter: blur(15px);
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        }
        h2 { text-align: center; margin-bottom: 25px; font-size: 1.8rem; }
        .filters, .summary {
            display: flex; flex-wrap: wrap;
            gap: 10px; justify-content: space-between;
        }
        .filters form {
            display: flex; flex-wrap: wrap; gap: 10px; flex-grow: 1;
        }
        select, input[type="date"], button {
            padding: 10px 14px;
            border-radius: 10px;
            border: none;
            background: rgba(255,255,255,0.2);
            color: white;
        }
        .add-btn, .export-btn {
            background: #ff6f00;
            color: white;
            border: none;
            border-radius: 10px;
            padding: 10px 14px;
            cursor: pointer;
        }
        .summary-box {
            flex: 1; padding: 16px;
            background: rgba(255,255,255,0.08);
            border-radius: 12px; text-align: center;
        }
        .summary-box strong { color: orange; font-size: 18px; display: block; }
        table {
            width: 100%; margin-top: 20px;
            border-collapse: collapse;
            background: rgba(0,0,0,0.3);
            border-radius: 12px;
        }
        th, td {
            padding: 12px 14px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        th { background: rgba(255,111,0,0.9); }
        .actions a {
            margin-right: 10px; color: #ffa;
            text-decoration: none;
        }
        .actions a.delete { color: #ff6666; }
        .actions a.restore { color: #66ff66; }
/* ... (same styles as before, omitted here for brevity, keep your original CSS) ... */
</style>
</head>
<body>
<div class="overlay"></div>
<div class="content">

    <h2>Expenses Summary</h2>

    <div class="filters">
        <form method="GET">
            <select name="store_id">
                <option value="">All Stores</option>
                <?php while($s = $stores->fetch_assoc()): ?>
                <option value="<?= $s['id'] ?>" <?= $f_store == $s['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['store_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
            <select name="expense_type">
                <option value="">All Types</option>
                <?php foreach ($typesArr as $t): ?>
                <option value="<?= $t ?>" <?= $f_type == $t ? 'selected' : '' ?>><?= $t ?></option>
                <?php endforeach; ?>
            </select>
            <input type="date" name="start_date" value="<?= $f_start ?>">
            <input type="date" name="end_date" value="<?= $f_end ?>">
            <button type="submit">Filter</button>
        </form>

        <div>
            <button class="add-btn" onclick="window.location='add_expense.php'">+ Add Expense</button>
            <button class="export-btn" onclick="exportCSV()">Export CSV</button>
            <button class="export-btn" onclick="window.print()">Export PDF</button>
            <button class="export-btn" onclick="window.location='expenses_trash.php'">View Trash Bin</button>
        </div>
    </div>

    <div class="summary">
        <div class="summary-box"><strong><?= $totalCount ?></strong>Total Records</div>
        <div class="summary-box"><strong>MWK <?= number_format($totalMonth,2) ?></strong>This Month</div>
        <div class="summary-box"><strong>MWK <?= number_format($totalAll,2) ?></strong>Grand Total</div>
    </div>

    <table>
        <thead>
            <tr>
                <th>#</th><th>Store</th><th>Type</th><th>Description</th>
                <th>Amount</th><th>Date</th><th>Added By</th><th>Attachment</th><th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($expenses): foreach ($expenses as $i => $e): ?>
            <tr>
                <td data-label="#"><?= $i + 1 ?></td>
                <td data-label="Store"><?= htmlspecialchars($e['store_name']) ?></td>
                <td data-label="Type"><?= htmlspecialchars($e['expense_type']) ?></td>
                <td data-label="Description"><?= htmlspecialchars($e['description']) ?></td>
                <td data-label="Amount">MWK <?= number_format($e['amount'], 2) ?></td>
                <td data-label="Date"><?= $e['expense_date'] ?></td>
                <td data-label="Added By"><?= htmlspecialchars($e['first_name'] . ' ' . $e['last_name']) ?></td>
                <td data-label="Attachment">
                    <?= $e['attachment_path'] ? "<a class='download-link' href='../../uploads/expenses/".htmlspecialchars($e['attachment_path'])."' target='_blank'>View</a>" : 'N/A' ?>
                </td>
                <td data-label="Actions" class="actions">
                    <a href="edit_expense.php?id=<?= $e['id'] ?>">Edit</a>
                    <a href="delete_expense.php?id=<?= $e['id'] ?>" class="delete" onclick="return confirm('Soft delete this expense?')">Delete</a>
                </td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="9" style="text-align:center;">No expenses found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
function exportCSV() {
    let rows = document.querySelectorAll('table tbody tr');
    if (!rows.length) return alert('No data to export.');

    let headers = Array.from(document.querySelectorAll('table thead th')).map(th => `"${th.innerText}"`);
    let csv = headers.join(',') + '\n';

    rows.forEach(row => {
        let cols = row.querySelectorAll('td');
        let rowData = Array.from(cols).map(td => `"${td.innerText.replace(/"/g, '""')}"`);
        csv += rowData.join(',') + '\n';
    });

    const a = document.createElement('a');
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = 'expenses.csv';
    a.click();
}
</script>
</body>
</html>
