<?php
include $_SERVER['DOCUMENT_ROOT'] . "/WebBuilder/WebApp.class.php";

$db = new DBMain();

// Build invoice content string
$content = '';
$index = 1;
while ($index < $_POST['rows']) {
    if (strlen($_POST['item_desciption_' . $index]) >= 1) {
        $content .= $_POST['item_desciption_' . $index] . ","
                  . $_POST['item_quantity_'   . $index] . ","
                  . $_POST['item_amount_'     . $index] . ","
                  . $_POST['item_discount_'   . $index] . ","
                  . $_POST['item_total_'      . $index] . ";";
    }
    $index++;
}

$record_id = $db->insert("INSERT INTO invoices 
    (`invoice_no`,`invoices_name`,`invoice_content`,`quotes_id`,`total`,`clients_id`,`status`,`date_created`,`date_sent`,`date_due`,`description`) 
    VALUES (
        {$_POST['invoice_no']},
        '{$_POST['invoice_no']}',
        '$content',
        {$_POST['quote_no']},
        {$_POST['total']},
        {$_POST['client_id']},
        '{$_POST['status']}',
        '{$_POST['date']}',
        '',
        '{$_POST['exp_date']}',
        '{$_POST['description']}'
    )");

if (!$record_id) {
    die("ERROR: Could not save invoice. Please go back and try again.");
}

// Invoice saved. Now trigger the download from the TOP window
// (the form runs inside an iframe — downloads fired inside iframes are silently blocked by browsers)
$invoice_no = intval($_POST['invoice_no']);
?>
<script>
    // Create a hidden <a download> link in the TOP window and click it.
    // This breaks out of the iframe so the browser shows the Save As dialog.
    var link = window.top.document.createElement('a');
    link.href  = '/WebApp/download_invoice.php?record_id=<?= $record_id ?>';
    link.download = 'Invoice_<?= $invoice_no ?>.pdf';
    link.style.display = 'none';
    window.top.document.body.appendChild(link);
    link.click();
    window.top.document.body.removeChild(link);
</script>