<?php
// Buffer ALL output immediately — WebApp.class.php outputs HTML on include.
// We must discard that before sending JSON for AJAX calls.
ob_start();

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']}'
    )");

$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

if ($is_ajax) {
    ob_end_clean(); // discard all HTML output from WebApp.class.php
    header('Content-Type: application/json');
    if ($record_id > 0) {
        echo json_encode(['success' => true, 'record_id' => $record_id]);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Could not save invoice. Please try again.']);
    }
} else {
    // Normal SAVE button — flush the buffered HTML and redirect as before
    ob_end_flush();
    if ($record_id > 0) {
        echo "<script>window.location.href='invoice.pdf.php?record_id=$record_id';</script>";
    } else {
        echo "ENCOUNTERED AN ERROR PLEASE TRY AGAIN";
    }
}