<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// ================= FILTERS =================
$from_date   = $_GET['from'] ?? '';
$to_date     = $_GET['to'] ?? '';
$type        = $_GET['type'] ?? '';
$min_amount  = $_GET['min_amount'] ?? '';
$max_amount  = $_GET['max_amount'] ?? '';

$where = [];
if($from_date) $where[] = "DATE(payment_date) >= '".$conn->real_escape_string($from_date)."'";
if($to_date)   $where[] = "DATE(payment_date) <= '".$conn->real_escape_string($to_date)."'";
if($type)      $where[] = "type = '".$conn->real_escape_string($type)."'";
if($min_amount !== '') $where[] = "amount >= ".floatval($min_amount);
if($max_amount !== '') $where[] = "amount <= ".floatval($max_amount);

$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

// ================= FETCH AUDIT DATA =================
$audit = $conn->query("
    SELECT 
        DATE(payment_date) AS date, 
        SUM(amount) AS total_income,
        SUM(CASE WHEN type='Cash' THEN amount ELSE 0 END) AS cash_total,
        SUM(CASE WHEN type='Card' THEN amount ELSE 0 END) AS card_total
    FROM payments
    $where_sql
    GROUP BY DATE(payment_date)
    ORDER BY date DESC
");

// Overall totals
$overall_total = 0;
$overall_cash  = 0;
$overall_card  = 0;
$username      = $_SESSION['username'] ?? 'Guest';
?>

<!-- ================= STYLES ================= -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.5/css/jquery.dataTables.min.css">
<style>
.welcome-msg { font-size:1.1rem; margin-bottom:15px; color:#1b4d32; }
.table tbody tr.low-cash { background-color:#fff3cd; } /* highlight Cash <50% */
</style>

<div class="container mt-4">

    <!-- WELCOME -->
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>

    <button class="btn btn-secondary mb-2" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h4>Night Audit Report</h4>
    <hr>

    <!-- FILTER FORM -->
    <form method="GET" class="row g-2 mb-3">
        <div class="col-md-2">
            <input type="date" name="from" class="form-control" value="<?= htmlspecialchars($from_date) ?>">
        </div>
        <div class="col-md-2">
            <input type="date" name="to" class="form-control" value="<?= htmlspecialchars($to_date) ?>">
        </div>
        <div class="col-md-2">
            <select name="type" class="form-control">
                <option value="">All Types</option>
                <option value="Cash" <?= ($type=='Cash')?'selected':'' ?>>Cash</option>
                <option value="Card" <?= ($type=='Card')?'selected':'' ?>>Card</option>
            </select>
        </div>
        <div class="col-md-2">
            <input type="number" name="min_amount" class="form-control" placeholder="Min Amount" value="<?= htmlspecialchars($min_amount) ?>">
        </div>
        <div class="col-md-2">
            <input type="number" name="max_amount" class="form-control" placeholder="Max Amount" value="<?= htmlspecialchars($max_amount) ?>">
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary w-100">Filter</button>
        </div>
    </form>

    <!-- EXPORT / PRINT -->
    <div class="mb-3 d-flex gap-2">
        <a href="export_audit_csv.php?from=<?= $from_date ?>&to=<?= $to_date ?>&type=<?= $type ?>&min_amount=<?= $min_amount ?>&max_amount=<?= $max_amount ?>" class="btn btn-success">Export CSV</a>
        <a href="generate_audit_pdf.php?from=<?= $from_date ?>&to=<?= $to_date ?>&type=<?= $type ?>&min_amount=<?= $min_amount ?>&max_amount=<?= $max_amount ?>" class="btn btn-danger">Export PDF</a>
        <button onclick="window.print();" class="btn btn-info">Print</button>
    </div>

    <!-- AUDIT TABLE -->
    <table class="table table-bordered table-striped table-sm" id="auditTable">
        <thead class="table-dark">
            <tr>
                <th>Date</th>
                <th>Total Income (MK)</th>
                <th>Cash (MK)</th>
                <th>Card (MK)</th>
            </tr>
        </thead>
        <tbody>
        <?php if($audit->num_rows > 0): ?>
            <?php while($a = $audit->fetch_assoc()):
                $date = $a['date'];
                $total = (float)$a['total_income'];
                $cash  = (float)$a['cash_total'];
                $card  = (float)$a['card_total'];

                $overall_total += $total;
                $overall_cash  += $cash;
                $overall_card  += $card;

                $row_class = ($cash / $total < 0.5) ? 'low-cash' : '';
            ?>
            <tr class="<?= $row_class ?>">
                <td><?= $date ?></td>
                <td><?= number_format($total,2) ?></td>
                <td><?= number_format($cash,2) ?></td>
                <td><?= number_format($card,2) ?></td>
            </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="4" class="text-center">No records found.</td></tr>
        <?php endif; ?>
        </tbody>
        <tfoot class="table-dark">
            <tr>
                <th>Overall Totals</th>
                <th><?= number_format($overall_total,2) ?></th>
                <th><?= number_format($overall_cash,2) ?></th>
                <th><?= number_format($overall_card,2) ?></th>
            </tr>
        </tfoot>
    </table>
</div>

<!-- DATA TABLES -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function(){
    $('#auditTable').DataTable({
        "order": [[0, "desc"]],
        "pageLength": 20
    });
});
</script>

<?php include 'includes/footer.php'; ?>