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

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

$booking = $conn->query("SELECT * FROM conference_bookings WHERE id=$booking_id")->fetch_assoc();
if(!$booking){ die("<div class='alert alert-danger'>Booking not found</div>"); }


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

// Fetch guest_id from booking
$booking = $conn->query("SELECT * FROM conference_bookings WHERE id=$booking_id")->fetch_assoc();
$guest_id = intval($booking['guest_id'] ?? 0);

// Prevent duplicate invoice
$existing_invoice = $conn->query("SELECT id FROM invoices WHERE guest_id=$guest_id LIMIT 1")->fetch_assoc();
if($existing_invoice){
    die("<div class='alert alert-danger'>Invoice already exists for this guest. <a href='view_invoice.php?invoice_id=".$existing_invoice['id']."'>View Invoice</a></div>");
}




$attendees = intval($booking['attendees']);
$num_days = intval($booking['num_days']);
$total_booking_discount = floatval($booking['total_discount']);

// ===========================
// HANDLE MANUAL DISCOUNT SUBMISSION
// ===========================
if(isset($_POST['apply_manual_discount'])){
    $manual_discount = floatval($_POST['manual_discount'] ?? 0);
    $discount_desc = $conn->real_escape_string($_POST['discount_description'] ?? '');

    if($manual_discount > 0){
        // Update booking table with manual discount info
        $conn->query("UPDATE conference_bookings 
                     SET manual_discount = $manual_discount, manual_discount_desc='$discount_desc' 
                     WHERE id=$booking_id");

        // Update total_booking_discount for display
        $total_booking_discount += $manual_discount;

        // Update $booking array so description is displayed immediately
        $booking['manual_discount'] = $manual_discount;
        $booking['manual_discount_desc'] = $discount_desc;
    }
}




if(isset($_POST['remove_manual_discount'])){
    // Reset manual discount
    $conn->query("UPDATE conference_bookings 
                 SET manual_discount = 0, manual_discount_desc='' 
                 WHERE id=$booking_id");

    // Update total_booking_discount for display
    $total_booking_discount -= floatval($booking['manual_discount']);

    // Update $booking array
    $booking['manual_discount'] = 0;
    $booking['manual_discount_desc'] = '';
}
// ===========================
// 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 (with per-room discounts)
$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']); // apply per-room discount
    $total_accommodation += max($room_total,0);
}

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

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

// ===========================
// VAT and Tourism Levy
// ===========================
$vat_rate = 0.175;   // 17.5% VAT
$levy_rate = 0.01;   // 1% Tourism Levy

$vat = $subtotal * $vat_rate;
$levy = $subtotal * $levy_rate;

// GRAND TOTAL (inclusive of VAT and Levy)
$grand_total = $subtotal + $vat + $levy;

// ===========================


// INVOICE NUMBER
// ===========================
$invoice_number = 'INVCNF-'.date('YmdHis').'-'.$booking_id;

// ===========================
// INSERT INVOICE INTO DATABASE
// ===========================
$guest_id = intval($booking['guest_id'] ?? 0);
$stay_id = intval($booking_id);
$issue_date = date('Y-m-d H:i:s');
$due_date = null; // or calculate based on your rules
$description = "Auto generated from booking #$booking_id";
$status = 'Unpaid';
$created_by = $_SESSION['username'] ?? 'system';
$conf = 2;

$insert_stmt = $conn->prepare("
    INSERT INTO invoices 
    (invoice_number, guest_id, stay_id, issue_date, due_date, total_amount, status, description, created_by, conf)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$insert_stmt->bind_param(
    "siissdsssi",
    $invoice_number,
    $guest_id,
    $stay_id,
    $issue_date,
    $due_date,
    $grand_total,
    $status,
    $description,
    $created_by,
    $conf
);

if($insert_stmt->execute()){
    $invoice_id = $conn->insert_id;
} else {
    echo "<div class='alert alert-danger'>Failed to save invoice: ".$conn->error."</div>";
}
?>

<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{.no-print{display:none;} body{zoom:0.88;} .invoice-box{padding:25px !important;} .cert-title{font-size:24px !important;} .cert-table td{padding:6px !important; font-size:13px !important;} .table td, .table th{padding:6px !important; font-size:13px !important;} .signature-area{margin-top:30px !important;} .watermark{font-size:80px;}}
@page {size: A4 portrait; margin: 8mm;}
</style>

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

    <!-- HEADER -->
    <div class="cert-header">
        <img src="assets/logo.png" style="height:100px;">

        <div class="header-info mt-2">
            <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>

    <!-- MANUAL DISCOUNT FORM -->
    <div class="no-print mt-3 p-3 border rounded" style="background:#f9f9f9;">
        <h5>Apply Manual Discount</h5>
        <form method="post" class="row g-2 align-items-end">
            <div class="col-md-4">
                <label>Discount Description</label>
                <input type="text" name="discount_description" class="form-control" required 
                       placeholder="E.g. Loyalty Discount">
            </div>
            <div class="col-md-3">
                <label>Discount Amount (MWK)</label>
                <input type="number" step="0.01" name="manual_discount" class="form-control" required>
            </div>
            <div class="col-md-2">
                <button type="submit" name="apply_manual_discount" class="btn btn-success">
                    Apply Discount
                </button>
            </div>
        </form>
      <?php if(!empty($booking['manual_discount_desc'])): ?>
    <p class="mt-2 text-success">
        Applied Discount: <?= htmlspecialchars($booking['manual_discount_desc']) ?> - MWK <?= number_format($booking['manual_discount'],2) ?>
    </p>
    
    <!-- REMOVE DISCOUNT BUTTON -->
    <form method="post" class="d-inline">
        <button type="submit" name="remove_manual_discount" class="btn btn-danger btn-sm">
            Remove Discount
        </button>
    </form>
<?php endif; ?>
    </div>

    <!-- DETAILS -->
    <table class="cert-table">
        <tr><td class="cert-label">Client Name</td><td>: <b><?= htmlspecialchars($booking['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,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 
                    <?php if(!empty($booking['manual_discount_desc'])): ?>
                        (<?= htmlspecialchars($booking['manual_discount_desc']) ?>)
                    <?php endif; ?>
                </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,2) ?></th></tr>
        </tbody>
    </table>

    <!-- 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+<?= $booking_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_bookings.php" class="btn btn-secondary">Back</a>

        <?php if(isset($invoice_id) && $invoice_id > 0): ?>
            <a href="receive_pay.php?guest_id=<?= $guest_id ?>&booking_id=<?= $booking_id ?>" 
               class="btn btn-success">
               💰 Receive Payment
            </a>
        <?php else: ?>
            <button class="btn btn-secondary" disabled title="Invoice not yet generated">
               💰 Receive Payment
            </button>
        <?php endif; ?>
    </div>
</div>