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

if (file_exists('../../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
function padInvoiceList6(string $value): string {
    $value = trim($value);
    if ($value === '') return '';

    $parts = array_filter(array_map('trim', explode(',', $value)));
    $out = [];

    foreach ($parts as $p) {
        // keep digits only (handles accidental spaces/text)
        $digits = preg_replace('/\D+/', '', $p);
        if ($digits === '') continue;

        $n = (int)ltrim($digits, '0');
        $out[] = sprintf('%06d', $n);
    }

    return implode(',', $out);
}
switch($_REQUEST['FUNCTION']){
    default:break;


    case "delete_receipt":        
        $sql=mysqli_query($GLOBALS['con'],"DELETE FROM `receipts` WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
       echo "success";
    break;

    case "removeInvoice":
        echo $_REQUEST['invoice'];
        $sql=mysqli_query($GLOBALS['con'],"UPDATE `invoices` SET `date_paid`='0', `status`='1' WHERE `invNo`='".$_REQUEST['invoice']."'")or die(mysqli_error($GLOBALS['con']));
        $sql=mysqli_query($GLOBALS['con'],"DELETE FROM `receipts` WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
        
    break;

    
    case 'register_receipts': 
        // Inputs
        $registered = $_SESSION['user'] ?? 'system';
        $pType      = trim($_REQUEST['pType'] ?? 'in');                  // 'in'
        $payee      = trim($_REQUEST['payee'] ?? '');
        $details    = trim($_REQUEST['details'] ?? '');
        $totals     = trim($_REQUEST['totals'] ?? '0|0');                // "net|vat"
        $vat_flag   = (int)($_REQUEST['vat_flag'] ?? 0);                 // 1 or 0
        $commission = trim($_REQUEST['commission'] ?? '');
        $method     = trim($_REQUEST['method'] ?? 'BACS');               // BACS | Cheque | Card | Other
        $invoice    = trim($_REQUEST['invoice'] ?? '');
        $invoice = padInvoiceList6($invoice);
        $chequeNoIn = trim($_REQUEST['chequeNo'] ?? '');
        $dateUnix   = (int)($_REQUEST['date'] ?? 0);                     // unix ts

        // Persist VAT rate string on receipt (0.2 or 0)
        $vatRateStr = $vat_flag ? '0.2' : '0';

        // Cheque number nullable
        $chequeNo = (strcasecmp($method, 'Cheque') === 0 && $chequeNoIn !== '') ? (int)$chequeNoIn : null;

        // If invoice field has values, mark each one paid
        $firstLinkedInv = ''; // for commission description
        if ($invoice !== '') {
            $pieces = array_filter(array_map('trim', explode(',', $invoice)));
            foreach ($pieces as $piece) {
                if ($piece === '') continue;
                $invNoStr = ltrim($piece, '0');
                if ($invNoStr === '') continue;
                $invNo = (int)$invNoStr;
                if ($invNo <= 0) continue;

                if ($firstLinkedInv === '') $firstLinkedInv = $invNo; // capture first

                $paidTs = $dateUnix ?: time();
                $stmtU = $GLOBALS['con']->prepare("UPDATE `invoices` SET `status`=3, `date_paid`=? WHERE `invNo`=?");
                $stmtU->bind_param('ii', $paidTs, $invNo);
                $stmtU->execute();
                $stmtU->close();
            }
        }

        // Insert receipt
        $sql = "INSERT INTO `receipts`
                (`registered`,`pType`,`payee`,`details`,`vat`,`totals`,`commission`,`method`,`invoice`,`chequeNo`,`date`)
                VALUES (?,?,?,?,?,?,?,?,?,?,?)";
        $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param(
            'ssssssssssi',
            $registered, $pType, $payee, $details, $vatRateStr, $totals, $commission, $method, $invoice, $chequeNo, $dateUnix
        );
        $ok = $stmt->execute();
        if (!$ok) die(mysqli_error($GLOBALS['con']));
        $stmt->close();

        // If commission > 0, record an OUTGOING
        $commissionVal = (float)preg_replace('/[^0-9.]/', '', $commission);
        if ($commissionVal > 0) {
            // Configure VAT handling for commission (default: no VAT on commission)
            $commissionVatOn = false;                // set true to apply VAT to commission
            $commissionRate  = $commissionVatOn ? '0.2' : '0';
            $commissionVat   = $commissionVatOn ? round($commissionVal * 0.2, 2) : 0.00;

            $employee        = (string)$registered;
            $payment_type    = 'Outgoings';
            $code            = 'Commission';
            $type            = 'Commission';
            $descInvLabel    = ($firstLinkedInv !== '' ? str_pad((int)$firstLinkedInv, 6, '0', STR_PAD_LEFT) : 'N/A');
            $desc            = 'Commission payment in respect of invoice ' . $descInvLabel;
            $dateStr         = (string)($dateUnix ?: time()); // schema stores varchar
            $amountStr       = number_format($commissionVal, 2, '.', '');
            $totalsStr       = $amountStr . '|' . number_format($commissionVat, 2, '.', '');
            $vReg            = '';
            $vMileage        = '';
            $vRate           = '';
            $vDetails        = '';
            $payment_method  = $method;
            $chequeNoStr     = $chequeNoIn;          // keep as provided
            $payeeStr        = $payee;

            $sqlEx = "INSERT INTO `expenses`
                (`employee`,`payment_type`,`code`,`type`,`desc`,`date`,`amount`,`vatrate`,`totals`,
                `vReg`,`vMileage`,`vRate`,`vDetails`,`payment_method`,`chequeNo`,`payee`)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            $ex = $GLOBALS['con']->prepare($sqlEx) or die(mysqli_error($GLOBALS['con']));
            $ex->bind_param(
                'ssssssssssssssss',
                $employee, $payment_type, $code, $type, $desc, $dateStr, $amountStr, $commissionRate, $totalsStr,
                $vReg, $vMileage, $vRate, $vDetails, $payment_method, $chequeNoStr, $payeeStr
            );
            $ex->execute();
            $ex->close();
        }

        echo "success";
        exit;
    break;



    
        case "update_receipt":
            // Normalise / sanitise incoming data
            $_REQUEST['details'] = str_replace("'", "&#39;", $_REQUEST['details'] ?? '');

            $id         = isset($_REQUEST['id']) ? (int)$_REQUEST['id'] : 0;
            $ptype      = $_REQUEST['ptype']      ?? '';
            $payee      = $_REQUEST['payee']      ?? '';
            $details    = $_REQUEST['details']    ?? '';
            $vatrate    = $_REQUEST['vatrate']    ?? '0.20';
            $totalsStr  = $_REQUEST['totals']     ?? '0|0'; // "net|vat"
            $commission = $_REQUEST['commission'] ?? '0';
            $method     = $_REQUEST['payment_method'] ?? 'BACS';
            $invoices   = $_REQUEST['invoices']   ?? '';
            $invoices   = padInvoiceList6($invoices);
            $chequeNo   = isset($_REQUEST['chequeNo']) ? (int)$_REQUEST['chequeNo'] : 0;

            // Date comes in as dd-mm-yyyy
            $dateTs = 0;
            if (!empty($_REQUEST['date'])) {
                $dateTs = strtotime($_REQUEST['date']);
                if ($dateTs === false) {
                    $dateTs = 0;
                }
            }

            // Flags / data for optional invoice regeneration
            $invoiceUpdated       = false;
            $updatedInvNo         = 0;
            $updatedInvClient     = 0;
            $updatedInvTarget     = '';
            $updatedInvBrokerCom  = 0;
            $updatedInvAgentCom   = 0;
            $updatedInvBrokerId   = 0;
            $updatedInvAgentId    = 0;

            if ($id > 0) {
                // Update the receipt record
                $stmt = $GLOBALS['con']->prepare("
                    UPDATE `receipts` SET
                        `pType`      = ?,
                        `payee`      = ?,
                        `details`    = ?,
                        `vat`        = ?,
                        `totals`     = ?,
                        `commission` = ?,
                        `method`     = ?,
                        `invoice`    = ?,
                        `chequeNo`   = ?,
                        `date`       = ?
                    WHERE `id` = ?
                ") or die(mysqli_error($GLOBALS['con']));

                $stmt->bind_param(
                    'ssssssssiii',
                    $ptype,
                    $payee,
                    $details,
                    $vatrate,
                    $totalsStr,
                    $commission,
                    $method,
                    $invoices,
                    $chequeNo,
                    $dateTs,
                    $id
                );
                $stmt->execute();
                $stmt->close();

                // Optionally update the linked invoice financials
                if (
                    !empty($_REQUEST['update_invoice']) &&
                    $_REQUEST['update_invoice'] === '1' &&
                    !empty($_REQUEST['invoice_id'])
                ) {
                    $invId = (int)$_REQUEST['invoice_id'];

                    if ($invId > 0) {
                        // Pull everything we need to:
                        // - update net/vat/commission
                        // - know how to regenerate the invoice
                        $stmtInv = $GLOBALS['con']->prepare("
                            SELECT
                                `totals`,
                                `client`,
                                `broker`,
                                `agent`,
                                `target`
                              FROM `invoices`
                             WHERE `invNo` = ?
                             LIMIT 1
                        ") or die(mysqli_error($GLOBALS['con']));
                        $stmtInv->bind_param('i', $invId);
                        $stmtInv->execute();
                        $resInv = $stmtInv->get_result();
                        $invRow = $resInv ? $resInv->fetch_assoc() : null;
                        $stmtInv->close();

                        if ($invRow) {
                            // Invoice totals are stored as: net|vat|... (at least 2 fields)
                            $invTotals = explode('|', (string)$invRow['totals']);
                            $rcpTotals = explode('|', (string)$totalsStr);

                            if (!isset($invTotals[0])) $invTotals[0] = '0';
                            if (!isset($invTotals[1])) $invTotals[1] = '0';

                            if (isset($rcpTotals[0])) $invTotals[0] = $rcpTotals[0]; // net
                            if (isset($rcpTotals[1])) $invTotals[1] = $rcpTotals[1]; // vat

                            $newTotals      = implode('|', $invTotals);
                            $invCommission  = $commission; // keep invoice commission in sync

                            // Update invoice financials
                            $stmtUpd = $GLOBALS['con']->prepare("
                                UPDATE `invoices` SET
                                    `totals`     = ?,
                                    `commission` = ?,
                                    `date_paid` = ?
                                WHERE `invNo` = ?
                            ") or die(mysqli_error($GLOBALS['con']));
                            $stmtUpd->bind_param('ssii', $newTotals, $invCommission, $dateTs, $invId);
                            $stmtUpd->execute();
                            $stmtUpd->close();

                            // Prepare regen metadata
                            $invoiceUpdated      = true;
                            $updatedInvNo        = $invId;
                            $updatedInvClient    = (int)($invRow['client'] ?? 0);
                            $updatedInvBrokerId  = (int)($invRow['broker'] ?? 0);
                            $updatedInvAgentId   = (int)($invRow['agent'] ?? 0);
                            $updatedInvTarget    = (string)($invRow['target'] ?? '');

                            $updatedInvBrokerCom = $updatedInvBrokerId > 0 ? 1 : 0;
                            $updatedInvAgentCom  = $updatedInvAgentId > 0 ? 1 : 0;
                        }
                    }
                }
            }

            $commissionVal = (float)preg_replace('/[^0-9.]/', '', (string)$commission);
$invDescLabel  = ($_REQUEST['invoice_id'] > 0 ? sprintf('%06d', $_REQUEST['invoice_id']) : '');
$commissionDesc = 'Commission payment in respect of invoice ' . $invDescLabel;

// only run this sync if we have an invoice id to anchor the record to
if ($_REQUEST['invoice_id'] > 0 && $invDescLabel !== '') {

    // If commission now zero -> remove any previous commission outgoing for this invoice
    if ($commissionVal <= 0) {
        $stmtDel = $GLOBALS['con']->prepare("
            DELETE FROM `expenses`
             WHERE `payment_type`='Outgoings'
               AND `code`='Commission'
               AND `type`='Commission'
               AND `desc`=?
        ") or die(mysqli_error($GLOBALS['con']));
        $stmtDel->bind_param('s', $commissionDesc);
        $stmtDel->execute();
        $stmtDel->close();

    } else {
        // No VAT on commission (matches register_receipts behaviour)
        $commissionVat   = 0.00;
        $commissionRate  = '0';
        $amountStr       = number_format($commissionVal, 2, '.', '');
        $totalsStr       = $amountStr . '|' . number_format($commissionVat, 2, '.', '');
        $dateStr         = (string)($dateTs ?: time()); // expenses.date is varchar in schema
        $employee        = (string)($_SESSION['user'] ?? 'system');
        $payment_type    = 'Outgoings';
        $code            = 'Commission';
        $type            = 'Commission';
        $vReg            = '';
        $vMileage        = '';
        $vRate           = '';
        $vDetails        = '';
        $payment_method  = $method;
        $chequeNoStr     = (string)$chequeNo; // keep simple; schema is varchar
        $payeeStr        = (string)$payee;

        // 1) Try update existing commission expense entry
        $stmtUpEx = $GLOBALS['con']->prepare("
            UPDATE `expenses` SET
                `employee`        = ?,
                `payee`           = ?,
                `date`            = ?,
                `amount`          = ?,
                `vatrate`         = ?,
                `totals`          = ?,
                `payment_method`  = ?,
                `chequeNo`        = ?
            WHERE `payment_type`='Outgoings'
              AND `code`='Commission'
              AND `type`='Commission'
              AND `desc`=?
            LIMIT 1
        ") or die(mysqli_error($GLOBALS['con']));
        $stmtUpEx->bind_param(
            'sssssssss',
            $employee,
            $payeeStr,
            $dateStr,
            $amountStr,
            $commissionRate,
            $totalsStr,
            $payment_method,
            $chequeNoStr,
            $commissionDesc
        );
        $stmtUpEx->execute();
        $affected = $stmtUpEx->affected_rows;
        $stmtUpEx->close();

        // 2) If nothing updated, insert new commission expense entry
        if ($affected <= 0) {
            $stmtInEx = $GLOBALS['con']->prepare("
                INSERT INTO `expenses`
                    (`employee`,`payment_type`,`code`,`type`,`desc`,`date`,`amount`,`vatrate`,`totals`,
                     `vReg`,`vMileage`,`vRate`,`vDetails`,`payment_method`,`chequeNo`,`payee`)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ") or die(mysqli_error($GLOBALS['con']));
            $stmtInEx->bind_param(
                'ssssssssssssssss',
                $employee,
                $payment_type,
                $code,
                $type,
                $commissionDesc,
                $dateStr,
                $amountStr,
                $commissionRate,
                $totalsStr,
                $vReg,
                $vMileage,
                $vRate,
                $vDetails,
                $payment_method,
                $chequeNoStr,
                $payeeStr
            );
            $stmtInEx->execute();
            $stmtInEx->close();
        }
    }
}

            // Response:
            //  - "success" if only receipt was updated
            //  - "success|invoice_regen|invNo|client|target|brokerCom|agentCom|brokerId|agentId"
            if ($invoiceUpdated && $updatedInvNo > 0) {
                echo 'success|invoice_regen|'
                   . $updatedInvNo . '|'
                   . $updatedInvClient . '|'
                   . $updatedInvTarget . '|'
                   . $updatedInvBrokerCom . '|'
                   . $updatedInvAgentCom . '|'
                   . $updatedInvBrokerId . '|'
                   . $updatedInvAgentId;
            } else {
                echo 'success';
            }
        break;

}