<?php //invoice.php
ini_set('display_errors', 1);ini_set('display_startup_errors', 1);error_reporting(E_ALL);

$tenant = (string)($_POST['tenant'] ?? '');
$invNo = (int)($_POST['invNo'] ?? 0);

if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if ($invNo <= 0) {
    echo 'error|Invalid invoice number';
    exit();
}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` WHERE `invNo`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $invNo);
$stmt->execute();
$iv = $stmt->get_result();
$stmt->close();
$cd = mysqli_fetch_array($iv);
if (!$cd) {
    echo 'error|Invoice not found';
    exit();
}
$clientNumber=$cd['client'];

$address = @unserialize($cd['address']);
if (!is_array($address)) {
    $address = [];
}
$totals = explode('|', $cd['totals']);
$invoiceNotes = trim($cd['notes']);
$subDisplay = (string)($totals[0] ?? '0.00');
$vatDisplay = (string)($totals[1] ?? '0.00');
$sub = str_replace(',', '', $subDisplay);
$vat = str_replace(',', '', $vatDisplay);
$com = str_replace(',', '', $cd['commission']);
$gtotal = (float)$sub + (float)$vat;
if($cd['target']!='client' || $cd['target']!='blank'){
$agentGtotal = (float)$sub + (float)$vat;
$brokerGtotal = $agentGtotal - (float)$com;
}
$client_body = '';
$broker_body = '';
$agent_body = '';
$remit_body = '';
$remind_body = '';
$proform_body = '';

function getclientDetailDirect($type, $client)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`='" . $client . "'") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $s = $stmt->get_result();
    $stmt->close();
    $xd = mysqli_fetch_array($s);
    if ($type == "bankName") {
        return $xd['bankName'];
    }
    if ($type == "accountNo") {
        return $xd['accountNo'];
    }
    if ($type == "sortCode") {
        return $xd['sortCode'];
    }
    if ($type == "name") {
        return $xd['company'];
    }
    if ($type == "vatno") {
        return $xd['vatno'];
    }
    if ($type == "web") {
        return $xd['web'];
    }
    if ($type == "name_short") {
        return $xd['company_short'];
    }
    if ($type == "email") {
        return $xd['pri_contact_email'];
    }
    if ($type == "address") {
        return '<tr><td>' . $xd['clientname'] . '</td></tr><tr><td>' . $xd['address1'] . '</td></tr><tr><td>' . $xd['address2'] . '</td></tr><tr><td>' . $xd['town'] . '</td></tr><tr><td>' . $xd['postcode'] . '</td></tr>';
    }
    if ($type == "contact") {
        return '<p>' . $xd['tel'] . '<br>' . $xd['mob'] . '<br>' . $xd['main_email'] . '<br>' . $xd['web'] . '</p>';
    }
}

function getclientDetailsInvoice($type, $client)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`='" . $client . "'") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $s = $stmt->get_result();
    $stmt->close();
    $xd = mysqli_fetch_array($s);
    if ($type == "bankName") {
        return $xd['bankName'];
    }
    if ($type == "accountNo") {
        return $xd['accountNo'];
    }
    if ($type == "sortCode") {
        return $xd['sortCode'];
    }
    if ($type == "name") {
        return $xd['company'];
    }
    if ($type == "vatno") {
        return $xd['vatno'];
    }
    if ($type == "web") {
        return $xd['web'];
    }
    if ($type == "name_short") {
        return $xd['company_short'];
    }
    if ($type == "email") {
        return $xd['pri_contact_email'];
    }
    if ($type == "address") {
        return '<tr><td>' . $xd['billing_name'] . '</td></tr><tr><td>' . $xd['billing1'] . '</td></tr><tr><td>' . $xd['billing2'] . '</td></tr><tr><td>' . $xd['billing_town'] . '</td></tr><tr><td>' . $xd['billing_postcode'] . '</td></tr>';
    }
    if ($type == "contact") {
        return '<p>' . $xd['tel'] . '<br>' . $xd['mob'] . '<br>' . $xd['main_email'] . '<br>' . $xd['web'] . '</p>';
    }
}



function getAgentDetails($type, $agent)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `agents` WHERE `agent_number`='" . $agent . "'") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $s = $stmt->get_result();
    $stmt->close();
    $xd = mysqli_fetch_array($s);
    if ($type == "bankName") {
        return $xd['bankName'];
    }
    if ($type == "accountNo") {
        return $xd['accountNo'];
    }
    if ($type == "sortCode") {
        return $xd['sortCode'];
    }
    if ($type == "name") {
        return $xd['company'];
    }
    if ($type == "vatno") {
        return $xd['vatno'];
    }
    if ($type == "web") {
        return $xd['web'];
    }
    if ($type == "name_short") {
        return $xd['company_short'];
    }
    if ($type == "email") {
        return $xd['pri_contact_email'];
    }
    if ($type == "address") {
        return '<tr><td>' . $xd['agent_name'] . '</td></tr><tr><td>' . $xd['address1'] . '</td></tr><tr><td>' . $xd['address2'] . '</td></tr><tr><td>' . $xd['town'] . '</td></tr><tr><td>' . $xd['post'] . '</td></tr>';
    }
    if ($type == "contact") {
        return '<p>' . $xd['tel'] . '<br>' . $xd['mob'] . '<br>' . $xd['main_email'] . '<br>' . $xd['web'] . '</p>';
    }
}

function getBrokerDetails($type, $broker)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `brokers` WHERE `broker_number`='" . $broker . "'") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $s = $stmt->get_result();
    $stmt->close();
    $xd = mysqli_fetch_array($s);
    if ($type == "bankName") {
        return $xd['bankName'];
    }
    if ($type == "accountNo") {
        return $xd['accountNo'];
    }
    if ($type == "sortCode") {
        return $xd['sortCode'];
    }
    if ($type == "name") {
        return $xd['broker_name'];
    }
    if ($type == "vatno") {
        return $xd['vatno'];
    }
    if ($type == "web") {
        return $xd['web'];
    }
    if ($type == "name_short") {
        return $xd['company_short'];
    }
    if ($type == "email") {
        return $xd['pri_contact_email'];
    }
    if ($type == "address") {
        return '<tr><td>' . $xd['broker_name'] . '</td></tr><tr><td>' . $xd['address1'] . '</td></tr><tr><td>' . $xd['address2'] . '</td></tr><tr><td>' . $xd['town'] . '</td></tr><tr><td>' . $xd['post'] . '</td></tr>';
    }
    if ($type == "contact") {
        return '<p>' . $xd['tel'] . '<br>' . $xd['mob'] . '<br>' . $xd['main_email'] . '<br>' . $xd['web'] . '</p>';
    }
}

function invType($type)
{
    if ($type == "client") {
        return ('<span style="color:#2a3f54">INVOICE</span>');
    }
    if ($type == "agent") {
        return ('<span style="color:#2a3f54">INVOICE</span>');
    }
    if ($type == "remit") {
        return ('<span style="color:#257609">REMITTANCE ADVICE</span>');
    }
    if ($type == "remind") {
        return ('<span style="color:#bd0404">REMINDER</span>');
    }
}

$companyAddress = getCompanyDetails('address');
$parts = [
    trim($address['billing_name'] ?? $address['client_name'] ?? ''),
    trim($address['billing1'] ?? ''),
    trim($address['billing2'] ?? ''),
    trim($address['billing_town'] ?? ''),
    trim($address['billing_county'] ?? ''),
    trim($address['billing_postcode'] ?? '')
];

// remove empty values
$parts = array_filter($parts, fn($v) => $v !== '');

$deliveryAddress = implode('<br>', $parts);

if ($_POST['agentCom'] > 0) {
    $clientAddress = getclientDetailsInvoice('address', $clientNumber);
    $agentAddress = getAgentDetails('address', $cd['agent']);
}
if ($_POST['brokerCom'] > 0) {
    $clientAddress = getclientDetailsInvoice('address', $clientNumber);
    $brokerAddress = getBrokerDetails('address', $cd['broker']);
}


$itemRow = '';

$itemsRaw = $cd['items'];
$items = [];

if (is_array($itemsRaw)) {
    $items = $itemsRaw;
} elseif (is_string($itemsRaw) && $itemsRaw !== '') {
    $decoded = @unserialize($itemsRaw);

    if (is_array($decoded)) {
        $items = $decoded;
    } elseif (is_string($decoded) && $decoded !== '') {
        $jsonDecoded = json_decode($decoded, true);
        if (is_array($jsonDecoded)) {
            $items = $jsonDecoded;
        }
    } else {
        $jsonDecoded = json_decode($itemsRaw, true);
        if (is_array($jsonDecoded)) {
            $items = $jsonDecoded;
        }
    }
}

if (is_array($items) && !empty($items)) {
    foreach ($items as $item) {
        $service  = $item['service'] ?? '';
        $notes    = $item['notes'] ?? '';
        $rate     = $item['rate'] ?? '0.00';
        $quantity = $item['quantity'] ?? '0';

        $rateVal = (float)str_replace(',', '', $rate);
        $qtyVal  = (float)$quantity;
        $net     = $rateVal * $qtyVal;

        $itemRow .= '<tr>
            <td class="p-1 mt-1">' . htmlspecialchars($service) . '</td>
            <td class="p-1 mt-1">' . nl2br(htmlspecialchars($notes)) . '</td>
            <td class="p-1 mt-1">' . htmlspecialchars($rate) . '</td>
            <td class="p-1 mt-1 text-center">' . htmlspecialchars($quantity) . '</td>
            <td class="p-1 mt-1 text-end" style="background-color:#eaeaec!important;">' . number_format($net, 2) . '</td>
        </tr>';
    }
} else {
    $itemRow .= '<tr><td colspan="5" class="text-danger">Unable to load items</td></tr>';
}



switch ($cd['target']) {
    default:
        break;
    case "blank":
        $blankInfo = '
     <div style="width:200px; float:left">
    <table class="invtable table table-borderless">
    <thead><tr><th style="background-color:#2a3f54!important; color:#ffffff!important">To:</th></tr></thead>
    <tbody>
    <tr><td>' . $deliveryAddress . '</td></tr>
    </tbody>
    </table>
    </div>
    
    <div style="width:200px; float:right">
    <table class="invtable table table-borderless" style="text-align:right">
    <tbody>
    <tr><td>' . getCompanyDetails('address') . '</td></tr>
    </tbody>
    </table>
    </div>
   ';
        $addInfo = $blankInfo;
        break;

    case "client":
        $clientInfo = '
    <div style="width:200px; float:left">
    <table class="invtable table table-borderless">
    <thead><tr><th style="background-color:#2a3f54!important; color:#ffffff!important">To:</th></tr></thead>
    <tbody>
    ' . getclientDetailDirect('address', $clientNumber) . '
    </tbody>
    </table>
    </div>
    
    <div style="width:200px; float:left; margin-left: 20px">
    <table class="invtable table table-borderless">
    <thead><tr><th></th></tr></thead>
    <tbody>
    
    </tbody>
    </table>
    </div>
       
    <div style="width:200px; float:right">
    <table class="invtable table table-borderless" style="text-align:right">
    <tbody>
    <tr><td>' . getCompanyDetails('address') . '</td></tr>
    </tbody>
    </table>
    </div>
   ';
        $addInfo = $clientInfo;
        break;

    case "broker":
        $addInfo = '
    <div style="width:200px; float:left">
    <table class="invtable table table-borderless">
    <thead><tr><th style="background-color:#2a3f54!important; color:#ffffff!important">To:</th></tr></thead>
    <tbody>
    ' . $brokerAddress . '
    </tbody>
    </table>
    </div>
    
    <div style="width:200px; float:left; margin-left: 20px">
    <table class="invtable table table-borderless">
    <thead><tr><th style="background-color:#2a3f54!important; color:#ffffff!important">In respect of:</th></tr></thead>
    <tbody>getclientDetailsInvoice
    ' . getclientDetailsInvoice('address', $clientNumber) . '
    </tbody
    ></table>
    </div>
    
    <div style="width:200px; float:right">
    <table class="invtable table table-borderless" style="text-align:right">
    <tbody>
    <tr><td>' . getCompanyDetails('address') . '</td></tr>
    </tbody>
    </table>
    </div>
    ';

        $clientInfo = '
    <div style="width:200px; float:left">
    <table class="invtable table table-borderless">
    <thead><tr><th style="background-color:#2a3f54!important; color:#ffffff!important">To:</th></tr></thead>
    <tbody>
    ' . getclientDetailsInvoice('address', $clientNumber) . '
    </tbody>
    </table>
    </div>
    
    <div style="width:200px; float:left; margin-left: 20px">
    <table class="invtable table table-borderless">
    <thead><tr><th></th></tr></thead>
    <tbody>
    
    </tbody>
    </table>
    </div>
       
    <div style="width:200px; float:right">
    <table class="invtable table table-borderless" style="text-align:right">
    <tbody>
    <tr><td>' . getCompanyDetails('address') . '</td></tr>
    </tbody>
    </table>
    </div>
   ';
        break;

    case "agent":
        $addInfo = '
    <div style="width:200px; float:left">
    <table class="invtable table table-borderless">
    <thead><tr><th style="background-color:#2a3f54!important; color:#ffffff!important">To:</th></tr></thead>
    <tbody>
    ' . $agentAddress . '
    </tbody>
    </table>
    </div>
    
    <div style="width:200px; float:left; margin-left: 20px">
    <table class="invtable table table-borderless">
    <thead><tr><th style="background-color:#2a3f54!important; color:#ffffff!important">In respect of:</th></tr></thead>
    <tbody>
    ' . getclientDetailsInvoice('address', $clientNumber) . '
    </tbody>
    </table>
    </div>
    
    <div style="width:200px; float:right">
    <table class="invtable table table-borderless" style="text-align:right">
    <tbody>
    <tr><td>' . getCompanyDetails('address') . '</td></tr>
    </tbody>
    </table>
    </div>
    ';
        $clientInfo = '
    <div style="width:200px; float:left">
    <table class="invtable table table-borderless">
    <thead><tr><th style="background-color:#2a3f54!important; color:#ffffff!important">To:</th></tr></thead>
    <tbody>
    ' . getclientDetailsInvoice('address', $clientNumber) . '
    </tbody>
    </table>
    </div>
    
    <div style="width:200px; float:left; margin-left: 20px">
    <table class="invtable table table-borderless">
    <thead><tr><th></th></tr></thead>
    <tbody>
    
    </tbody>
    </table>
    </div>
       
    <div style="width:200px; float:right">
    <table class="invtable table table-borderless" style="text-align:right">
    <tbody>
    <tr><td>' . getCompanyDetails('address') . '</td></tr>
    </tbody>
    </table>
    </div>
   ';
        break;
}


$header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
$header .= '</head> 
<body bgcolor="#FFFFFF" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="font-size:10px!important">';
$header .= file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/header_view.php');

// CLIENT ///////////////////
$client_body .= '<link href="../../packages/bootstrap/bootstrap.gen.css" rel="stylesheet">';
$client_body .= file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/style.php');
$client_body .= '<h2 style="text-align:right; color:#2a3f54">INVOICE</h2>';
if ($cd['target'] == "blank") {
    $client_body .= $blankInfo;
}
if ($cd['target'] == "client" || $cd['target'] == "agent" || $cd['target'] == "broker") {
    $client_body .= $clientInfo;
}

$client_body .= '
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<div style="width:30%; float:left"><table class="invtable table table-borderless">
<tr><th>INVOICE NUMBER</th><td>' . sprintf("%06d", $_POST['invNo']) . '</td></tr>
</table></div>
<div style="width:40%; float:right"><table class="invtable table table-borderless" style="text-align:right">
<tr><th>VAT REGISTRATION NUMBER</th><td>' . getCompanyDetails('vatno') . '</td></tr>
</table></div>
<div style="clear:both"></div>
<div style="width:30%; float:left"><table class="invtable table table-borderless">
<tr><th>INVOICE DATE</th><td>' . date('d-m-Y', $cd['date']) . '</td></tr>';

if (!empty($cd['purchase_order'])) {
    $client_body .= '<tr><th>&nbsp;</th></tr><tr><th>PURCHASE ORDER NO</th><td>' . $cd['purchase_order'] . '</td></tr>';
}

$client_body .= '
</table></div>
<div style="width:40%; float:right"><table class="invtable table table-borderless" style="text-align:right">
<tr><th>TERMS</th><td>Stricly 30 days</td></tr>
</table></div>
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<table class="invtable table"><thead>
<tr>
<th style="background-color:#2a3f54!important; color:#ffffff!important">SERVICE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">REFERENCE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">RATE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">QTY</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">NET</th>
</tr></thead>
<tbody>
' . $itemRow . '
<tr><td colspan="5"><hr style="color:#2a3f54"></td></tr>
</tbody>
<tfoot>
<tr><td colspan="3"></td><td>SUBTOTAL</td><td style="background-color:#eaeaec!important;"  align="right">' . $subDisplay . '</td></tr>
<tr><td colspan="3"></td><td>VAT @ 20%</td><td align="right">' . $vatDisplay . '</td></tr>
<tr><td colspan="3"></td><td colspan="2"><hr style="color:#2a3f54"></td></tr>
<tr><td colspan="3"></td><td>TOTAL</td><td style="background-color:#2a3f54; color:#ffffff;" align="right">&pound;' . number_format($gtotal, 2) . '</td></tr>

</tfoot>
</table>
';
if (!empty($invoiceNotes)) {
    $client_body .= '<div style="border: 1px solid #999; background-color: #f9f9f9; padding: 12px; margin-top: 20px; font-size: 13px; color: #444; white-space: pre-line;">
        <strong style="color: #2a3f54;">Notes:</strong><br>' . nl2br(htmlspecialchars($invoiceNotes)) . '
    </div>';
}
//echo "invNo=".$_POST['invNo'];
// BROKER ///////////////////
if ($_POST['brokerCom'] == 1) {
    $broker_body .= '<link href="../../packages/bootstrap/bootstrap.gen.css" rel="stylesheet">';
    $broker_body .= file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/style.php');
    $broker_body .= '<h2 style="text-align:right; color:#2a3f54">INVOICE</h2>';
    $broker_body .= $addInfo;
    $broker_body .= '
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<div style="width:30%; float:left"><table class="invtable table">
<tr><th>INVOICE NUMBER</th><td>' . sprintf("%06d", $_POST['invNo']) . '</td></tr>
</table></div>
<div style="width:40%; float:right"><table class="invtable table" style="text-align:right">
<tr><th>VAT REGISTRATION NUMBER</th><td>' . getCompanyDetails('vatno') . '</td></tr>
</table></div>
<div style="clear:both"></div>
<div style="width:30%; float:left"><table class="invtable table">
<tr><th>INVOICE DATE</th><td>' . date('d-m-Y', $cd['date']) . '</td></tr>';

    if (!empty($cd['purchase_order'])) {
        $broker_body .= '<tr><th>&nbsp;</th></tr><tr><th>PURCHASE ORDER NO</th><td>' . $cd['purchase_order'] . '</td></tr>';
    }

    $broker_body .= '
</table></div>
<div style="width:40%; float:right"><table class="invtable table" style="text-align:right">
<tr><th>TERMS</th><td>Stricly 30 days</td></tr>
</table></div>
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<table class="invtable table"><thead>
<tr>
<th style="background-color:#2a3f54!important; color:#ffffff!important">SERVICE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">REFERENCE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">RATE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">QTY</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">NET</th>
</tr></thead>
<tbody class="mt-1">
' . $itemRow . '
<tr><td colspan="5"><hr style="color:#2a3f54"></td></tr>
</tbody>
<tfoot>
<tr><td colspan="3"></td><td>SUBTOTAL</td><td style="background-color:#eaeaec!important;"  align="right">' . $subDisplay . '</td></tr>
    <tr><td colspan="3"></td><td>VAT @ 20%</td><td align="right">' . $vatDisplay . '</td></tr>
    <tr><td colspan="3"></td><td colspan="2"><hr style="color:#2a3f54"></td></tr>
    
<tr><td colspan="3"></td><td>COMMISSION</td><td style="background-color:#eaeaec!important;"  align="right">' . $com . '</td></tr>
<tr><td colspan="3"></td><td colspan="2"><hr style="color:#2a3f54"></td></tr>
<tr><td colspan="3"></td><td>TOTAL</td><td style="background-color:#2a3f54; color:#ffffff;" align="right">&pound;' . number_format($brokerGtotal, 2) . '</td></tr>

</tfoot>
</table>
';
    if (!empty($invoiceNotes)) {
        $broker_body .= '<div style="border: 1px solid #999; background-color: #f9f9f9; padding: 12px; margin-top: 20px; font-size: 13px; color: #444; white-space: pre-line;">
        <strong style="color: #2a3f54;">Notes:</strong><br>' . nl2br(htmlspecialchars($invoiceNotes)) . '
    </div>';
    }
}
// AGENT ///////////////////
if ($_POST['agentCom'] == 1) {
    $agent_body .= '<link href="../../packages/bootstrap/bootstrap.gen.css" rel="stylesheet">';
    $agent_body .= file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/style.php');
    $agent_body .= '<h2 style="text-align:right; color:#2a3f54">INVOICE</h2>';
    $agent_body .= $addInfo;
    $agent_body .= '
    <div style="clear:both"></div>
    <hr style="color:#2a3f54">
    <div style="width:30%; float:left"><table class="invtable table">
    <tr><th>INVOICE NUMBER</th><td>' . sprintf("%06d", $_POST['invNo']) . '</td></tr>
    </table></div>
    <div style="width:40%; float:right"><table class="invtable table" style="text-align:right">
    <tr><th>VAT REGISTRATION NUMBER</th><td>' . getCompanyDetails('vatno') . '</td></tr>
    </table></div>
    <div style="clear:both"></div>
    <div style="width:30%; float:left"><table class="invtable table">
    <tr><th>INVOICE DATE</th><td>' . date('d-m-Y', $cd['date']) . '</td></tr>';

    if (!empty($cd['purchase_order'])) {
        $agent_body .= '<tr><th>&nbsp;</th></tr><tr><th>PURCHASE ORDER NO</th><td>' . $cd['purchase_order'] . '</td></tr>';
    }

    $agent_body .= '
    </table></div>
    <div style="width:40%; float:right"><table class="invtable table" style="text-align:right">
    <tr><th>TERMS</th><td>Stricly 30 days</td></tr>
    </table></div>
    <div style="clear:both"></div>
    <hr style="color:#2a3f54">
    <table class="invtable table"><thead>
    <tr>
    <th style="background-color:#2a3f54!important; color:#ffffff!important">SERVICE</th>
    <th style="background-color:#2a3f54!important; color:#ffffff!important">REFERENCE</th>
    <th style="background-color:#2a3f54!important; color:#ffffff!important">RATE</th>
    <th style="background-color:#2a3f54!important; color:#ffffff!important">QTY</th>
    <th style="background-color:#2a3f54!important; color:#ffffff!important">NET</th>
    </tr></thead>
    <tbody>
    ' . $itemRow . '
    <tr><td colspan="5"><hr style="color:#2a3f54"></td></tr>
    </tbody>
    <tfoot>
    <tr><td colspan="3"></td><td>SUBTOTAL</td><td style="background-color:#eaeaec!important;"  align="right">' . $subDisplay . '</td></tr>
    <tr><td colspan="3"></td><td>VAT @ 20%</td><td align="right">' . $vatDisplay . '</td></tr>
    <tr><td colspan="3"></td><td colspan="2"><hr style="color:#2a3f54"></td></tr>
    <tr><td colspan="3"></td><td>TOTAL</td><td style="background-color:#2a3f54; color:#ffffff;" align="right">&pound;' . number_format($gtotal, 2) . '</td></tr>

    </tfoot>
    </table>
    ';
    if (!empty($invoiceNotes)) {
        $agent_body .= '<div style="border: 1px solid #999; background-color: #f9f9f9; padding: 12px; margin-top: 20px; font-size: 13px; color: #444; white-space: pre-line;">
        <strong style="color: #2a3f54;">Notes:</strong><br>' . nl2br(htmlspecialchars($invoiceNotes)) . '
    </div>';
    }
}
// REMIT ///////////////////
$remit_body .= '<link href="../../packages/bootstrap/bootstrap.gen.css" rel="stylesheet">';
$remit_body .= file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/style.php');
$remit_body .= '<h2 style="text-align:right; color:#257609">REMITTANCE ADVICE</h2>';
$remit_body .= $addInfo;
$remit_body .= '
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<div style="width:30%; float:left"><table class="invtable table">
<tr><th>INVOICE NUMBER</th><td>' . sprintf("%06d", $_POST['invNo']) . '</td></tr>
</table></div>
<div style="width:40%; float:right"><table class="invtable table" style="text-align:right">
<tr><th>VAT REGISTRATION NUMBER</th><td>' . getCompanyDetails('vatno') . '</td></tr>
</table></div>
<div style="clear:both"></div>
<div style="width:30%; float:left"><table class="invtable table">
<tr><th>INVOICE DATE</th><td>' . date('d-m-Y', $cd['date']) . '</td></tr>
</table></div>
<div style="width:40%; float:right"><table class="invtable table" style="text-align:right">
<tr><th>TERMS</th><td>Stricly 30 days</td></tr>
</table></div>
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<table class="invtable table"><thead>
<tr>
<th style="background-color:#2a3f54!important; color:#ffffff!important">SERVICE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">REFERENCE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">RATE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">QTY</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">NET</th>
</tr></thead>
<tbody class="p-1">
' . $itemRow . '
<tr><td colspan="5"><hr style="color:#2a3f54"></td></tr>
</tbody>
<tfoot>
<tr><td colspan="3"></td><td>SUBTOTAL</td><td style="background-color:#eaeaec!important;"  align="right">' . $subDisplay . '</td></tr>
<tr><td colspan="3"></td><td>VAT</td><td align="right">' . $vatDisplay . '</td></tr>
<tr><td colspan="3"></td><td colspan="2"><hr style="color:#2a3f54"></td></tr>
<tr><td colspan="3"></td><td>TOTAL</td><td style="background-color:#2a3f54; color:#ffffff;" align="right">&pound;' . number_format($gtotal, 2) . '</td></tr>

</tfoot>
</table>
';

// REMIND ///////////////////
$remind_body .= '<link href="../../packages/bootstrap/bootstrap.gen.css" rel="stylesheet">';
$remind_body .= file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/style.php');
$remind_body .= '<h2 style="text-align:right; color:#bd0404">REMINDER</h2>';
$remind_body .= $addInfo;
$remind_body .= '
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<div style="clear:both"></div>
<p>This is a friendly reminder that an invoice is now overdue.</p>
<p>INVOICE DATE: ' . date('d-m-Y', $cd['date']) . '<br>
<p>INVOICE NUMBER: ' . sprintf("%06d", $_POST['invNo']) . '<br>
<p>INVOICE AMOUNT: &pound;' . number_format($gtotal, 2) . '</p>
<br><br>
<p>We understand that oversights happen but would appreciate prompt payment of this amount. Could you please let me know when I can expect payment? If payment has already been made, please disregard this notice.<br><br>
Thanks in advance for your cooperation.</p>
';

// PROFORMA ///////////////////
$proform_body .= '<link href="../../packages/bootstrap/bootstrap.gen.css" rel="stylesheet">';
$proform_body .= file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/style.php');
$proform_body .= '<h2 style="text-align:right; color#3f3f3f">PRO FORMA INVOICE</h2>';
$proform_body .= $addInfo;
$proform_body .= '
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<div style="width:30%; float:left"><table class="invtable table">
<tr><th>REFERENCE NUMBER</th><td>' . sprintf("%06d", $_POST['invNo']) . '</td></tr>
</table></div>
<div style="width:40%; float:right"><table class="invtable table" style="text-align:right">
<tr><th>VAT REGISTRATION NUMBER</th><td>' . getCompanyDetails('vatno') . '</td></tr>
</table></div>
<div style="clear:both"></div>
<div style="width:30%; float:left"><table class="invtable table">
<tr><th>DATE</th><td>' . date('d-m-Y', $cd['date']) . '</td></tr>
</table></div>
<div style="width:40%; float:right"><table class="invtable table" style="text-align:right">
<tr><th>TERMS</th><td>Valid for 30 days</td></tr>
</table></div>
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<table class="invtable table"><thead>
<tr>
<th style="background-color:#2a3f54!important; color:#ffffff!important">SERVICE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">REFERENCE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">RATE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">QTY</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">NET</th>
</tr></thead>
<tbody>
' . $itemRow . '
<tr><td colspan="5"><hr style="color:#2a3f54"></td></tr>
</tbody>
<tfoot>
<tr><td colspan="3"></td><td>SUBTOTAL</td><td style="background-color:#eaeaec!important;"  align="right">' . $subDisplay . '</td></tr>
<tr><td colspan="3"></td><td>VAT @ 20%</td><td align="right">' . $vatDisplay . '</td></tr>
<tr><td colspan="3"></td><td colspan="2"><hr style="color:#2a3f54"></td></tr>
<tr><td colspan="3"></td><td>TOTAL</td><td style="background-color:#2a3f54; color:#ffffff;" align="right">&pound;' . number_format($gtotal, 2) . '</td></tr>

</tfoot>
</table>
';

$footer = file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/footer_view.php');
$footerBroker = file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/footer_broker.php');

//// CONTENT REPLACEMENT
if (file_exists('../../../' . TENANT_URL . '/images/company/logo.jpg')) {
    $header = str_replace('[LGO]', '<img src="../../../' . TENANT_URL . '/images/company/logo.jpg"  height="50px" />', $header);
}
if (file_exists('../../../' . TENANT_URL . '/images/company/afl_1.jpg')) {
    $header = str_replace('[AF1]', '<td><img src="../../../' . TENANT_URL . '/images/company/afl_1.jpg" width="50px" /></td>', $header);
}
if (file_exists('../../../' . TENANT_URL . '/images/company/afl_2.jpg')) {
    $header = str_replace('[AF2]', '<td><img src="../../../' . TENANT_URL . '/images/company/afl_2.jpg" width="50px" /></td>', $header);
}
if (file_exists('../../../' . TENANT_URL . '/images/company/afl_3.jpg')) {
    $header = str_replace('[AF3]', '<td><img src="../../../' . TENANT_URL . '/images/company/afl_3.jpg" width="50px" /></td>', $header);
}
if (file_exists('../../../' . TENANT_URL . '/images/company/afl_4.jpg')) {
    $header = str_replace('[AF4]', '<td><img src="../../../' . TENANT_URL . '/images/company/afl_4.jpg" width="50px" /></td>', $header);
}
if (file_exists('../../../' . TENANT_URL . '/images/company/afl_5.jpg')) {
    $header = str_replace('[AF5]', '<td><img src="../../../' . TENANT_URL . '/images/company/afl_5.jpg" width="50px" /></td>', $header);
}
if (file_exists('../../../' . TENANT_URL . '/images/company/afl_6.jpg')) {
    $header = str_replace('[AF6]', '<td><img src="../../../' . TENANT_URL . '/images/company/afl_6.jpg" width="50px" /></td>', $header);
}

$footer = str_replace('[QCODE]', '<img src="../../invoices/' . $_POST['invNo'] . '.png" width="100px" />', $footer);
$footer = str_replace('[CNAME]', getCompanyDetails('name'), $footer);
$footer = str_replace('[CBANK]', getCompanyDetails('bankName'), $footer);
$footer = str_replace('[CACNO]', getCompanyDetails('accountNo'), $footer);
$footer = str_replace('[CSCODE]', getCompanyDetails('sortCode'), $footer);
$footer = str_replace('[WEB]', getCompanyDetails('web'), $footer);

if (!empty($_POST['brokerCom']) && (int)$_POST['brokerCom'] === 1) {
    $footerBroker = str_replace('[BROKER]', getBrokerDetails('name', $cd['broker']), $footerBroker);
}


require_once '../../packages/mpd/vendor/autoload.php';
//CLIENT
$filestore = "../../../" . TENANT_URL . "/invoices/" . $_POST['invNo'] . "_invoice.pdf";
$mpdf = new \Mpdf\Mpdf([
    'setAutoTopMargin' => 'stretch',
    'setAutoBottomMargin' => 'stretch',
    'mode' => 'utf-8',
    'format' => 'A4',
    'orientation' => 'P'
]);


$mpdf->SetHTMLHeader($header);
$mpdf->WriteHTML($client_body);
if ($_POST['brokerCom'] == 1) {
    $mpdf->SetHTMLFooter($footerBroker);
} else {
    $mpdf->SetHTMLFooter($footer);
}
$mpdf->Output($filestore);
//$mpdf->Output();
// BROKER
if ($_POST['brokerCom'] == 1) {
    $filestore = "../../../" . TENANT_URL . "/invoices/" . $_POST['invNo'] . "_broker.pdf";
    $mpdf = new \Mpdf\Mpdf([
        'setAutoTopMargin' => 'stretch',
        'setAutoBottomMargin' => 'stretch',
        'mode' => 'utf-8',
        'format' => 'A4',
        'orientation' => 'P'
    ]);

    $mpdf->SetHTMLHeader($header);
    $mpdf->WriteHTML($broker_body);
    $mpdf->SetHTMLFooter($footer);
    $mpdf->Output($filestore);
    //$mpdf->Output();
}

// AGENT
if ($_POST['agentCom'] == 1) {
    $filestore = "../../../" . TENANT_URL . "/invoices/" . $_POST['invNo'] . "_agent.pdf";
    $mpdf = new \Mpdf\Mpdf([
        'setAutoTopMargin' => 'stretch',
        'setAutoBottomMargin' => 'stretch',
        'mode' => 'utf-8',
        'format' => 'A4',
        'orientation' => 'P'
    ]);

    $mpdf->SetHTMLHeader($header);
    $mpdf->WriteHTML($agent_body);
    $mpdf->SetHTMLFooter($footer);
    $mpdf->Output($filestore);
    //$mpdf->Output();
}

// REMIT
$filestore = "../../../" . TENANT_URL . "/invoices/" . $_POST['invNo'] . "_remit.pdf";
$mpdf = new \Mpdf\Mpdf([
    'setAutoTopMargin' => 'stretch',
    'setAutoBottomMargin' => 'stretch',
    'mode' => 'utf-8',
    'format' => 'A4',
    'orientation' => 'P'
]);

$mpdf->SetHTMLHeader($header);
$mpdf->WriteHTML($remit_body);
$mpdf->SetHTMLFooter($footer);
$mpdf->Output($filestore);
//$mpdf->Output();

// REMIND
$filestore = "../../../" . TENANT_URL . "/invoices/" . $_POST['invNo'] . "_remind.pdf";
$mpdf = new \Mpdf\Mpdf([
    'setAutoTopMargin' => 'stretch',
    'setAutoBottomMargin' => 'stretch',
    'mode' => 'utf-8',
    'format' => 'A4',
    'orientation' => 'P'
]);

$mpdf->SetHTMLHeader($header);
$mpdf->WriteHTML($remind_body);
$mpdf->SetHTMLFooter($footer);
$mpdf->Output($filestore);
//$mpdf->Output();

// PROFORM
$filestore = "../../../" . TENANT_URL . "/invoices/" . $_POST['invNo'] . "_proforma.pdf";
$mpdf = new \Mpdf\Mpdf([
    'setAutoTopMargin' => 'stretch',
    'setAutoBottomMargin' => 'stretch',
    'mode' => 'utf-8',
    'format' => 'A4',
    'orientation' => 'P'
]);

$mpdf->SetHTMLHeader($header);
$mpdf->WriteHTML($proform_body);
$mpdf->SetHTMLFooter($footer);
$mpdf->Output($filestore);
//$mpdf->Output();


$path = "../../../" . TENANT_URL . "/invoices/";

// Only build if broker copy requested
if (!empty($_POST['brokerCom']) && (int)$_POST['brokerCom'] === 1) {
    $zipFile = $path . $_POST['invNo'] . "_broker.zip";

    // Remove any existing zip to avoid append issues
    if (file_exists($zipFile)) {
        @unlink($zipFile);
    }

    $zip = new ZipArchive();
    $ok = $zip->open($zipFile, ZipArchive::CREATE);
    if ($ok !== TRUE) {
        error_log("Zip open failed ({$ok}) for {$zipFile}");
    } else {
        // Add PDFs using absolute paths, store with simple names
        $files = [
            $path . $_POST['invNo'] . "_broker.pdf"  => $_POST['invNo'] . "_broker.pdf",
            $path . $_POST['invNo'] . "_invoice.pdf" => $_POST['invNo'] . "_invoice.pdf",
        ];
        foreach ($files as $abs => $inZip) {
            if (is_file($abs)) {
                $zip->addFile($abs, $inZip);
            } else {
                error_log("Missing file for zip: {$abs}");
            }
        }
        $zip->close();
    }
}

//$stmt = $GLOBALS['con']->prepare("INSERT INTO `finance_reports` VALUES (NULL,'" . $cd['client'] . "','" . $_POST['invNo'] . "','Invoice','" . urlencode($client_body) . "','" . $_SESSION['user'] . "','" . strtotime('now') . "','" . $cd['date'] . "','','1')");
//$stmt->execute();
//$stmt->close();
