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

// ================= FILTERS =================
$guest_filter = $_GET['guest'] ?? '';
$from_date    = $_GET['from'] ?? '';
$to_date      = $_GET['to'] ?? '';

// Build WHERE clauses
$where = [];
if($guest_filter) $where[] = "g.name LIKE '%".$conn->real_escape_string($guest_filter)."%'";
if($from_date)    $where[] = "DATE(i.created_at) >= '".$conn->real_escape_string($from_date)."'";
if($to_date)      $where[] = "DATE(i.created_at) <= '".$conn->real_escape_string($to_date)."'";
$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

// ================= FETCH BILLS WITH DETAILS =================
$bills = $conn->query("
SELECT i.id AS invoice_id,
       g.id AS guest_id,
       g.name AS guest_name,
       g.status AS guest_status,
       i.total_amount,
       i.created_at,
       s.id AS stay_id,
       s.room_id,
       r.room_number,
       r.room_type,
       IFNULL(s.locked_room_price,0) AS locked_room_price,
       s.checkin_date,
       s.checkout_date,
       IFNULL(s.days, DATEDIFF(s.checkout_date, s.checkin_date)) AS days,
       IFNULL((
           SELECT SUM(amount)
           FROM charges
           WHERE guest_id = g.id
       ),0) AS service_total,
       IFNULL((
           SELECT SUM(amount)
           FROM payments
           WHERE guest_id = g.id AND status='Paid'
       ),0) AS total_paid
FROM invoices i
JOIN guests g ON i.guest_id=g.id
LEFT JOIN stays s ON i.stay_id = s.id
LEFT JOIN rooms r ON s.room_id = r.id
$where_sql
ORDER BY i.created_at DESC
");

// ================= TAX RATES =================
$vat_rate = 0.175;      // 17.5%
$tourism_rate = 0.01;   // 1%
?>

<div class="container mt-4">
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>

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

    <h4>Customer Bills</h4>
    <hr>

    <!-- ================= FILTER FORM ================= -->
    <form method="GET" class="row g-2 mb-3">
        <div class="col-md-3">
            <input type="text" name="guest" class="form-control" placeholder="Guest Name" value="<?= htmlspecialchars($guest_filter) ?>">
        </div>
        <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">
            <button class="btn btn-primary w-100">Filter</button>
        </div>
        <div class="col-md-3">
            <a href="customer_bills.php" class="btn btn-secondary w-100">Reset</a>
        </div>
    </form>

    <!-- ================= BILLS TABLE ================= -->
    <table class="table table-bordered table-striped table-sm">
        <thead class="table-dark">
            <tr>
                <th>Guest</th>
                <th>Invoice #</th>
                <th>Date</th>
                <th>Room #</th>
                <th>Room Type</th>
                <th>Days</th>
                <th>Room Cost (MK)</th>
                <th>Service Charges (MK)</th>
                <th>VAT (17.5%)</th>
                <th>Tourism Levy (1%)</th>
                <th>Total (MK)</th>
                <th>Paid (MK)</th>
                <th>Balance (MK)</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
        <?php if($bills->num_rows > 0): 
            $overall_total = $overall_paid = $overall_balance = 0;
            $overall_room = $overall_service = $overall_vat = $overall_tourism = 0;

            while($b = $bills->fetch_assoc()):
                $days       = intval($b['days']);
                $room_cost  = floatval($b['locked_room_price']) * $days;
                $service    = floatval($b['service_total']);

                // ================= TAX CALCULATIONS =================
                $subtotal   = $room_cost + $service;
                $vat        = $subtotal * $vat_rate;
                $tourism    = $subtotal * $tourism_rate;
                $total      = $subtotal + $vat + $tourism;

                $paid       = floatval($b['total_paid']);
                $balance    = $total - $paid;

                // ================= UPDATE OVERALLS =================
                $overall_room    += $room_cost;
                $overall_service += $service;
                $overall_vat     += $vat;
                $overall_tourism += $tourism;
                $overall_total   += $total;
                $overall_paid    += $paid;
                $overall_balance += $balance;

                // Determine payment status
                if($balance <= 0){
                    $status = '<span class="badge bg-success">Paid</span>';
                } elseif($paid > 0){
                    $status = '<span class="badge bg-warning text-dark">Partial</span>';
                } else {
                    $status = '<span class="badge bg-danger">Unpaid</span>';
                }
        ?>
            <tr>
                <td><?= htmlspecialchars($b['guest_name']) ?></td>
                <td><?= $b['invoice_id'] ?></td>
                <td><?= date('Y-m-d', strtotime($b['created_at'])) ?></td>
                <td><?= $b['room_number'] ?></td>
                <td><?= $b['room_type'] ?></td>
                <td><?= $days ?></td>
                <td><?= number_format($room_cost,2) ?></td>
                <td><?= number_format($service,2) ?></td>
                <td><?= number_format($vat,2) ?></td>
                <td><?= number_format($tourism,2) ?></td>
                <td><?= number_format($total,2) ?></td>
                <td><?= number_format($paid,2) ?></td>
                <td><?= number_format($balance,2) ?></td>
                <td><?= $status ?></td>
                <td>
                    <?php if($balance > 0): ?>
                        <!-- Show invoice and payment only if balance exists -->
                        <a href="invoice.php?stay_id=<?= $b['stay_id'] ?>" class="btn btn-dark btn-sm" title="View Invoice">
                            <i class="fa fa-file-invoice-dollar"></i>
                        </a>
                        <a href="receive_payment.php?guest_id=<?= $b['guest_id'] ?>&stay_id=<?= $b['stay_id'] ?>" 
                           class="btn btn-success btn-sm" title="Receive Payment">
                            <i class="fa fa-money-bill-wave"></i>
                        </a>
                    <?php else: ?>
                        <!-- Only show receipt if fully paid -->
                        <a href="receipt_thermal.php?stay_id=<?= $b['stay_id'] ?>" target="_blank" 
                           class="btn btn-secondary btn-sm" title="Print Thermal Receipt">
                            <i class="fa fa-receipt"></i>
                        </a>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endwhile; else: ?>
            <tr><td colspan="15" class="text-center">No bills found.</td></tr>
        <?php endif; ?>
        </tbody>
        <tfoot class="table-dark">
            <tr>
                <th colspan="6">Overall Totals</th>
                <th><?= number_format($overall_room,2) ?></th>
                <th><?= number_format($overall_service,2) ?></th>
                <th><?= number_format($overall_vat,2) ?></th>
                <th><?= number_format($overall_tourism,2) ?></th>
                <th><?= number_format($overall_total,2) ?></th>
                <th><?= number_format($overall_paid,2) ?></th>
                <th><?= number_format($overall_balance,2) ?></th>
                <th colspan="2"></th>
            </tr>
        </tfoot>
    </table>
</div>

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