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

/* =========================================================
   ROOM SUMMARY CARDS
========================================================= */
$available_rooms = $conn->query("SELECT COUNT(*) as t FROM rooms WHERE status='Available'")->fetch_assoc()['t'];
$reserved_rooms  = $conn->query("SELECT COUNT(*) as t FROM rooms WHERE status='Reserved'")->fetch_assoc()['t'];
$occupied_rooms  = $conn->query("SELECT COUNT(*) as t FROM rooms WHERE status='Occupied'")->fetch_assoc()['t'];


/* =========================================================
   CREATE RESERVATION
========================================================= */
if(isset($_POST['reserve'])){

    $guest_id = intval($_POST['guest_id']);
    $room_id  = intval($_POST['room_id']);
    $date_in  = $_POST['date_in'];
    $date_out = $_POST['date_out'];
    $payment  = floatval($_POST['payment_amount']);

    if($guest_id && $room_id && $date_in && $date_out){

        $stmt = $conn->prepare("
            INSERT INTO reservations
            (guest_id, room_id, date_in, date_out, status)
            VALUES (?, ?, ?, ?, 'Reserved')
        ");

        $stmt->bind_param("iiss",$guest_id,$room_id,$date_in,$date_out);
        $stmt->execute();

        $reservation_id = $stmt->insert_id;

        // update room
        $conn->query("UPDATE rooms SET status='Reserved' WHERE id=$room_id");

        // save optional payment
        if($payment > 0){

            $stmt_pay = $conn->prepare("
                INSERT INTO payments
                (reservation_id, amount, method, status)
                VALUES (?, ?, 'Airtel Money', 'Paid')
            ");

            $stmt_pay->bind_param("id",$reservation_id,$payment);
            $stmt_pay->execute();
        }

        echo "<script>alert('Reservation created successfully');window.location='reservations.php';</script>";
        exit;
    }
}


/* =========================================================
   CANCEL RESERVATION + EMAIL + 50% REFUND
========================================================= */
if(isset($_GET['cancel_id'])){

    $res_id = intval($_GET['cancel_id']);

    $res_info = $conn->query("
        SELECT r.*, g.email, g.name, rm.price, rm.room_number
        FROM reservations r
        JOIN guests g ON r.guest_id=g.id
        JOIN rooms rm ON r.room_id=rm.id
        WHERE r.id=$res_id
    ")->fetch_assoc();

    if($res_info){

        $room_id = $res_info['room_id'];

        $days = max(1,(strtotime($res_info['date_out']) - strtotime($res_info['date_in']))/86400);
        $total_amount = $res_info['price'] * $days;
        $refund_amount = $total_amount * 0.5;

        // insert refund
        $stmt_ref = $conn->prepare("
            INSERT INTO refunds
            (reservation_id, guest_id, total_amount, refund_amount, refund_status)
            VALUES (?, ?, ?, ?, 'Pending')
        ");

        $stmt_ref->bind_param(
            "iidd",
            $res_id,
            $res_info['guest_id'],
            $total_amount,
            $refund_amount
        );
        $stmt_ref->execute();

        // check if room has other reservations
        $active_res = $conn->query("
            SELECT id FROM reservations
            WHERE room_id=$room_id
            AND status='Reserved'
            AND id<>$res_id
        ");

        if($active_res->num_rows == 0){
            $conn->query("UPDATE rooms SET status='Available' WHERE id=$room_id");
        }

        $conn->query("UPDATE reservations SET status='Canceled' WHERE id=$res_id");

        /* ================= EMAIL ================= */

        if(!empty($res_info['email'])){

            $subject = "Reservation Cancellation & Refund Notice";

            $message = "
            Dear {$res_info['name']},<br><br>

            Your reservation has been <b>successfully canceled</b>.<br><br>

            <b>Reservation Details:</b><br>
            Room: {$res_info['room_number']}<br>
            Check-in: {$res_info['date_in']}<br>
            Check-out: {$res_info['date_out']}<br><br>

            <b>Refund Policy:</b><br>
            Total Amount: MK ".number_format($total_amount,2)."<br>
            Eligible Refund (50%): <b>MK ".number_format($refund_amount,2)."</b><br><br>

            Our finance team will process your refund shortly.<br><br>

            Regards,<br>
            Rams Lodge
            ";

            $headers  = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8\r\n";
            $headers .= "From: reservations@ramslodgemw.com\r\n";

            @mail($res_info['email'],$subject,$message,$headers);
        }

        echo "<script>alert('Reservation canceled. 50% refund initiated.');window.location='reservations.php';</script>";
        exit;
    }
}


/* =========================================================
   FETCH DATA
========================================================= */

$guests = $conn->query("SELECT * FROM guests ORDER BY name");

$rooms = $conn->query("
SELECT rm.*,

(
SELECT MIN(r.date_out)
FROM reservations r
WHERE r.room_id = rm.id
AND r.status='Reserved'
AND r.date_out >= CURDATE()
) AS next_available_date,

(
SELECT DATE_ADD(s.checkin_date, INTERVAL s.days DAY)
FROM stays s
WHERE s.room_id = rm.id
AND s.checkout_date IS NULL
LIMIT 1
) AS occupied_until

FROM rooms rm
ORDER BY rm.room_number
");


$res = $conn->query("
SELECT r.*, 
g.name AS guest_name, 
rm.room_number,
rm.price AS room_price,
IFNULL(SUM(p.amount),0) AS paid_amount,
DATEDIFF(r.date_out,r.date_in) AS days
FROM reservations r
JOIN guests g ON r.guest_id=g.id
JOIN rooms rm ON r.room_id=rm.id
LEFT JOIN payments p ON p.reservation_id=r.id AND p.status='Paid'
GROUP BY r.id
ORDER BY r.id DESC
");
?>

<div class="container mt-4">

<?php $username = $_SESSION['username'] ?? 'Guest'; ?>

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

<div class="d-flex gap-2 mb-3">

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

<a href="refund_report.php" target="_blank" class="btn btn-secondary">
Refund Report
</a>

</div>

<h4>Reservations</h4>
<hr>

<div class="row mb-3">

<div class="col-md-4">
<div class="card bg-success text-white">
<div class="card-body">
<h6>Available Rooms</h6>
<h3><?= $available_rooms ?></h3>
</div>
</div>
</div>

<div class="col-md-4">
<div class="card bg-warning">
<div class="card-body">
<h6>Reserved Rooms</h6>
<h3><?= $reserved_rooms ?></h3>
</div>
</div>
</div>

<div class="col-md-4">
<div class="card bg-danger text-white">
<div class="card-body">
<h6>Occupied Rooms</h6>
<h3><?= $occupied_rooms ?></h3>
</div>
</div>
</div>

</div>


<!-- CREATE RESERVATION -->

<form method="POST" class="row g-2 mb-4">

<div class="col-md-3">
<select name="guest_id" class="form-control" required>
<option value="">Select Guest</option>
<?php while($g=$guests->fetch_assoc()): ?>
<option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['name']) ?></option>
<?php endwhile; ?>
</select>
</div>


<div class="col-md-3">
<select name="room_id" class="form-control" required>
<option value="">Select Room</option>

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

$label="Room {$r['room_number']} ({$r['room_type']}) - MK ".number_format($r['price'],2);

$disabled="";
$extra="";

if($r['status']=='Occupied'){
$disabled="disabled";
$extra=" - Occupied until ".$r['occupied_until'];
}
elseif($r['status']=='Reserved'){
$extra=" - Reserved until ".$r['next_available_date'];
}

?>

<option value="<?= $r['id'] ?>" <?= $disabled ?>>
<?= $label.$extra ?>
</option>

<?php endwhile; ?>

</select>
</div>


<div class="col-md-2">
<input type="date" name="date_in" class="form-control" required>
</div>

<div class="col-md-2">
<input type="date" name="date_out" class="form-control" required>
</div>

<div class="col-md-2">
<input type="number" name="payment_amount" class="form-control" placeholder="Payment MK" step="0.01" min="0" value="0">
<small class="text-muted">Airtel Money (optional)</small>
</div>

<div class="col-md-2">
<button name="reserve" class="btn btn-warning w-100">
<i class="fa fa-bed"></i> Reserve
</button>
</div>

</form>


<table class="table table-bordered table-sm">

<thead class="table-dark">
<tr>
<th>Guest</th>
<th>Room</th>
<th>From</th>
<th>To</th>
<th>Days</th>
<th>Status</th>
<th>Paid (MK)</th>
<th>Remaining (MK)</th>
<th>Actions</th>
</tr>
</thead>

<tbody>

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

$days=max(1,$r['days']);
$total=$r['room_price']*$days;
$remaining=$total-$r['paid_amount'];

?>

<tr <?= $r['status']=='Canceled'?'class="table-danger"':'' ?>>

<td><?= htmlspecialchars($r['guest_name']) ?></td>
<td><?= $r['room_number'] ?></td>
<td><?= $r['date_in'] ?></td>
<td><?= $r['date_out'] ?></td>
<td><?= $days ?></td>
<td><?= $r['status'] ?></td>
<td><?= number_format($r['paid_amount'],2) ?></td>

<td class="<?= $remaining>0?'text-danger fw-bold':'text-success fw-bold' ?>">
<?= number_format($remaining,2) ?>
</td>

<td>

<?php if($r['status']=='Reserved'): ?>

<a href="reservations.php?cancel_id=<?= $r['id'] ?>"
class="btn btn-sm btn-danger"
onclick="return confirm('Cancel this reservation?')">

<i class="fa fa-times"></i> Cancel

</a>

<?php else: ?>

<span class="text-muted">N/A</span>

<?php endif; ?>

</td>

</tr>

<?php endwhile; ?>

</tbody>
</table>

</div>

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