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

/* =========================================================
   MARK REFUND AS COMPLETED
========================================================= */
if(isset($_GET['complete_id'])){
    $id = intval($_GET['complete_id']);

    $stmt = $conn->prepare("
        UPDATE refunds 
        SET refund_status='Completed', completed_at=NOW() 
        WHERE id=? AND refund_status!='Completed'
    ");
    $stmt->bind_param("i",$id);
    $stmt->execute();

    echo "<script>alert('Refund marked as completed');window.location='refund_report.php';</script>";
    exit;
}

/* =========================================================
   FETCH REFUNDS
========================================================= */
$refunds = $conn->query("
    SELECT rf.*, g.name, r.room_id
    FROM refunds rf
    JOIN guests g ON rf.guest_id=g.id
    JOIN reservations r ON rf.reservation_id=r.id
    ORDER BY rf.id DESC
");
?>

<div class="container mt-4">
<h4>💰 Refund Report</h4>
<hr>

<table class="table table-bordered table-sm">
<thead class="table-dark">
<tr>
    <th>Guest</th>
    <th>Total (MK)</th>
    <th>Refund 50% (MK)</th>
    <th>Status</th>
    <th>Date</th>
    <th>Action</th>
</tr>
</thead>
<tbody>

<?php while($r=$refunds->fetch_assoc()): 

    // badge color
    $badge = 'bg-warning';
    if($r['refund_status']=='Completed') $badge='bg-success';
    if($r['refund_status']=='Rejected') $badge='bg-danger';

?>
<tr>
    <td><?= htmlspecialchars($r['name']) ?></td>
    <td><?= number_format($r['total_amount'],2) ?></td>

    <td class="text-danger fw-bold">
        <?= number_format($r['refund_amount'],2) ?>
    </td>

    <td>
        <span class="badge <?= $badge ?>">
            <?= $r['refund_status'] ?>
        </span>
    </td>

    <td><?= $r['created_at'] ?></td>

    <td>
        <?php if($r['refund_status']!='Completed'): ?>
            <a href="refund_report.php?complete_id=<?= $r['id'] ?>"
               class="btn btn-sm btn-success"
               onclick="return confirm('Mark this refund as completed?')">
               <i class="fa fa-check"></i> Complete
            </a>
        <?php else: ?>
            <span class="text-success fw-bold">✔ Done</span>
        <?php endif; ?>
    </td>
</tr>
<?php endwhile; ?>

</tbody>
</table>
</div>

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