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

// ================= VALIDATE STAY ID =================
if (!isset($_GET['stay_id']) || !is_numeric($_GET['stay_id'])) {
    echo "<script>
        alert('Invalid stay ID');
        window.location='checkouts.php';
    </script>";
    exit;
}

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

// ================= FETCH STAY INFO =================
$stay = $conn->query("
    SELECT s.*, g.id AS guest_id, g.name AS guest_name, r.id AS room_id 
    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();

// ❌ CHECK IF STAY EXISTS
if (!$stay) {
    echo "<script>
        alert('Invalid stay selected');
        window.location='checkouts.php';
    </script>";
    exit;
}

// ❌ CHECK IF ALREADY CHECKED OUT
if (!empty($stay['checkout_date'])) {
    echo "<script>
        alert('Guest already checked out');
        window.location='checkouts.php';
    </script>";
    exit;
}

// ================= CHECK UNPAID BILLS =================
$unpaid_tabs = $conn->query("
    SELECT COUNT(*) AS unpaid_count
    FROM bar_tabs
    WHERE guest_id = {$stay['guest_id']}
      AND status = 'Open'
")->fetch_assoc()['unpaid_count'] ?? 0;

if ($unpaid_tabs > 0) {
    echo "<script>
        alert('Cannot checkout: Guest has $unpaid_tabs unpaid bar tab(s). Please settle the bills first.');
        window.location='checkouts.php';
    </script>";
    exit;
}

// ================= CHECK IF INVOICE EXISTS =================
$invoice_exists = $conn->query("
    SELECT id 
    FROM invoices 
    WHERE stay_id = {$stay_id} AND guest_id = {$stay['guest_id']}
    LIMIT 1
")->num_rows > 0;

// ================= PERFORM CHECKOUT =================
$conn->begin_transaction();

try {
    // Update stay with checkout date
    $stmt1 = $conn->prepare("UPDATE stays SET checkout_date = NOW() WHERE id = ?");
    $stmt1->bind_param("i", $stay_id);
    $stmt1->execute();

    // Make room available
    $stmt2 = $conn->prepare("UPDATE rooms SET status='Available' WHERE id = ?");
    $stmt2->bind_param("i", $stay['room_id']);
    $stmt2->execute();

    // Create invoice if missing
  // Create invoice if missing
if (!$invoice_exists) {

    // Calculate total_amount (room charge + closed bar tabs)
    $room_charge = $stay['total_amount'] ?? 0; // Assuming stays table has total_amount
    $bar_charge = $conn->query("
        SELECT SUM(total) AS total 
        FROM bar_tabs 
        WHERE guest_id = {$stay['guest_id']} AND status='Closed'
    ")->fetch_assoc()['total'] ?? 0;

    $total_amount = $room_charge + $bar_charge;

    // Generate invoice_number (e.g., INV-YYYYMMDD-HHMMSS)
    $invoice_number = 'INV-' . date('Ymd-His');

    // Issue date
    $issue_date = date('Y-m-d');

    // Due date = 30 days from issue_date
    $due_date = date('Y-m-d', strtotime('+30 days'));

   // Created by (from session)
$created_by = $_SESSION['username'] ?? 'system';
$description = "Room: {$room_charge}, Bar: {$bar_charge}, Stay ID: {$stay_id}";

// Insert invoice
$stmt3 = $conn->prepare("
    INSERT INTO invoices 
    (stay_id, guest_id, invoice_number, total_amount, issue_date, due_date, created_by, description, created_at) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
");

$stmt3->bind_param(
    "iisdssss",
    $stay_id,
    $stay['guest_id'],
    $invoice_number,
    $total_amount,
    $issue_date,
    $due_date,
    $created_by,
    $description
);

$stmt3->execute();

// ================= UPDATE CONF = 3 =================
$invoice_id = $conn->insert_id;

$stmt4 = $conn->prepare("UPDATE invoices SET conf = 3 WHERE id = ?");
$stmt4->bind_param("i", $invoice_id);
$stmt4->execute();
}

    $conn->commit();

    // ================= SEND EMAIL ALERT =================
    // ================= SEND EMAIL ALERT =================
$checked_out_by = $_SESSION['username'] ?? 'Unknown Staff';


    $admin_emails = [
        'giantplusmw@gmail.com',
        'rams.investments@gmail.com'
    ];

    $subject = "Guest Checkout Alert - 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'>✅ Guest Checked Out</div>

            <div class='row'><span class='label'>Guest:</span> {$stay['guest_name']}</div>
            <div class='row'><span class='label'>Stay ID:</span> {$stay_id}</div>
            <div class='row'><span class='label'>Room ID:</span> {$stay['room_id']}</div>
            <div class='row'><span class='label'>Checkout Time:</span> " . date('Y-m-d H:i:s') . "</div>
            <div class='row'><span class='label'>Checked Out By:</span> {$checked_out_by}</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 =================
    $msg = $invoice_exists
        ? "Checkout successful. Invoice already exists."
        : "Checkout successful. Invoice created.";

    echo "<script>
        alert('{$msg}');
        window.location='checkouts.php?stay_id={$stay_id}';
    </script>";

} catch (Exception $e) {
    $conn->rollback();
    echo "<script>
        alert('Error during checkout: " . addslashes($e->getMessage()) . "');
        window.location='checkouts.php';
    </script>";
}
?>
