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

// ===========================
// 1. Get invoice_id from GET
// ===========================
$invoice_id = intval($_GET['invoice_id'] ?? 0);
if(!$invoice_id){
    die("<div class='alert alert-danger'>Invalid invoice ID.</div>");
}

// ===========================
// 2. Fetch invoice and booking info
// ===========================
$stmt = $conn->prepare("
    SELECT i.*, cb.client_name, cb.attendees, cb.num_days, cb.room_price, cb.total_discount, cb.manual_discount, cb.booking_date, cb.id AS booking_id
    FROM invoices i
    LEFT JOIN conference_bookings cb ON i.stay_id = cb.id
    WHERE i.id = ? 
    LIMIT 1
");
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();

if(!$invoice){
    die("<div class='alert alert-danger'>Invoice not found.</div>");
}

// Extract details
$booking_id = intval($invoice['booking_id']);
$guest_id = intval($invoice['guest_id']);
$invoice_number = $invoice['invoice_number'];
$invoice_status = $invoice['status'];

$attendees = intval($invoice['attendees'] ?? 0);
$num_days = intval($invoice['num_days'] ?? 0);
$total_booking_discount = floatval($invoice['total_discount'] ?? 0);
$manual_discount = floatval($invoice['manual_discount'] ?? 0);
if($manual_discount>0) $total_booking_discount += $manual_discount;

// ===========================
// 3. Handle manual discount update
// ===========================
if(isset($_POST['update_discount']) && $invoice_status != 'Paid'){
    $new_discount = floatval($_POST['manual_discount'] ?? 0);
    $upd_stmt = $conn->prepare("UPDATE conference_bookings SET manual_discount=? WHERE id=?");
    $upd_stmt->bind_param("di", $new_discount, $booking_id);
    if($upd_stmt->execute()){
        echo "<div class='alert alert-success'>Manual discount updated successfully.</div>";
        // Reload page to reflect new totals
        echo "<meta http-equiv='refresh' content='1;url=view_invoice.php?invoice_id=$invoice_id'>";
        exit;
    } else {
        echo "<div class='alert alert-danger'>Failed to update discount: ".$conn->error."</div>";
    }
}

// ===========================
// FETCH TOTALS
// ===========================

// Meals
$total_meals = 0;
$res_stmt = $conn->prepare("
    SELECT cm.price
    FROM conference_booking_resources cbr
    JOIN conference_meals cm ON cbr.resource_id = cm.id
    WHERE cbr.booking_id=? AND cbr.resource_type='FOOD'
");
$res_stmt->bind_param("i", $booking_id);
$res_stmt->execute();
$res_result = $res_stmt->get_result();
while($row = $res_result->fetch_assoc()){
    $total_meals += $row['price'] * $attendees * $num_days;
}

// Refreshments
$total_refreshments = 0;
$res_stmt = $conn->prepare("
    SELECT crf.price
    FROM conference_booking_resources cbr
    JOIN conference_refreshments crf ON cbr.resource_id = crf.id
    WHERE cbr.booking_id=? AND cbr.resource_type='REFRESHMENT'
");
$res_stmt->bind_param("i", $booking_id);
$res_stmt->execute();
$res_result = $res_stmt->get_result();
while($row = $res_result->fetch_assoc()){
    $total_refreshments += $row['price'] * $attendees * $num_days;
}

// Accommodation
$total_accommodation = 0;
$rooms_stmt = $conn->prepare("
    SELECT r.price, cba.discount
    FROM conference_booking_accommodation cba
    JOIN rooms r ON cba.room_id=r.id
    WHERE cba.booking_id=?
");
$rooms_stmt->bind_param("i",$booking_id);
$rooms_stmt->execute();
$rooms_result = $rooms_stmt->get_result();
while($r = $rooms_result->fetch_assoc()){
    $room_total = $r['price'] * $num_days;
    $room_total -= floatval($r['discount']);
    $total_accommodation += max($room_total,0);
}

// Conference Room
$conference_total = $invoice['room_price'] * $num_days;

// ===========================
// CALCULATE SUBTOTAL & GRAND TOTAL
// ===========================
$subtotal = $total_meals + $total_refreshments + $total_accommodation + $conference_total;
$subtotal -= $total_booking_discount;

// VAT & Tourism Levy
$vat_rate = 0.175;
$levy_rate = 0.01;
$vat = $subtotal * $vat_rate;
$levy = $subtotal * $levy_rate;
$grand_total_calc = $subtotal + $vat + $levy;
?>

<style>
.invoice-box{ background:#fff; padding:35px; border-radius:12px; font-size:15px; border:4px solid #0a7f2e; position:relative; font-family:"Segoe UI", Tahoma, Geneva, Verdana, sans-serif;}
.cert-header{text-align:center;}
.cert-title{font-size:30px; font-weight:bold; color:#0a7f2e; margin-top:10px;}
.header-info{display:flex; justify-content:space-between; align-items:flex-start; margin-top:10px; flex-wrap:wrap;}
.header-left{text-align:left; font-size:14px;}
.header-right{text-align:right; font-size:14px;}
.cert-table{width:100%; margin-top:25px;}
.cert-table td{padding:10px; border-bottom:1px dotted #999;}
.cert-label{font-weight:bold; width:250px;}
.signature-area{margin-top:50px;}
.watermark{position:absolute; top:45%; left:25%; font-size:100px; color:rgba(0,128,0,0.08); transform:rotate(-30deg); font-weight:bold;}
@media print {
    body {
        margin: 0;
        padding: 0;
        zoom: 0.80; /* key fix: shrink whole page slightly */
    }

    .no-print {
        display: none !important;
    }

  .invoice-box {
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
}

    .cert-title {
        font-size: 22px !important;
        margin: 5px 0 !important;
    }

    .cert-table td {
        padding: 5px !important;
        font-size: 12px !important;
    }

    .table td, .table th {
        padding: 5px !important;
        font-size: 12px !important;
    }

    h5 {
        font-size: 14px !important;
        margin-top: 10px !important;
    }

    .signature-area {
        margin-top: 15px !important;
    }

    .watermark {
        font-size: 60px !important;
        opacity: 0.05 !important;
    }
}
@page {
    size: A4 portrait;
    margin: 5mm;
}


</style>

<div class="container invoice-box">
    <div class="watermark">INVOICE</div>

    <!-- HEADER -->
    <div class="cert-header">
        <img src="assets/logo.png" style="height:100px;">
      <div class="header-info" style="margin-top:5px;">
            <div class="header-left">
                <strong>Mponela Trading Centre.<br>
                100 Meters from Mount Meru Filling Station<br>
                Along M1 Road Next to St Peters Secondary School</strong><br/>
                <strong>TPIN:30798071</strong>
            </div>
            <div class="header-right">
                <strong>
                0993 899 382<br>
                0883 899 382<br>
                https://ramslodgemw.com<br/>
                ramslodge@gmail.com</strong>
            </div>
        </div>
        <br>
        <div class="cert-title">INVOICE</div>
    </div>

    <!-- DETAILS -->
    <table class="cert-table">
        <tr><td class="cert-label">Client Name</td><td>: <b><?= htmlspecialchars($invoice['client_name']) ?></b></td></tr>
        <tr><td class="cert-label">Function Days</td><td>: <?= $num_days ?></td></tr>
        <tr><td class="cert-label">Attendees</td><td>: <?= $attendees ?></td></tr>
        <tr><td class="cert-label">Invoice Number</td><td>: <?= $invoice_number ?></td></tr>
        <tr><td class="cert-label">Grand Total (MWK)</td><td>: <strong><?= number_format($grand_total_calc,2) ?></strong></td></tr>
    </table>

    <!-- BREAKDOWN -->
    <h5 class="mt-4">Charge Breakdown</h5>
    <table class="table table-bordered">
        <thead class="table-dark">
            <tr><th>Description</th><th>Amount (MWK)</th></tr>
        </thead>
        <tbody>
            <tr><td>Meals</td><td><?= number_format($total_meals,2) ?></td></tr>
            <tr><td>Refreshments</td><td><?= number_format($total_refreshments,2) ?></td></tr>
            <tr><td>Accommodation</td><td><?= number_format($total_accommodation,2) ?></td></tr>
            <tr><td>Conference Room</td><td><?= number_format($conference_total,2) ?></td></tr>

            <?php if($total_booking_discount>0): ?>
            <tr><td>Total Booking Discount</td><td>-<?= number_format($total_booking_discount,2) ?></td></tr>
            <?php endif; ?>

            <tr><th>Subtotal</th><th><?= number_format($subtotal,2) ?></th></tr>
            <tr><td>VAT (17.5%)</td><td><?= number_format($vat,2) ?></td></tr>
            <tr><td>Tourism Levy (1%)</td><td><?= number_format($levy,2) ?></td></tr>
            <tr class="table-primary"><th>Grand Total (MWK)</th><th><?= number_format($grand_total_calc,2) ?></th></tr>
        </tbody>
    </table>

    <!-- MANAGE DISCOUNT -->
    <?php if($invoice_status != 'Paid'): ?>
    <div class="mt-4 mb-3">
        <form method="post" class="d-flex align-items-center">
            <label for="manual_discount" class="me-2"><strong>Manual Discount (MWK):</strong></label>
            <input type="number" step="0.01" name="manual_discount" id="manual_discount" value="<?= $invoice['manual_discount'] ?>" class="form-control me-2" style="width:150px;">
            <button type="submit" name="update_discount" class="btn btn-success">Update Discount</button>
        </form>
    </div>
    <?php endif; ?>

    <!-- BANKING INFO & QR -->
    <div class="row signature-area">
        <div class="col-md-6">
            <strong>OUR BANKING DETAILS</strong><br>
            ACCOUNT NAME: RAMS EXECUTIVE LODGE<br>
            ACCOUNT NUMBER: 9100007723188<br>
            BANK NAME: STANDARD BANK
        </div>
        <div class="col-md-6 text-end">
            <img src="https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=Invoice+<?= $invoice_id ?>"><br>
            <small>Verify by scanning this QR code.</small>
        </div>
    </div>

    <!-- BUTTONS -->
    <div class="no-print mt-4 text-center">
        <button class="btn btn-dark" onclick="window.print()"><i class="fa fa-print"></i> Print</button>
        <a href="conference_invoices.php" class="btn btn-secondary">Back</a>
        <a href="receive_pay.php?guest_id=<?= $guest_id ?>&invoice_id=<?= $invoice_id ?>" class="btn btn-success">💰 Receive Payment</a>
    </div>
</div>

