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

$user_role = $_SESSION['role'] ?? 'guest';

// Fetch Guests
$guests = $conn->query("SELECT id, name FROM guests WHERE status=1 ORDER BY name");

// Selected guest
$guest_id = intval($_GET['guest_id'] ?? 0);

// Fetch items
$services = $conn->query("SELECT id, name, price FROM services ORDER BY name");
$restaurant_menu = $conn->query("SELECT id, name, price FROM restaurant_menu WHERE is_active=1 ORDER BY name");
$products = $conn->query("SELECT id, name, selling_price FROM products ORDER BY name");
$rooms = $conn->query("SELECT id, room_number, room_type, price FROM rooms ORDER BY room_number");

// ================= HANDLE ADD ITEM =================
if(isset($_POST['add_item'])){
    $guest_id = intval($_POST['guest_id']);
    $type = $_POST['item_type'];
    $item_id = intval($_POST['item_id']);
    $quantity = intval($_POST['quantity']) ?: 1;

    // Determine item details
    if($type=='Service'){
        $row = $conn->query("SELECT name, price FROM services WHERE id=$item_id")->fetch_assoc();
        $name = $row['name'] ?? null;
        $price = $row['price'] ?? 0;
    } elseif($type=='Restaurant'){
        $row = $conn->query("SELECT name, price FROM restaurant_menu WHERE id=$item_id")->fetch_assoc();
        $name = $row['name'] ?? null;
        $price = $row['price'] ?? 0;
    } elseif($type=='Product'){
        $row = $conn->query("SELECT name, selling_price FROM products WHERE id=$item_id")->fetch_assoc();
        $name = $row['name'] ?? null;
        $price = $row['selling_price'] ?? 0;
    } elseif($type=='Room'){
        $row = $conn->query("SELECT room_number, room_type, price FROM rooms WHERE id=$item_id")->fetch_assoc();
        if($row){
            $name = "ROOM ".$row['room_number']." (".$row['room_type'].")";
            $price = $row['price'];
        } else {
            $name = null;
            $price = 0;
        }
    }

    if(!$name){
        echo "<script>alert('Selected item not found!');window.history.back();</script>";
        exit;
    }

    $amount = $price * $quantity;
    $stmt = $conn->prepare("INSERT INTO quotations (guest_id, type, item_name, unit_price, quantity, amount) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("issidd", $guest_id, $type, $name, $price, $quantity, $amount);
    $stmt->execute();

    echo "<script>window.location='add_quotation.php?guest_id=$guest_id';</script>";
    exit;
}

// ================= HANDLE DELETE ITEM =================
if(isset($_GET['delete_id']) && in_array($user_role,['admin','manager'])){
    $delete_id = intval($_GET['delete_id']);
    $conn->query("DELETE FROM quotations WHERE id=$delete_id");
    echo "<script>window.location='add_quotation.php?guest_id=$guest_id';</script>";
    exit;
}

// ================= HANDLE FINALIZE QUOTATION =================
if(isset($_POST['finalize'])){
    $guest_id = intval($_POST['guest_id']);

    // Calculate total
    $total_amount = 0;
    $quotation_items = $conn->query("SELECT * FROM quotations WHERE guest_id=$guest_id");
    while($row = $quotation_items->fetch_assoc()){
        $total_amount += $row['amount'];
    }

    // Insert into finalized table
    $stmt = $conn->prepare("INSERT INTO quotation_finalized (guest_id, total_amount, created_at) VALUES (?, ?, NOW())");
    $stmt->bind_param("id", $guest_id, $total_amount);
    $stmt->execute();

    // Redirect to quotation.php to view quotation
    echo "<script>window.location='quotation.php?guest_id=$guest_id';</script>";
    exit;
}

// ================= FETCH QUOTATION ITEMS =================
$all_items = [];
$total_amount = 0;
if($guest_id){
    $quotation_items = $conn->query("SELECT * FROM quotations WHERE guest_id=$guest_id ORDER BY created_at ASC");
    while($row = $quotation_items->fetch_assoc()){
        $total_amount += $row['amount'];
        $all_items[] = $row;
    }
}
?>

<div class="container mt-4">
    <h3>Create Quotation</h3>

    <!-- SELECT GUEST -->
    <form method="GET" class="mb-3 row g-3">
        <div class="col-md-4">
            <label>Select Guest</label>
            <select name="guest_id" class="form-control" onchange="this.form.submit()">
                <option value="">-- Select Guest --</option>
                <?php while($g=$guests->fetch_assoc()): ?>
                    <option value="<?= $g['id'] ?>" <?= $g['id']==$guest_id?'selected':'' ?>><?= htmlspecialchars($g['name']) ?></option>
                <?php endwhile; ?>
            </select>
        </div>
    </form>

<?php if($guest_id): ?>
<!-- ADD ITEM FORM -->
<form method="POST" class="row g-3 mb-4">
    <input type="hidden" name="guest_id" value="<?= $guest_id ?>">
    <div class="col-md-3">
        <label>Type</label>
        <select name="item_type" id="item_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">Product</option>
            <option value="Room">Room</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" class="form-control" value="1" min="1">
    </div>
    <div class="col-md-2 d-flex align-items-end">
        <button type="submit" name="add_item" class="btn btn-success w-100"><i class="fa fa-plus"></i> Add</button>
    </div>
</form>

<!-- QUOTATION ITEMS TABLE -->
<table class="table table-bordered table-striped">
    <thead class="table-dark">
        <tr>
            <th>#</th>
            <th>Type</th>
            <th>Item</th>
            <th>Unit Price</th>
            <th>Qty</th>
            <th>Amount</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php $i=1; foreach($all_items as $q): ?>
        <tr>
            <td><?= $i++ ?></td>
            <td><?= htmlspecialchars($q['type']) ?></td>
            <td><?= htmlspecialchars($q['item_name']) ?></td>
            <td><?= number_format($q['unit_price'],2) ?></td>
            <td><?= $q['quantity'] ?></td>
            <td><?= number_format($q['amount'],2) ?></td>
            <td>
                <?php if(in_array($user_role,['admin','manager'])): ?>
                <a href="add_quotation.php?delete_id=<?= $q['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete item?')"><i class="fa fa-trash"></i></a>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        <tr>
            <td colspan="5" class="text-end"><strong>Total:</strong></td>
            <td colspan="2"><strong><?= number_format($total_amount,2) ?> MK</strong></td>
        </tr>
    </tbody>
</table>

<!-- FINALIZE QUOTATION BUTTON -->
<form method="POST" class="mt-3">
    <input type="hidden" name="guest_id" value="<?= $guest_id ?>">
    <button type="submit" name="finalize" class="btn btn-primary"><i class="fa fa-check"></i> Finalize Quotation</button>
</form>

<?php endif; ?>
</div>

<script>
// Load items dynamically
let services = <?= json_encode($services->fetch_all(MYSQLI_ASSOC)) ?>;
let restaurant_menu = <?= json_encode($restaurant_menu->fetch_all(MYSQLI_ASSOC)) ?>;
let products = <?= json_encode($products->fetch_all(MYSQLI_ASSOC)) ?>;
let rooms = <?= json_encode($rooms->fetch_all(MYSQLI_ASSOC)) ?>;

function loadItems(){
    let type = document.getElementById('item_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;
    if(type=='Room') list = rooms;

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

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