<?php
ob_start(); // start output buffering
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

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

if (!$guest_id || !$type) {
    echo "<div class='alert alert-danger'>Invalid parameters.</div>";
    echo "<a href='payments.php' class='btn btn-secondary mt-3'>Back to Payments</a>";
    exit;
}

// ================== CHECK IF CHARGE WAS REMOVED ==================
$removed_stmt = $conn->prepare("SELECT id FROM guest_removed_charges WHERE guest_id=? AND type=?");
$removed_stmt->bind_param("is", $guest_id, $type);
$removed_stmt->execute();
$removed_res = $removed_stmt->get_result();
if ($removed_res->num_rows > 0) {
    echo "<div class='alert alert-danger'>Cannot edit charge '$type'. This charge was removed for this guest.</div>";
    echo "<a href='payments.php?guest_id=$guest_id' class='btn btn-secondary mt-3'>Back to Payments</a>";
    exit;
}

// ================== GET BASE CHARGE AMOUNT ==================
$charge_amount = 0;

// 1. Room charge
if ($type == 'Room') {
    $stay = $conn->query("SELECT s.days, r.price FROM stays s JOIN rooms r ON s.room_id=r.id WHERE s.guest_id=$guest_id AND s.checkout_date IS NULL LIMIT 1")->fetch_assoc();
    $charge_amount = $stay ? $stay['days'] * $stay['price'] : 0;
}

// 2. Conference charge
elseif ($type == 'Conference') {
    $guest_name = $conn->query("SELECT name FROM guests WHERE id=$guest_id")->fetch_assoc()['name'] ?? '';
    if ($guest_name) {
        $conf_res = $conn->prepare("SELECT SUM(total_amount) as total FROM conference_bookings WHERE client_name=? AND status<>?");
        $status_cancelled = 'CANCELLED';
        $conf_res->bind_param("ss", $guest_name, $status_cancelled);
        $conf_res->execute();
        $charge_amount = $conf_res->get_result()->fetch_assoc()['total'] ?? 0;
    }
}

// 3. Standard charges from charges table
else {
    $charge_row = $conn->prepare("SELECT amount FROM charges WHERE name=? LIMIT 1");
    $charge_row->bind_param("s", $type);
    $charge_row->execute();
    $charge_amount = $charge_row->get_result()->fetch_assoc()['amount'] ?? 0;
}

// ================== GET TOTAL PAID ==================
$paid_stmt = $conn->prepare("SELECT SUM(amount) as total_paid FROM payments WHERE guest_id=? AND type=?");
$paid_stmt->bind_param("is", $guest_id, $type);
$paid_stmt->execute();
$paid = $paid_stmt->get_result()->fetch_assoc()['total_paid'] ?? 0;

// ================== HANDLE FORM SUBMISSION ==================
if (isset($_POST['update_charge'])) {
    $new_amount = floatval($_POST['amount']);
    
    if ($new_amount < $paid) {
        echo "<div class='alert alert-danger'>Cannot set charge below amount already paid (".number_format($paid,2)." MK).</div>";
    } else {
        // Since no guest_custom_charges table, we update only the charges table for standard charges
        if ($type != 'Room' && $type != 'Conference') {
            $update_stmt = $conn->prepare("UPDATE charges SET amount=? WHERE name=?");
            $update_stmt->bind_param("ds", $new_amount, $type);
            if ($update_stmt->execute()) {
                header("Location: payments.php?guest_id=$guest_id&msg=Charge '".urlencode($type)."' updated successfully");
                exit;
            } else {
                echo "<div class='alert alert-danger'>Error updating charge: ".$update_stmt->error."</div>";
            }
        } else {
            // Room and Conference charges are dynamic and cannot be manually updated
            echo "<div class='alert alert-danger'>Cannot manually update Room or Conference charges. They are calculated automatically.</div>";
        }
    }
}
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
    <h4>Edit Charge: <?= htmlspecialchars($type) ?></h4>
    <hr>

    <form method="POST" class="row g-3">
        <div class="col-md-4">
            <label>Current Total Charge (MK)</label>
            <input type="number" class="form-control" value="<?= number_format($charge_amount,2) ?>" disabled>
        </div>
        <div class="col-md-4">
            <label>Total Paid (MK)</label>
            <input type="number" class="form-control" value="<?= number_format($paid,2) ?>" disabled>
        </div>
        <div class="col-md-4">
            <label>New Charge Amount (MK)</label>
            <input type="number" step="0.01" name="amount" class="form-control" 
                   value="<?= number_format($charge_amount,2) ?>" 
                   min="<?= $paid ?>" 
                   <?= ($type == 'Room' || $type == 'Conference') ? 'disabled' : '' ?> 
                   required>
            <?php if($type == 'Room' || $type == 'Conference'): ?>
                <small class="text-muted">Room and Conference charges are calculated automatically.</small>
            <?php else: ?>
                <small class="text-muted">Cannot be less than paid amount (<?= number_format($paid,2) ?> MK)</small>
            <?php endif; ?>
        </div>
        <div class="col-md-2 mt-3">
            <button type="submit" name="update_charge" class="btn btn-success w-100" <?= ($type == 'Room' || $type == 'Conference') ? 'disabled' : '' ?>>Update Charge</button>
        </div>
        <div class="col-md-2 mt-3">
            <a href="payments.php?guest_id=<?= $guest_id ?>" class="btn btn-secondary w-100">Cancel</a>
        </div>
    </form>
</div>

<?php include 'includes/footer.php'; 
ob_end_flush(); // flush the buffer
?>

