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

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

$user_role = $_SESSION['role_id'];
$user_store = $_SESSION['store_id'] ?? null;

$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 NOT NULL"];
$params = [];
$types = '';

// Manager restriction
if ($user_role == 2) {
    $where[] = "e.store_id = ?";
    $params[] = $user_store;
    $types .= 'i';
} elseif ($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.deleted_at DESC";

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

$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 Trash Bin</title>
<link rel="stylesheet" href="../../css/dashboard.css" />
<style>
/* Reuse your existing styles from expenses.php */
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 {
    display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;
    justify-content: space-between; align-items: center;
}
.filters form {
    display: flex; flex-wrap: wrap; gap: 10px; flex-grow: 1;
}
select, .filters input[type="date"], .filters button {
    padding: 10px 14px; border-radius: 10px; border: none;
    background: rgba(255,255,255,0.2); color: white; font-size: 14px;
}
.filters button[type="submit"],
.filters button.action-btn {
    background: #ff6f00; transition: background 0.3s ease; cursor: pointer;
}
.filters button[type="submit"]:hover,
.filters button.action-btn:hover {
    background: #e65c00;
}
.export-btn {
    background: #ff6f00; padding: 10px 18px; border-radius: 10px;
    color: white; border: none; cursor: pointer; transition: background 0.3s ease;
}
.export-btn:hover {
    background: #e65c00;
}
.summary {
    display: flex; flex-wrap: wrap; gap: 15px; margin-bottom: 25px;
    justify-content: space-between;
}
.summary-box {
    flex: 1; padding: 16px; background: rgba(255,255,255,0.08);
    border-radius: 12px; text-align: center; font-size: 15px;
}
.summary-box strong {
    display: block; font-size: 18px; color: #ffa500;
}
table {
    width: 100%; border-collapse: collapse; background: rgba(0,0,0,0.3);
    border-radius: 12px; overflow: hidden; box-shadow: 0 0 12px rgba(0,0,0,0.6);
}
th, td {
    padding: 12px 14px; border-bottom: 1px solid rgba(255,255,255,0.1);
    text-align: left; font-size: 14px;
}
th {
    background: rgba(255,111,0,0.9);
}
.actions a {
    margin-right: 10px; color: #ffa; text-decoration: none;
}
.actions a.delete {
    color: #ff6666;
}
.download-link {
    color: #aef; text-decoration: underline;
}
@media (max-width: 768px) {
    .filters { flex-direction: column; }
    table, thead, tbody, th, td, tr {
        font-size: 13px; display: block;
    }
    thead { display: none; }
    td {
        position: relative; padding-left: 50%; border: none; margin-bottom: 10px;
    }
    td::before {
        content: attr(data-label);
        position: absolute; left: 15px; width: 45%;
        font-weight: bold; color: #ffa500;
    }
}
</style>
</head>
<body>
<div class="overlay"></div>
<div class="content">

<h2>Expenses Trash Bin</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>
    <button onclick="window.location='expenses.php'" class="export-btn">Back to Expenses</button>
</div>

<form id="bulkForm" method="POST" action="bulk_trash_actions.php" onsubmit="return confirmBulkAction()">
    <table>
        <thead>
            <tr>
                <th><input type="checkbox" id="selectAll" /></th>
                <th>#</th><th>Store</th><th>Type</th><th>Description</th>
                <th>Amount</th><th>Date</th><th>Added By</th><th>Deleted At</th><th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($expenses): foreach ($expenses as $i => $e): ?>
            <tr>
                <td data-label="Select"><input type="checkbox" name="selected_ids[]" value="<?= $e['id'] ?>"></td>
                <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="Deleted At"><?= $e['deleted_at'] ?></td>
                <td data-label="Actions" class="actions">
                    <a href="restore_expense.php?id=<?= $e['id'] ?>" onclick="return confirm('Restore this expense?')">Restore</a>
                    <a href="permanent_delete_expense.php?id=<?= $e['id'] ?>" class="delete" onclick="return confirm('Permanently delete this expense? This action cannot be undone.')">Delete Permanently</a>
                </td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="10" style="text-align:center;">No deleted expenses found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>

    <?php if ($expenses): ?>
    <div style="margin-top:15px; display:flex; gap:10px; flex-wrap:wrap;">
        <button type="submit" name="action" value="restore" class="action-btn">Bulk Restore</button>
        <button type="submit" name="action" value="permanent_delete" class="action-btn delete" style="background:#ff4444;">Bulk Delete Permanently</button>
    </div>
    <?php endif; ?>
</form>

<script>
document.getElementById('selectAll').addEventListener('change', function(e){
    let checkboxes = document.querySelectorAll('input[name="selected_ids[]"]');
    checkboxes.forEach(cb => cb.checked = e.target.checked);
});

function confirmBulkAction() {
    const action = document.querySelector('button[type="submit"][clicked=true]');
    if (!action) {
        alert('Please click a bulk action button.');
        return false;
    }
    if (action.value === 'permanent_delete') {
        return confirm('Are you sure you want to permanently delete selected expenses? This cannot be undone.');
    }
    return confirm('Are you sure you want to restore selected expenses?');
}

// Track which button was clicked in the form (for multiple submit buttons)
document.querySelectorAll('#bulkForm button[type="submit"]').forEach(button => {
    button.addEventListener('click', function() {
        document.querySelectorAll('#bulkForm button[type="submit"]').forEach(btn => btn.removeAttribute('clicked'));
        this.setAttribute('clicked', 'true');
    });
});
</script>

</div>
</body>
</html>
