<?php
include 'includes/auth.php';
include 'db.php';
require_once 'dompdf/vendor/autoload.php'; // DOMPDF

use Dompdf\Dompdf;

// Get guest ID
$guest_id = intval($_GET['guest_id'] ?? 0);
if(!$guest_id) exit("Invalid Guest ID");

// Fetch latest stay for guest
$stay = $conn->query("
    SELECT s.*, g.name AS guest_name, g.phone,
           r.room_number, r.room_type, IFNULL(r.price,0) AS price
    FROM stays s
    JOIN guests g ON s.guest_id=g.id
    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) exit("No active stay found for this guest");

// Calculate room cost
$room_cost = $stay['price'] * $stay['days'];

// Fetch individual services
$service_items_res = $conn->query("
    SELECT name, quantity, amount
    FROM charges
    WHERE guest_id={$stay['guest_id']}
    ORDER BY id ASC
");

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

// Totals
$subtotal = $room_cost + $service_total;
$tax_rate = 0.175;
$tax_due = $subtotal * $tax_rate;
$tourism_levy = $subtotal * 0.01;
$total_bill = $subtotal + $tax_due + $tourism_levy;

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

$balance = $total_bill - $paid;

// Invoice number (use existing or generate new)
$inv_check = $conn->query("SELECT * FROM invoices WHERE stay_id={$stay['id']}")->fetch_assoc();
if($inv_check){
    $invoice_number = $inv_check['invoice_number'];
} else {
    $last_inv = $conn->query("SELECT invoice_number FROM invoices ORDER BY id DESC LIMIT 1")->fetch_assoc();
    $num = $last_inv ? intval(preg_replace('/[^0-9]/','',$last_inv['invoice_number']))+1 : 1001;
    $invoice_number = "INV-$num";
}

// Dates
$checkin = strtotime($stay['checkin_date']);
$checkout = strtotime("+{$stay['days']} days", $checkin);

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

// Logo path (absolute or relative)
$logo_path = __DIR__ . "/assets/logo.png";
if(file_exists($logo_path)){
    $logo_pdf = 'file://'.$logo_path;
} else {
    $logo_pdf = '';
}

// =================== HTML ===================
$html = '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: monospace; font-size:12px; }
.header-flex { display:flex; justify-content:space-between; align-items:center; }
table { width:100%; border-collapse:collapse; margin-top:10px; }
td, th { padding:5px; border:1px solid #000; }
th { background:#333; color:#fff; }
.total-row td { font-weight:bold; border-top:2px solid #000; }
.text-end { text-align:right; }
</style>
</head>
<body>

<div class="header-flex">
    <div>';
if($logo_pdf) $html .= '<img src="'.$logo_pdf.'" style="height:80px;">';
$html .= '</div>

    <div class="text-center">
        <h3 style="margin:0;">QUOTATION</h3>
         <strong>TPIN:30798071</strong><br>
        <strong>Mponela Trading Centre</strong><br>
        Phone: 0993 899 382<br>
        Cell: 0885 899 293
    </div>

    <div class="text-end">
        <img src="'.$qr_url.'">
    </div>
</div>

<hr>

<div>
    <strong>Customer:</strong> '.htmlspecialchars($stay['guest_name']).'<br>
    <strong>Room:</strong> '.$stay['room_number'].' ('.$stay['room_type'].')<br>
    <strong>Invoice #:</strong> '.$invoice_number.'<br>
    <strong>Check-in:</strong> '.date('d/m/Y',$checkin).' - '.date('d/m/Y',$checkout).'
</div>

<table>
    <thead>
        <tr>
            <th>DESCRIPTION</th>
            <th>UNIT PRICE</th>
            <th>QTY</th>
            <th>No of days</th>
            <th>AMOUNT</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>ROOM ACCOMMODATION</td>
            <td class="text-end">'.number_format($stay['price'],2).'</td>
            <td class="text-end">1</td>
            <td class="text-end">'.$stay['days'].'</td>
            <td class="text-end">'.number_format($room_cost,2).'</td>
        </tr>';

foreach($service_items as $srv){
    $html .= '<tr>
        <td>'.htmlspecialchars($srv['name']).'</td>
        <td class="text-end">'.number_format($srv['amount'],2).'</td>
        <td class="text-end">'.$srv['quantity'].'</td>
        <td class="text-end">1</td>
        <td class="text-end">'.number_format($srv['amount'],2).'</td>
    </tr>';
}

$html .= '
    </tbody>
</table>

<table>
    <tr>
        <td>Subtotal</td>
        <td class="text-end">'.number_format($subtotal,2).'</td>
    </tr>
    <tr>
        <td>Tax (17.5%)</td>
        <td class="text-end">'.number_format($tax_due,2).'</td>
    </tr>
    <tr>
        <td>Tourism Levy</td>
        <td class="text-end">'.number_format($tourism_levy,2).'</td>
    </tr>
    <tr class="total-row">
        <td>Total</td>
        <td class="text-end">'.number_format($total_bill,2).'</td>
    </tr>
    <tr>
        <td>Amount Paid</td>
        <td class="text-end">'.number_format($paid,2).'</td>
    </tr>
    <tr>
        <td>Balance</td>
        <td class="text-end">'.number_format($balance,2).'</td>
    </tr>
</table>

<hr>
<div>
<strong>OUR BANKING DETAILS</strong><br>
ACCOUNT NAME: RAMS EXECUTIVE LODGE<br>
ACCOUNT NUMBER: 9100007723188<br>
BANK NAME: STANDARD BANK
</div>

</body>
</html>
';

// =================== GENERATE PDF ===================
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("invoice_{$invoice_number}.pdf", ["Attachment" => true]);
exit;
?>
