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

$guest_id = intval($_GET['guest_id'] ?? 0);
if(!$guest_id){
    echo "<div class='alert alert-danger'>Invalid Guest</div>";
    exit;
}

// ================= FETCH GUEST =================
$guest = $conn->query("SELECT * FROM guests WHERE id=$guest_id")->fetch_assoc();
if(!$guest){
    echo "<div class='alert alert-danger'>Guest not found</div>";
    exit;
}

// ================= FETCH LATEST STAY =================
$stay = $conn->query("
    SELECT s.*, r.room_number, r.room_type, r.price AS room_price
    FROM stays s
    JOIN rooms r ON s.room_id=r.id
    WHERE s.guest_id=$guest_id
    ORDER BY s.checkin_date DESC LIMIT 1
")->fetch_assoc();

if(!$stay){
    echo "<div class='alert alert-warning'>No active stay found for this guest</div>";
    exit;
}

// ================= CALCULATE COSTS =================
$days = $stay['days']; // directly from stays table
$room_cost = $stay['room_price'] * $days;

// Services
$services_res = $conn->query("
    SELECT name, quantity, amount
    FROM charges
    WHERE guest_id=$guest_id
    ORDER BY id ASC
");

$service_items = [];
$service_total = 0;
while($s = $services_res->fetch_assoc()){
    $service_items[] = $s;
    $service_total += floatval($s['amount']);
}

// Subtotal & Taxes
$subtotal = $room_cost + $service_total;
$tax_rate = 0.175;
$tax_due = $subtotal * $tax_rate;
$tourism_levy = $subtotal * 0.01;
$total_bill = $subtotal ;

// Payments received
$paid = $conn->query("
    SELECT SUM(amount) as total
    FROM payments
    WHERE guest_id=$guest_id AND status='Paid'
")->fetch_assoc()['total'] ?? 0;

$balance = $total_bill - $paid;

// ================= HANDLE PAYMENT =================
// ================= HANDLE PAYMENT =================
if(isset($_POST['save_payment'])){
    $amount = floatval($_POST['amount']);
    $discount = floatval($_POST['discount'] ?? 0); // New discount field
    $mode   = $_POST['mode'];
    $type   = $_POST['type'];

    // Adjusted payable amount
    $payable = max($amount - $discount, 0);

    if($payable > 0){
        $stmt = $conn->prepare("
            INSERT INTO payments (guest_id, amount,discount, type, method, status,state)
            VALUES (?,?,?,?,?,?,?)
        ");
        $status = "Paid";
           $state = 4;
        $stmt->bind_param("idddssi", $guest_id, $payable,$discount, $type, $mode, $status, $state);
        $stmt->execute();

        // Update invoice / stay balance
        $conn->query("
            UPDATE invoices 
            SET status = CASE 
                WHEN (SELECT SUM(amount) FROM payments WHERE guest_id=$guest_id AND status='Paid') >= total_amount THEN 'Paid'
                WHEN (SELECT SUM(amount) FROM payments WHERE guest_id=$guest_id AND status='Paid') > 0 THEN 'Partially Paid'
                ELSE 'Unpaid'
            END
            WHERE stay_id={$stay['id']}
        ");


        // ================= SEND EMAIL ALERT =================
        $admin_emails = [
            'giantplusmw@gmail.com',
            'rams.investments@gmail.com'
        ];

        $subject = "New Payment Received - RAMS EXECUTIVE LODGE";

        $message = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; background:#f4f6f8; padding:20px; }
                .box { max-width:600px; margin:auto; background:#ffffff; padding:20px; border-radius:8px; border-top:5px solid #28a745; }
                .title { font-size:20px; font-weight:bold; color:#28a745; margin-bottom:15px; }
                .row { margin:6px 0; }
                .label { font-weight:bold; color:#333; }
                .footer { margin-top:20px; font-size:12px; color:#888; text-align:center; }
            </style>
        </head>
        <body>
            <div class='box'>
                <div class='title'>💰 New Payment Received</div>
                <div class='row'><span class='label'>Guest:</span> ".htmlspecialchars($guest['name'])."</div>
                <div class='row'><span class='label'>Stay ID:</span> ".$stay['id']."</div>
                <div class='row'><span class='label'>Amount:</span> ".number_format($amount,2)."</div>
                <div class='row'><span class='label'>Payment Type:</span> ".htmlspecialchars($type)."</div>
                <div class='row'><span class='label'>Payment Mode:</span> ".htmlspecialchars($mode)."</div>
                <div class='row'><span class='label'>Date:</span> ".date('Y-m-d H:i:s')."</div>
                <div class='footer'>RAMS Executive Lodge System</div>
            </div>
        </body>
        </html>
        ";

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

        foreach($admin_emails as $to){
            @mail($to, $subject, $message, $headers);
        }

        // ================= REDIRECT =================
        echo "<script>
            alert('Payment recorded successfully!');
            window.location.href='invoices.php';
        </script>";
        exit;
    } else {
        echo "<div class='alert alert-danger'>Enter a valid amount</div>";
    }
}
// ================= FETCH PAYMENT HISTORY =================
$payments = $conn->query("SELECT * FROM payments WHERE guest_id=$guest_id ORDER BY payment_date DESC");

// ================= GENERATE QR =================
$qr_data = urlencode("Guest: ".$guest['name']." Stay: ".$stay['room_number']." Invoice Payment");
$qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=".$qr_data;

// Logo
$logo = "assets/logo.png";
?>

<div class="container mt-3">
      <button class="btn btn-secondary" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>
    <div class="welcome-msg mb-3">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>


    <h3>Receive Payment for <?= htmlspecialchars($guest['name']) ?></h3>

    <!-- Stay & Services Summary -->
    <table class="table table-bordered table-striped">
        <tr>
            <th>Room</th>
            <td><?= $stay['room_number'] ?> (<?= $stay['room_type'] ?>)</td>
        </tr>
        <tr>
            <th>Check-in</th>
            <td><?= $stay['checkin_date'] ?></td>
        </tr>
        <tr>
            <th>Days</th>
            <td><?= $days ?></td>
        </tr>
        <tr>
            <th>Room Cost</th>
            <td><?= number_format($room_cost,2) ?></td>
        </tr>
        <tr>
            <th colspan="2" class="text-center bg-light">Services Incurred</th>
        </tr>
        <?php foreach($service_items as $srv): ?>
        <tr>
            <td><?= htmlspecialchars($srv['name']) ?> (Qty: <?= $srv['quantity'] ?>)</td>
            <td><?= number_format($srv['amount'],2) ?></td>
        </tr>
        <?php endforeach; ?>
        <tr>
            <th>Subtotal</th>
            <td><?= number_format($subtotal,2) ?></td>
        </tr>
        <tr>
            <th>VAT (17.5%)</th>
            <td><?= number_format($tax_due,2) ?></td>
        </tr>
        <tr>
            <th>Tourism Levy (1%)</th>
            <td><?= number_format($tourism_levy,2) ?></td>
        </tr>
        <tr class="table-dark text-white">
            <th>Total Bill</th>
            <td><?= number_format($total_bill,2) ?></td>
        </tr>
        <tr class="table-success">
            <th>Paid</th>
            <td>
                <span class="badge bg-success"><i class="fa fa-check"></i> <?= number_format($paid,2) ?></span>
            </td>
        </tr>
        <tr class="<?= $balance>0?'table-danger':'table-primary' ?>">
            <th>Balance</th>
            <td><?= number_format($balance,2) ?></td>
        </tr>
    </table>

    <!-- Payment Form -->
    <div class="card mb-3">
        <div class="card-body">
            <h5><i class="fa fa-money-bill-wave"></i> Record Payment</h5>
            <form method="POST">
   <div class="mb-3">
    <label for="amount" class="form-label fw-bold">💰 Amount (MWK)</label>
    <div class="input-group">
        <span class="input-group-text bg-success text-white"><i class="fa fa-money-bill-wave"></i></span>
        <input type="number" 
               step="0.01" 
               name="amount" 
               id="amount" 
               class="form-control fw-bold text-danger fs-5" 
               readonly>
        <span class="input-group-text bg-light text-dark">MWK</span>
    </div>
    <small class="text-muted">This is the remaining balance. You cannot modify it manually.</small>
</div>

<script>
    const balance = <?= $balance ?>;
    const amountInput = document.getElementById('amount');
    amountInput.value = balance > 0 ? balance.toFixed(2) : "0.00";
</script>

<div class="mb-3">
    <label for="discount" class="form-label fw-bold">🎁 Discount (MWK)</label>
    <div class="input-group">
        <span class="input-group-text bg-warning text-white"><i class="fa fa-gift"></i></span>
        <input type="number" 
               step="0.01" 
               name="discount" 
               id="discount" 
               class="form-control fw-bold text-success fs-5" 
               value="0.00">
        <span class="input-group-text bg-light text-dark">MWK</span>
    </div>
    <small class="text-muted">Enter any discount to reduce the total payable amount.</small>
</div>
                <div class="mb-2">
                    <label>Payment Type</label>
                    <select name="type" class="form-control" required>
                        <option value="Room">Room</option>
                        <option value="Bar">Bar</option>
                        <option value="Restaurant">Restaurant</option>
                        <option value="Room Service">Room Service</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div class="mb-2">
                    <label>Payment Mode</label>
                   <div class="form-group">
    <label><i class="fa fa-credit-card"></i> Payment Mode</label>

    <select name="mode" id="payment_mode" class="form-control" required>
        <option value="">-- Select Payment Mode --</option>

        <option value="Cash">💵 Cash</option>
        <option value="Mobile Money">📱 Mobile Money</option>
        <option value="Airtel Money">📲 Airtel Money</option>
        <option value="TNM Mpamba">📲 TNM Mpamba</option>
        <option value="Card">💳 Card (POS)</option>
        <option value="Bank Transfer">🏦 Bank Transfer</option>
        <option value="Cheque">🧾 Cheque</option>
        <option value="Online Payment">🌐 Online Payment</option>
        <option value="Digital Wallet">👛 Digital Wallet</option>
        <option value="Other">➕ Other</option>
    </select>
</div>
                </div>
                <button type="submit" name="save_payment" class="btn btn-success">
                    <i class="fa fa-check-circle"></i> Submit Payment
                </button>
            </form>
        </div>
    </div>

    <!-- Payment History -->
    <h5><i class="fa fa-history"></i> Payment History</h5>
    <table class="table table-striped">
        <thead class="table-dark text-white">
            <tr>
                <th>Date</th>
                <th>Purpose</th>
                <th>Mode</th>
                <th>Amount</th>
            </tr>
        </thead>
        <tbody>
        <?php while($p = $payments->fetch_assoc()): ?>
            <tr>
                <td><?= $p['payment_date'] ?></td>
                <td><?= htmlspecialchars($p['type']) ?></td>
                <td><?= htmlspecialchars($p['method']) ?></td>
                <td><?= number_format($p['amount'],2) ?></td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>

    <!-- PDF & Print -->
    <div class="mb-3">
        <a href="receipt_pdf.php?stay_id=<?= $stay['id'] ?>" class="btn btn-primary">
            <i class="fa fa-file-pdf"></i> Download Invoice PDF
        </a>
        <button class="btn btn-info" onclick="window.open('receipt_pdf.php?stay_id=<?= $stay['id'] ?>','_blank')">
            <i class="fa fa-print"></i> Print Receipt
        </button>
        <a href="invoices.php" class="btn btn-secondary">
            <i class="fa fa-arrow-left"></i> Back to Invoices
        </a>
    </div>
</div>

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