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

$stay_id = intval($_GET['stay_id'] ?? 0);

if(!$stay_id){
    echo "<script>alert('Invalid stay ID');window.location='checkin.php';</script>";
    exit;
}

/* ================= FETCH STAY ================= */
$stay = $conn->query("
    SELECT s.id AS stay_id, s.guest_id, s.days,s.room_id, s.checkin_date, 
           s.checkout_date, s.days, s.locked_room_price, s.services_closed,
           g.name AS guest_name, r.room_number, r.price AS room_price
    FROM stays s
    JOIN guests g ON s.guest_id=g.id
    JOIN rooms r ON s.room_id=r.id
    WHERE s.id = $stay_id
")->fetch_assoc();

if(!$stay){
    echo "<script>alert('Stay not found');window.location='checkin.php';</script>";
    exit;
}

/* ================= LOCK ROOM PRICE ================= */
if(!$stay['locked_room_price'] || $stay['locked_room_price'] == 0){
    $conn->query("UPDATE stays SET locked_room_price={$stay['room_price']} WHERE id=$stay_id");
    $stay['locked_room_price'] = $stay['room_price'];
}

$services_closed = $stay['services_closed'];

/* ================= FETCH ITEMS ================= */
$services_res = $conn->query("SELECT id, name, price FROM services ORDER BY name");
$restaurant_res = $conn->query("SELECT id, name, price FROM restaurant_menu WHERE is_active=1 ORDER BY name");
// Only fetch products that are in Bar category (category_id = 13)
$products_res = $conn->query("SELECT id, name, selling_price FROM products WHERE category_id=13 ORDER BY name");

$services_data = [];
while($s = $services_res->fetch_assoc()) $services_data[] = $s;

$restaurant_data = [];
while($r = $restaurant_res->fetch_assoc()) $restaurant_data[] = $r;

$products_data = [];
while($p = $products_res->fetch_assoc()) $products_data[] = $p;


/* ================= ADD ITEM ================= */
if(isset($_POST['add_service']) && !$services_closed){

    $type = $_POST['service_type'];
    $item_id = intval($_POST['item_id']);
    $quantity = intval($_POST['quantity']) ?: 1;

    if($type == 'Service'){
        $row = $conn->query("SELECT name, price FROM services WHERE id=$item_id")->fetch_assoc();
        $unit_price = $row['price'];
    } elseif($type == 'Restaurant'){
        $row = $conn->query("SELECT name, price FROM restaurant_menu WHERE id=$item_id")->fetch_assoc();
        $unit_price = $row['price'];
    } elseif($type == 'Product'){
        $row = $conn->query("SELECT name, selling_price FROM products WHERE id=$item_id")->fetch_assoc();
        $unit_price = $row['selling_price'];
    }

    $amount = $unit_price * $quantity;

    $stmt = $conn->prepare("INSERT INTO charges (guest_id, name, amount, quantity, created_at) VALUES (?, ?, ?, ?, NOW())");
    $stmt->bind_param("isdi", $stay['guest_id'], $row['name'], $amount, $quantity);
    $stmt->execute();

    echo "<script>alert('Item added successfully');window.location='add_services.php?stay_id=$stay_id';</script>";
    exit;
}


/* ================= DELETE ITEM ================= */
if(isset($_GET['delete_id']) && !$services_closed){
    $delete_id = intval($_GET['delete_id']);
    $conn->query("DELETE FROM charges WHERE id=$delete_id AND guest_id={$stay['guest_id']}");
    echo "<script>alert('Item removed successfully');window.location='add_services.php?stay_id=$stay_id';</script>";
    exit;
}


/* ================= UPDATE QUANTITY ================= */
if(isset($_POST['update_quantity']) && !$services_closed){

    $charge_id = intval($_POST['charge_id']);
    $quantity = intval($_POST['quantity']) ?: 1;

    $row = $conn->query("SELECT name FROM charges WHERE id=$charge_id AND guest_id={$stay['guest_id']}")->fetch_assoc();

    if($row){
        $name = $row['name'];

        $price_row = $conn->query("
            SELECT price FROM services WHERE name='$name'
            UNION
            SELECT price FROM restaurant_menu WHERE name='$name'
            UNION
            SELECT selling_price FROM products WHERE name='$name'
        ")->fetch_assoc();

        $unit_price = $price_row['price'] ?? $price_row['selling_price'] ?? 0;
        $amount = $unit_price * $quantity;

        $conn->query("UPDATE charges SET quantity=$quantity, amount=$amount 
                      WHERE id=$charge_id AND guest_id={$stay['guest_id']}");
    }

    echo "<script>alert('Quantity updated');window.location='add_services.php?stay_id=$stay_id';</script>";
    exit;
}


/* ================= CLOSE SERVICES ================= */
if(isset($_POST['close_services'])){
    $conn->query("UPDATE stays SET services_closed=1 WHERE id=$stay_id");
    echo "<script>alert('Services closed');window.location='add_services.php?stay_id=$stay_id';</script>";
    exit;
}


/* ================= FETCH CHARGES ================= */
$allocated_services = $conn->query("SELECT * FROM charges WHERE guest_id={$stay['guest_id']} ORDER BY created_at DESC");

$total_services = $conn->query("SELECT IFNULL(SUM(amount),0) AS total 
                                FROM charges WHERE guest_id={$stay['guest_id']}")
                                ->fetch_assoc()['total'];

$nights = $stay['days'];
$total_room = $stay['locked_room_price'] * $nights;

$vat = ($total_services + $total_room) * 0.16;
$levy = ($total_services + $total_room) * 0.02;
$grand_total = $total_services + $total_room ;
?>

<div class="container mt-4">

<h4>Services & Items for <?= htmlspecialchars($stay['guest_name']) ?> (Room <?= $stay['room_number'] ?>)</h4>
<hr>

<?php if(!$services_closed): ?>

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

    <div class="col-md-3">
        <label>Type</label>
        <select name="service_type" id="service_type" class="form-control" required onchange="loadItems()">
            <option value="">Select Type</option>
            <option value="Service">Service</option>
            <option value="Restaurant">Restaurant</option>
            <option value="Product">Bar Item</option>
        </select>
    </div>

    <div class="col-md-3">
        <label>Item</label>
        <select name="item_id" id="item_select" class="form-control" required>
            <option value="">Select Item</option>
        </select>
    </div>

    <div class="col-md-2">
        <label>Quantity</label>
        <input type="number" name="quantity" value="1" min="1" class="form-control">
    </div>

    <div class="col-md-2 d-flex align-items-end">
        <button type="submit" name="add_service" class="btn btn-success w-100">Add</button>
    </div>

</form>
<div class="checkout-reminder">
    <i class="fa fa-exclamation-triangle"></i>
    <strong>Reminder:</strong>
    Make sure you close services before checking out or recieving a payment from a guest.
</div>

<style>
.checkout-reminder{
    background: linear-gradient(135deg, #fff3cd, #ffe69c);
    border-left: 6px solid #ffc107;
        border: 2px solid #dc3545;          /* ✅ RED BORDER */
    color: #664d03;
    padding: 14px 18px;
    border-radius: 10px;
    font-size: 0.95rem;
    margin-bottom: 15px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    display: flex;
    align-items: center;
    gap: 10px;
}

.checkout-reminder i{
    font-size: 20px;
    color: #ff9800;
}

/* subtle animation */
.checkout-reminder{
    animation: fadeInReminder .4s ease-in-out;
}

@keyframes fadeInReminder{
    from{opacity:0; transform: translateY(-5px);}
    to{opacity:1; transform: translateY(0);}
}
</style>
<form method="POST">
    <button type="submit" name="close_services" class="btn btn-danger">Close Services</button>
</form>

<?php endif; ?>


<h5 class="mt-4">Allocated Items</h5>

<table class="table table-bordered">
<tr>
    <th>#</th>
    <th>Name</th>
    <th>Qty</th>
    <th>Amount</th>
      <th>Date Created</th>
    <?php if(!$services_closed): ?><th>Action</th><?php endif; ?>
</tr>

<?php $i=1; while($a=$allocated_services->fetch_assoc()): ?>
<tr>
    <td><?= $i++ ?></td>
    <td><?= htmlspecialchars($a['name']) ?></td>
    <td><?= $a['quantity'] ?></td>
    <td><?= number_format($a['amount'],2) ?></td>
       <td><?= date('d F Y', strtotime($a['created_at'])) ?></td>

    <?php if(!$services_closed): ?>
    <td>
        <a href="add_services.php?stay_id=<?= $stay_id ?>&delete_id=<?= $a['id'] ?>"
           onclick="return confirm('Remove item?')" 
           class="btn btn-sm btn-danger">Remove</a>
    </td>
    <?php endif; ?>
</tr>
<?php endwhile; ?>
</table>


<div class="mt-3 p-3 border bg-light">
    <p><strong>Total Services:</strong> <?= number_format($total_services,2) ?> MK</p>
    <p><strong>Total Room:</strong> <?= number_format($total_room,2) ?> MK</p>
   
    <h5><strong>Grand Total: <?= number_format($grand_total,2) ?> MK</strong></h5>
</div>

</div>
<div class="mt-4 d-flex gap-2">

    <!-- Receive Payment -->
    <a href="receive_payment.php?guest_id=<?= $stay['guest_id'] ?>&stay_id=<?= $stay['stay_id'] ?>" 
       class="btn btn-success">
       <i class="fa fa-money-bill-wave"></i> Receive Payment
    </a>

    <!-- Invoice -->
    <a href="invoice.php?stay_id=<?= $stay['stay_id'] ?>" 
       class="btn btn-dark">
       <i class="fa fa-file-invoice-dollar"></i> Invoice
    </a>

    <!-- Checkout (disable if services not closed) -->
    <?php if(!$services_closed): ?>
        <button class="btn btn-primary" onclick="alert('Please close services before checkout')">
            <i class="fa fa-file-invoice"></i> Checkout
        </button>
    <?php else: ?>
        <a href="checkout.php?stay_id=<?= $stay['stay_id'] ?>" class="btn btn-primary">
            <i class="fa fa-file-invoice"></i> Checkout
        </a>
    <?php endif; ?>

</div>

<!-- FIXED CSS -->
<style>
.tips-box {
    background-color: #f0f9ff;
    border-left: 6px solid #0ea5e9;
    padding: 12px;
    border-radius: 6px;
    margin-top: 15px;
}
</style>


<!-- WORKING DROPDOWN SCRIPT -->
<script>
let services = <?= json_encode($services_data) ?>;
let restaurant_menu = <?= json_encode($restaurant_data) ?>;
let products = <?= json_encode($products_data) ?>;

function loadItems(){
    let type = document.getElementById('service_type').value;
    let select = document.getElementById('item_select');
    select.innerHTML = '<option value="">Select Item</option>';

    let list = [];

    if(type === 'Service') list = services;
    if(type === 'Restaurant') list = restaurant_menu;
    if(type === 'Product') list = products;

    list.forEach(item=>{
        let price = item.price ?? item.selling_price ?? 0;
        let option = document.createElement('option');
        option.value = item.id;
        option.text = item.name + ' (' + price + ' MK)';
        select.appendChild(option);
    });
}
</script>

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