<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// ================= FETCH FILTER OPTIONS =================
$rooms_res = $conn->query("SELECT id, room_number, room_type FROM rooms ORDER BY room_number ASC");
$guests_res = $conn->query("SELECT id, name FROM guests ORDER BY name ASC");

// ================= BUILD WHERE CLAUSE =================
$where = [];
if($room_filter) $where[] = "rm.id = '".$conn->real_escape_string($room_filter)."'";
if($guest_filter) $where[] = "g.id = '".$conn->real_escape_string($guest_filter)."'";
if($from_date) $where[] = "s.checkin_date >= '".$conn->real_escape_string($from_date)."'";
if($to_date) $where[] = "s.checkout_date <= '".$conn->real_escape_string($to_date)."'";

// ================= FETCH REPORT DATA =================
$query = "
SELECT s.id AS stay_id, g.name AS guest_name, rm.room_number, rm.room_type, rm.price AS room_price,
       s.checkin_date, s.checkout_date, s.days,
       SUM(CASE WHEN p.status='Paid' THEN p.amount ELSE 0 END) AS paid_amount,
       SUM(CASE WHEN p.status<>'Paid' THEN p.amount ELSE 0 END) AS unpaid_amount
FROM stays s
JOIN rooms rm ON s.room_id = rm.id
JOIN guests g ON s.guest_id = g.id
LEFT JOIN payments p ON p.guest_id = s.guest_id
".(count($where) ? "WHERE ".implode(" AND ", $where) : "")."
GROUP BY s.id
ORDER BY s.checkin_date DESC
";
$report_res = $conn->query($query);

// ================= FETCH SUMMARIES =================
$summary_query = "
SELECT 
    COUNT(s.id) AS total_stays,
    SUM(rm.price * s.days) AS total_room_revenue,
    SUM(CASE WHEN p.status='Paid' THEN p.amount ELSE 0 END) AS total_paid,
    SUM(CASE WHEN p.status<>'Paid' THEN p.amount ELSE 0 END) AS total_unpaid,
    SUM(COALESCE(c.amount * c.quantity,0)) AS total_services
FROM stays s
JOIN rooms rm ON s.room_id = rm.id
LEFT JOIN payments p ON p.guest_id = s.guest_id
LEFT JOIN charges c ON c.guest_id = s.guest_id
";
$summary = $conn->query($summary_query)->fetch_assoc();
?>

<div class="container mt-3">
<h3>Front Office Reports</h3>

<!-- FILTER FORM -->
<form method="GET" class="row mb-3 g-2">
    <div class="col-md-2">
        <label>Room</label>
        <select name="room" class="form-control">
            <option value="">All</option>
            <?php while($r = $rooms_res->fetch_assoc()): ?>
                <option value="<?= $r['id'] ?>" <?= $room_filter==$r['id']?'selected':'' ?>><?= htmlspecialchars($r['room_number']).' ('.$r['room_type'].')' ?></option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-2">
        <label>Guest</label>
        <select name="guest" class="form-control">
            <option value="">All</option>
            <?php while($g = $guests_res->fetch_assoc()): ?>
                <option value="<?= $g['id'] ?>" <?= $guest_filter==$g['id']?'selected':'' ?>><?= htmlspecialchars($g['name']) ?></option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-2">
        <label>Status</label>
        <select name="status" class="form-control">
            <option value="">All</option>
            <option value="Paid" <?= $status_filter=='Paid'?'selected':'' ?>>Paid ✔️</option>
            <option value="Unpaid" <?= $status_filter=='Unpaid'?'selected':'' ?>>Unpaid ❌</option>
            <option value="Partially Paid" <?= $status_filter=='Partially Paid'?'selected':'' ?>>Partial ⚠️</option>
        </select>
    </div>
    <div class="col-md-2">
        <label>From</label>
        <input type="date" name="from" class="form-control" value="<?= htmlspecialchars($from_date) ?>">
    </div>
    <div class="col-md-2">
        <label>To</label>
        <input type="date" name="to" class="form-control" value="<?= htmlspecialchars($to_date) ?>">
    </div>
    <div class="col-md-2 d-flex align-items-end">
        <button class="btn btn-primary form-control"><i class="fa fa-filter"></i> Filter</button>
    </div>
</form>

<!-- SUMMARY -->
<div class="mb-3">
    <strong>Summary:</strong>
    Total Stays: <?= $summary['total_stays'] ?> |
    Room Revenue: <?= number_format($summary['total_room_revenue'],2) ?> |
    Services Revenue: <?= number_format($summary['total_services'],2) ?> |
    Paid: <?= number_format($summary['total_paid'],2) ?> |
    Unpaid: <?= number_format($summary['total_unpaid'],2) ?>
</div>

<!-- REPORT TABLE -->
<table class="table table-bordered table-striped table-hover" style="font-size:0.85rem;"
    <thead class="table-dark">
        <tr>
            <th>Stay ID</th>
            <th>Guest</th>
            <th>Room #</th>
            <th>Type</th>
            <th>Check-in</th>
            <th>Check-out</th>
            <th>Days</th>
            <th>Room Cost</th>
            <th>Services</th>
            <th>Total</th>
            <th>Paid</th>
            <th>Unpaid</th>
            <th>Status</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php if($report_res->num_rows==0): ?>
            <tr><td colspan="14" class="text-center">No records found</td></tr>
        <?php else: ?>
            <?php while($row = $report_res->fetch_assoc()):
                $room_cost = $row['room_price'] * $row['days'];

                // Services summary
                $services_res = $conn->query("SELECT name, amount, quantity FROM charges WHERE guest_id={$row['stay_id']}");
                $service_total = 0;
                $service_summary = '';
                while($s = $services_res->fetch_assoc()){
                    $service_total += $s['amount'] * $s['quantity'];
                    $service_summary .= htmlspecialchars($s['name'])." (".number_format($s['amount'],2).") x ".$s['quantity']."<br>";
                }

                $total_cost = $room_cost + $service_total;

                // Payment status icon
                if($row['unpaid_amount']==0){
                    $status_icon = '<span class="text-success fw-bold">✔️ Paid</span>';
                } elseif($row['paid_amount']==0){
                    $status_icon = '<span class="text-danger fw-bold">❌ Unpaid</span>';
                } else {
                    $status_icon = '<span class="text-warning fw-bold">⚠️ Partial</span>';
                }
            ?>
            <tr>
                <td><?= $row['stay_id'] ?></td>
                <td><?= htmlspecialchars($row['guest_name']) ?></td>
                <td><?= htmlspecialchars($row['room_number']) ?></td>
                <td><?= htmlspecialchars($row['room_type']) ?></td>
                <td><?= $row['checkin_date'] ?></td>
                <td><?= $row['checkout_date'] ?></td>
                <td><?= $row['days'] ?></td>
                <td><?= number_format($room_cost,2) ?></td>
                <td>
                    <a href="#" data-bs-toggle="tooltip" data-bs-html="true" title="<?= $service_summary ?>">
                        <?= number_format($service_total,2) ?>
                    </a>
                </td>
                <td><?= number_format($total_cost,2) ?></td>
                <td><?= number_format($row['paid_amount'],2) ?></td>
                <td><?= number_format($row['unpaid_amount'],2) ?></td>
                <td><?= $status_icon ?></td>
                <td>
                    <a href="invoice.php?stay_id=<?= $row['stay_id'] ?>" target="_blank" class="btn btn-sm btn-primary">
                        <i class="fa fa-file-invoice-dollar"></i>
                    </a>
                  
                    <a href="receipt_thermal.php?stay_id=<?= $row['stay_id'] ?>" target="_blank" class="btn btn-sm btn-secondary">
                        <i class="fa fa-receipt"></i>
                    </a>
                </td>
            </tr>
            <?php endwhile; ?>
        <?php endif; ?>
    </tbody>
</table>

<script>
document.addEventListener('DOMContentLoaded', function(){
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl)
    })
});
</script>

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