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

$store_id = $_GET['store_id'] ?? '';
$expense_type = $_GET['expense_type'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$show_deleted = isset($_GET['show_deleted']) ? (bool)$_GET['show_deleted'] : false;
$export = $_GET['export'] ?? '';

// Build where clauses & params for filtering
$where = ['1'];
$params = [];
$types = '';

if ($store_id !== '') { $where[] = "e.store_id=?"; $params[] = $store_id; $types .= 'i'; }
if ($expense_type !== '') { $where[] = "e.expense_type=?"; $params[] = $expense_type; $types .= 's'; }
if ($date_from) { $where[] = "DATE(e.expense_date) >= ?"; $params[] = $date_from; $types .= 's'; }
if ($date_to) { $where[] = "DATE(e.expense_date) <= ?"; $params[] = $date_to; $types .= 's'; }
if (!$show_deleted) {
    $where[] = "e.deleted_at IS NULL";
}

// Fetch expenses
$sql = "SELECT e.*, s.store_name 
        FROM expenses e
        LEFT JOIN stores s ON e.store_id = s.id
        WHERE " . implode(' AND ', $where) . "
        ORDER BY e.expense_date DESC, e.id DESC";

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

// Calculate summaries
$total_expenses_overall = 0;
$total_expenses_this_month = 0;
$current_month = date('Y-m');

foreach ($expenses as $e) {
    $total_expenses_overall += $e['amount'];
    if (substr($e['expense_date'], 0, 7) === $current_month) {
        $total_expenses_this_month += $e['amount'];
    }
}

// Get distinct expense types for filter dropdown
$expense_types_res = $conn->query("SELECT DISTINCT expense_type FROM expenses ORDER BY expense_type");
$expense_types = [];
while ($row = $expense_types_res->fetch_assoc()) {
    $expense_types[] = $row['expense_type'];
}

// Get stores for filter dropdown
$stores_res = $conn->query("SELECT id, store_name FROM stores");

// Handle simple Excel export: output a downloadable HTML table file
if ($export === 'excel') {
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=expenses_report_" . date('YmdHis') . ".xls");
    echo "<table border='1'>";
    echo "<tr><th>#</th><th>Store</th><th>Expense Type</th><th>Description</th><th>Amount</th><th>Date</th><th>Attachment</th><th>Status</th></tr>";
    foreach ($expenses as $i => $row) {
        echo "<tr>";
        echo "<td>" . ($i + 1) . "</td>";
        echo "<td>" . htmlspecialchars($row['store_name']) . "</td>";
        echo "<td>" . htmlspecialchars($row['expense_type']) . "</td>";
        echo "<td>" . htmlspecialchars($row['description']) . "</td>";
        echo "<td>" . number_format($row['amount'], 2) . "</td>";
        echo "<td>" . $row['expense_date'] . "</td>";
        echo "<td>" . ($row['attachment'] ? htmlspecialchars(basename($row['attachment'])) : '') . "</td>";
        echo "<td>" . ($row['deleted_at'] ? 'Deleted' : 'Active') . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    exit();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Expenses Report</title>
<style>
    body {
        background: url('../../images/profile.jpg') no-repeat center center fixed;
        background-size: cover;
        color: white;
        font-family: 'Segoe UI', sans-serif;
    }
    .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: 1300px;
        padding: 30px;
        background: rgba(255,255,255,0.08);
        backdrop-filter: blur(15px);
        border-radius: 20px;
    }
    h2 { text-align: center; margin-bottom: 20px; }
    .filters, .summary { display: flex; gap: 15px; flex-wrap: wrap; justify-content: space-between; margin-bottom: 20px; }
    .filters select, .filters input[type="date"], .filters button {
        padding: 8px 12px; border-radius: 8px; background: rgba(255,255,255,0.2); border: none; color: white;
    }
    .filters button { background: #ff6f00; cursor: pointer; }
    .summary-box {
        flex: 1; background: rgba(255,255,255,0.08); padding: 15px;
        border-radius: 12px; text-align: center;
    }
    .summary-box strong { color: #ffa500; font-size: 18px; display: block; }
    table {
        width: 100%; 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);
        vertical-align: middle;
    }
    th { background: rgba(255,111,0,0.9); }
    a.attachment-link {
        color: #ffa500;
        text-decoration: underline;
        cursor: pointer;
    }
    .export-btn {
        background: #ff6f00; padding: 8px 14px; border-radius: 8px;
        color: white; border: none; margin-left: 10px;
        cursor: pointer;
    }
    .soft-delete-btn {
        background: transparent;
        border: none;
        color: #ffa500;
        cursor: pointer;
        font-weight: bold;
        text-decoration: underline;
        padding: 0;
    }
    tr.deleted {
        opacity: 0.6;
        font-style: italic;
    }
    /* Modal styles */
    #attachmentModal {
        display: none;
        position: fixed;
        z-index: 9999;
        left: 0; top: 0; width: 100%; height: 100%;
        background-color: rgba(0,0,0,0.8);
        overflow: auto;
    }
    #attachmentModal .modal-content {
        background: #222;
        margin: 10% auto;
        padding: 20px;
        border-radius: 15px;
        max-width: 90%;
        max-height: 80%;
        position: relative;
        color: white;
    }
    #attachmentModal .close-btn {
        position: absolute;
        top: 10px;
        right: 15px;
        font-size: 28px;
        font-weight: bold;
        color: #ffa500;
        cursor: pointer;
    }
    #attachmentModal img, #attachmentModal iframe {
        max-width: 100%;
        max-height: 70vh;
        border-radius: 12px;
    }
     .back-link {
    display: inline-block;
    margin-bottom: 20px;
    padding: 10px 20px;
    background:rgba(255, 111, 0, 0);
    color: white;
    font-weight: 600;
    border-radius: 8px;
    text-decoration: none;
    transition: background-color 0.3s ease;
}
.back-link:hover {
    background: #e65c00;
}
</style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
                  <a href="reports.php" class="back-link">&larr; Back to Reports</a>

    <h2>Expenses Report</h2>

    <form class="filters" method="GET" id="filterForm">
        <select name="store_id">
            <option value="">All Stores</option>
            <?php 
            $stores_res->data_seek(0);
            while ($s = $stores_res->fetch_assoc()): ?>
                <option value="<?= $s['id'] ?>" <?= ($store_id == $s['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['store_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>

        <select name="expense_type">
            <option value="">All Expense Types</option>
            <?php foreach ($expense_types as $type): ?>
                <option value="<?= htmlspecialchars($type) ?>" <?= ($expense_type == $type) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($type) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <input type="date" name="date_from" value="<?= htmlspecialchars($date_from) ?>">
        <input type="date" name="date_to" value="<?= htmlspecialchars($date_to) ?>">

        <button type="submit">Filter</button>

        <button type="button" class="export-btn" id="exportExcelBtn">Export Excel</button>
        <button type="button" class="export-btn" onclick="window.print()">Export PDF</button>

        <label style="color:#ffa500; cursor:pointer; user-select:none; margin-left: 15px;">
            <input type="checkbox" name="show_deleted" id="showDeletedCheckbox" <?= $show_deleted ? 'checked' : '' ?> style="vertical-align: middle; cursor: pointer;">
            Show Deleted
        </label>
    </form>

    <div class="summary">
        <div class="summary-box"><strong><?= count($expenses) ?></strong> Total Records</div>
        <div class="summary-box"><strong>MWK <?= number_format($total_expenses_this_month, 2) ?></strong> Total This Month</div>
        <div class="summary-box"><strong>MWK <?= number_format($total_expenses_overall, 2) ?></strong> Total Overall</div>
    </div>

    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Store</th>
                <th>Expense Type</th>
                <th>Description</th>
                <th>Amount</th>
                <th>Date</th>
                <th>Attachment</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($expenses): foreach ($expenses as $i => $row):
                $isDeleted = $row['deleted_at'] ? true : false;
                ?>
            <tr class="<?= $isDeleted ? 'deleted' : '' ?>">
                <td><?= $i + 1 ?></td>
                <td><?= htmlspecialchars($row['store_name']) ?></td>
                <td><?= htmlspecialchars($row['expense_type']) ?></td>
                <td><?= htmlspecialchars($row['description']) ?></td>
                <td>MWK <?= number_format($row['amount'], 2) ?></td>
                <td><?= date('d M Y', strtotime($row['expense_date'])) ?></td>
                <td>
                    <?php if ($row['attachment'] && file_exists('../../' . $row['attachment'])): ?>
                        <a href="#" class="attachment-link" data-attachment="../../<?= htmlspecialchars($row['attachment']) ?>" data-description="<?= htmlspecialchars($row['description']) ?>">View</a>
                    <?php else: ?>
                        N/A
                    <?php endif; ?>
                </td>
                <td><?= $isDeleted ? 'Deleted' : 'Active' ?></td>
                <td>
                    <button class="soft-delete-btn" data-id="<?= $row['id'] ?>" data-deleted="<?= $isDeleted ? 1 : 0 ?>">
                        <?= $isDeleted ? 'Undo Delete' : 'Delete' ?>
                    </button>
                </td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="9" style="text-align:center;">No expense records found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Attachment Preview Modal -->
<div id="attachmentModal">
    <div class="modal-content">
        <span class="close-btn" id="modalCloseBtn">&times;</span>
        <h3 id="modalDescription"></h3>
        <div id="modalAttachmentContainer"></div>
    </div>
</div>

<script>
    // Export Excel button handler (reloads with export param)
    document.getElementById('exportExcelBtn').addEventListener('click', () => {
        const form = document.getElementById('filterForm');
        const params = new URLSearchParams(new FormData(form));
        params.set('export', 'excel');
        window.location.search = params.toString();
    });

    // Show deleted toggle
    document.getElementById('showDeletedCheckbox').addEventListener('change', () => {
        document.getElementById('filterForm').submit();
    });

    // Soft delete / Undo delete
    document.querySelectorAll('.soft-delete-btn').forEach(button => {
        button.addEventListener('click', () => {
            const expenseId = button.dataset.id;
            const currentlyDeleted = button.dataset.deleted === '1';
            const action = currentlyDeleted ? 'undelete' : 'delete';

            if (!confirm(`Are you sure you want to ${action} this expense?`)) return;

            fetch('toggle_expense_delete.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: expenseId, action: action })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    // Reload page to reflect changes
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(() => alert('Failed to communicate with server.'));
        });
    });

    // Attachment modal logic
    const modal = document.getElementById('attachmentModal');
    const modalContentContainer = document.getElementById('modalAttachmentContainer');
    const modalDescription = document.getElementById('modalDescription');
    const modalCloseBtn = document.getElementById('modalCloseBtn');

    document.querySelectorAll('.attachment-link').forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const url = link.dataset.attachment;
            const desc = link.dataset.description || 'Attachment Preview';
            modalDescription.textContent = desc;
            modalContentContainer.innerHTML = '';

            const ext = url.split('.').pop().toLowerCase();

            if(['jpg','jpeg','png','gif','bmp','webp'].includes(ext)){
                const img = document.createElement('img');
                img.src = url;
                modalContentContainer.appendChild(img);
            } else if(['pdf'].includes(ext)) {
                const iframe = document.createElement('iframe');
                iframe.src = url;
                iframe.width = '100%';
                iframe.height = '500px';
                modalContentContainer.appendChild(iframe);
            } else {
                modalContentContainer.textContent = 'Preview not available for this file type.';
            }

            modal.style.display = 'block';
        });
    });

    modalCloseBtn.addEventListener('click', () => {
        modal.style.display = 'none';
        modalContentContainer.innerHTML = '';
    });

    window.addEventListener('click', (event) => {
        if (event.target === modal) {
            modal.style.display = 'none';
            modalContentContainer.innerHTML = '';
        }
    });
</script>

</body>
</html>
