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

$username = $_SESSION['username'] ?? 'Guest';
$room_number = $_GET['room'] ?? '';
$from_date = $_GET['from'] ?? date('Y-m-01');
$to_date   = $_GET['to'] ?? date('Y-m-d');

if(!$room_number){
    echo "<div class='alert alert-danger'>Room number not specified.</div>";
    include 'includes/footer.php';
    exit;
}

// ================= HANDLE RECONCILIATION =================
if(isset($_POST['reconcile_stay'])){
    $stay_id = intval($_POST['stay_id']);
    $update = $conn->prepare("UPDATE stays SET reconciled=1 WHERE id=?");
    $update->bind_param("i", $stay_id);
    if($update->execute()){
        $success = "Stay #$stay_id reconciled successfully.";
    } else {
        $error = "Failed to reconcile stay #$stay_id.";
    }
}

// ================= FETCH STAYS WITH BALANCE =================
$stays = $conn->query("
    SELECT s.*, r.room_number, r.room_type, IFNULL(r.price,0) AS room_price,
           g.name AS guest_name,
           (r.price*s.days - IFNULL((SELECT SUM(amount) FROM payments p WHERE p.guest_id=s.guest_id AND p.status='Paid'),0)) AS balance
    FROM stays s
    JOIN rooms r ON s.room_id=r.id
    JOIN guests g ON s.guest_id=g.id
    WHERE r.room_number='{$conn->real_escape_string($room_number)}'
      AND s.checkout_date BETWEEN '{$conn->real_escape_string($from_date)}' AND '{$conn->real_escape_string($to_date)}'
    ORDER BY s.checkout_date ASC
");
?>

<div class="container mt-4">
     <button class="btn btn-secondary btn-custom" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>
    <h3 class="text-center">🛠 Reconcile Room: <?= htmlspecialchars($room_number) ?></h3>
    <hr>

    <?php if(isset($error)): ?>
        <div class="alert alert-danger"><?= $error ?></div>
    <?php endif; ?>
    <?php if(isset($success)): ?>
        <div class="alert alert-success"><?= $success ?></div>
    <?php endif; ?>

    <a href="analytics_report.php?from=<?= $from_date ?>&to=<?= $to_date ?>" class="btn btn-secondary mb-3">
        <i class="fa fa-arrow-left"></i> Back to Analytics
    </a>

    <table class="table table-bordered table-striped table-sm">
        <thead class="bg-dark text-white">
            <tr>
                <th>#</th>
                <th>Guest</th>
                <th>Room Type</th>
                <th>Days</th>
                <th>Room Cost</th>
                <th>Paid</th>
                <th>Balance</th>
                <th>Check-In</th>
                <th>Check-Out</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php $i=1; while($s = $stays->fetch_assoc()): ?>
            <tr class="<?= $s['balance']>0 ? 'table-warning' : 'table-success' ?>">
                <td><?= $i ?></td>
                <td><?= htmlspecialchars($s['guest_name']) ?></td>
                <td><?= $s['room_type'] ?></td>
                <td><?= $s['days'] ?></td>
                <td><?= number_format($s['room_price']*$s['days'],2) ?></td>
                <td>
                    <?= number_format($s['room_price']*$s['days'] - $s['balance'],2) ?>
                </td>
                <td><?= number_format($s['balance'],2) ?></td>
                <td><?= date('Y-m-d', strtotime($s['checkin_date'])) ?></td>
                <td><?= date('Y-m-d', strtotime($s['checkout_date'])) ?></td>
                <td>
                    <?php if($s['balance']>0): ?>
                    <form method="post" style="display:inline;">
                        <input type="hidden" name="stay_id" value="<?= $s['id'] ?>">
                        <button type="submit" name="reconcile_stay" class="btn btn-sm btn-danger" onclick="return confirm('Mark this stay as reconciled?');">
                            Reconcile
                        </button>
                    </form>
                    <?php else: ?>
                        <span class="text-success">OK</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php $i++; endwhile; ?>
        </tbody>
    </table>
</div>

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