<?php
/**
 * download_invoice.php
 *
 * Standalone PDF download endpoint.
 * Called directly by the top window — no iframe, no layout wrapper.
 * Streams the invoice as a PDF file download (Save As dialog).
 */

ob_start();

// main.class.php loads the mPDF autoloader and DBMain — same as invoice.pdf.php
include $_SERVER['DOCUMENT_ROOT'] . "/WebBuilder/main.class.php";

if (!isset($_GET['record_id'])) {
    ob_end_clean();
    die("Missing record_id.");
}

$db = new DBMain();

// Fetch invoice
$invoice_res = $db->exec_query('invoices', ['*'], '', '', '', '', "record_id = " . intval($_GET['record_id']));
$invoice     = $invoice_res->fetch_assoc();

if (!$invoice) {
    ob_end_clean();
    die("Invoice not found.");
}

$invoice_number = $invoice['invoice_no'];
$date_created   = $invoice['date_created'];
$date_due       = $invoice['date_due'];
$description    = $invoice['description'];
$total          = $invoice['total'];

// Build line items
$content_array = explode(';', $invoice['invoice_content']);
$content_table = '';
foreach ($content_array as $line) {
    if (strlen($line) > 2) {
        $info = explode(',', $line);
        $content_table .= "
        <tr>
        <td style='padding-bottom:10px;width:300px;padding-right:20px;'> $info[0] </td>
        <td style='padding-bottom:10px;'> $info[1] </td>
        <td style='padding-bottom:10px;'> R " . number_format($info[2], 2, '.', ',') . " </td>
        <td style='padding-bottom:10px;'> $info[3] </td>
        <td style='padding-bottom:10px;'> R " . number_format($info[4], 2, '.', ',') . " </td>
        </tr>";
    }
}

// Fetch company
$company_res  = $db->exec_query('company', ['*']);
$company_info = $company_res->fetch_assoc();
$company_name    = $company_info['company_name'];
$company_email   = $company_info['email'];
$company_address = $company_info['address'];
$company_phone   = $company_info['phone'];
$bank            = $company_info['bank'];
$acc             = $company_info['acc'];
$branch          = $company_info['branch'];

// Fetch client
$client_res  = $db->exec_query('clients', ['*'], '', '', '', '', "record_id = {$invoice['clients_id']}");
$client      = $client_res->fetch_assoc();
$client_name    = $client['clients_name'];
$client_email   = $client['email'];
$client_address = $client['address'];
$client_phone   = $client['cell'];

// Build HTML (identical to invoice.pdf.php)
$htmlContent = "
    <img class='logo' src='Logo.svg' widht='100%' />
<div class='pdf_header'>
    <h1 class='pdf_heading'>INVOICE</h1>
    <h2 style='margin-top:10px;'>#$invoice_number</h2>
    <h3 style='margin-top:-200px;'>DATE: $date_created</h3>
    <h3 style='margin-top:-200px;'>DUE : $date_due</h3>
    <table class='pdf_info'>
    <tr>
        <td><h2>FROM</h2></td>
        <td><h2>TO</h2></td>
    </tr>
    <tr>
        <td><h4>$company_name</h4></td>
        <td><h4>$client_name</h4></td>
    </tr>
    <tr>
        <td><h4>$company_email</h4></td>
        <td><h4>$client_email</h4></td>
    </tr>
    <tr>
        <td><h4>$company_phone</h4></td>
        <td><h4>$client_phone</h4></td>
    </tr>
    <tr>
        <td><h4>$company_address</h4></td>
        <td><h4>$client_address</h4></td>
    </tr>
    <tr>
        <td><h4>$company_vat</h4></td>
        <td><h4>$client_vat</h4></td>
    </tr>
    </table>
</div>

<hr><div class='description'>$description</div><hr>

<table class='content'>
<tr>
<td style='padding-bottom:10px;width:300px;padding-right:20px;'><b>DESCRIPTION</b></td>
<td style='padding-bottom:10px;'><b>QUANTITY</b></td>
<td style='padding-bottom:10px;'><b>AMOUNT</b></td>
<td style='padding-bottom:10px;'><b>DISCOUNT</b></td>
<td style='padding-bottom:10px;'><b>SUB TOTAL</b></td>
</tr>
$content_table
</table>

<div class='footer'>
<div class='bank_details'>
BANK: <b>$bank</b><br>
ACC: <b>$acc</b><br>
BRANCH: <b>$branch</b><br>
REFERANCE: <b>$invoice_number</b><br>
EMAIL: <b>$company_email</b>
</div>
<div class='total'><h4>TOTAL</h4>
<div class='button'>R " . number_format($total, 2, '.', ',') . "</div></div>
</div>

<div style='margin-top:50px; text-align: center; background-color: #f5f5f5; padding:25px;'>
70% DEPOSID WITH ORDERING 30% WITH COLLECTOIN MUST BE PAID IN FULL IF ORDER IS APPROVED IT WILL TAKE 4 to 6 WEEKS 
FOR DELIVERY PER SCULPTURE.
</div>

<div style='margin-top:50px; text-align: center; background-color: #f5f5f5; padding:25px;'>
<span style='color:red'>NOTICE</span><br><br>
All Orders are subject to acceptance by Pro Art Moldings .
Acceptance of orders is based on the express condition that buyer agrees to all of the terms and conditions 
contained herein. Acceptance of delivery by buyer will constitute buyer's assent to these terms and conditions. These 
terms and conditions represent the complete agreement of the parties, and no terms or conditions in any way 
adding to, modifying, or otherwise changing the provisions stated herein shall be binding upon manufacturer unless 
made in writing, and signed and approved by an officer of manufacturer. No modification of any of these terms will 
be affected by manufacturer's shipment of goods following receipt of buyer's purchase order, shipping request, or 
similar forms containing printed terms and conditions conflicting or inconsistent with the terms herein
</div>

<div style='margin-top:50px; text-align: center; background-color: #f5f5f5; padding:25px;'>
<span style='color:red'>PRICES AND TERMS</span><br><br>
All Pro Art Moldings products are made to order per the specifications of its customers. All orders must be in the 
form of a legally binding purchase order with item name, applicable SKUs, quantity, finish, requested delivery date, 
and pricing. Pro Art Moldings welcomes custom orders and will proceed upon customer approval of samples, 
drawings, pricing, delivery and payment terms.
Prices are subject to change without notice. All product prices are exclusive of other charges and freight charges. All 
prices are FOB shipping point at our workshop in Kiepersol Mpumalanga , South Africa. Product pricing does not 
include shipping, storage, local delivery, cartoning, crating, packing, sales tax, or uncrating. These services may be 
quoted as separate line items. All prices are in South African Rand.
A minimum deposit of fifty percent (50%) of the total purchase price is required to initiate order fulfillment. All 
accounts shall be paid net when invoiced. A service charge of the lesser of 2% per month or the maximum 
permissible rate will be added to all accounts not paid within sixty (60) days from the date of invoice for final balance 
due. Orders must be paid in full, including any applicable or prescribed shipping, handling, crating and packing, 
storage (see \"STORAGE\"), taxes, and service charges prior to shipping
</div>

<div style='margin-top:50px; text-align: center; background-color: #f5f5f5; padding:25px;'>
<span style='color:red'>PRICES AND TERMS</span><br><br>
Orders may not be cancelled after ten (10) business days after deposit is received or purchase order accepted by Pro 
Art Moldings After ten (10) business days, any deposit made by Buyer in connection with an order is nonrefundable 
and may be applied to a future new order within ninety (90) days. Cancellations require prior written approval and 
confirmation from Pro Art Moldings
</div>
";

// Generate PDF
$mpdf = new \Mpdf\Mpdf([
    'margin_top'    => 5,
    'margin_bottom' => 1,
    'margin_left'   => 1,
    'margin_right'  => 1,
]);
$mpdf->Addpage('P');
$stylesheet = file_get_contents('Styles/pdf.css');
$mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);
$mpdf->WriteHTML($htmlContent);

// Clear buffer and stream as download — Save As dialog
$safe_client = preg_replace('/[^A-Za-z0-9]/', '_', $client_name);
$filename    = 'Invoice_' . $invoice_number . '_' . $safe_client . '.pdf';

ob_end_clean();
$mpdf->Output($filename, 'D');
exit();