<?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');
}


//////////////////////////
/// PAYMENT STATUS     ///
/// 1 - Unpaid         ///
/// 2 - Reminder       ///
/// 3 - Paid           ///
/// 4 - Refund         ///
//////////////////////////

if (!isset($_REQUEST['FUNCTION'])) {
    exit;
}

switch ($_REQUEST['FUNCTION']) {
    default:
        break;

    case 'register_outgoing': {
        $con = $GLOBALS['con'];

        $employee = $_SESSION['user'] ?? '';

        $details = trim((string)($_REQUEST['desc'] ?? $_REQUEST['details'] ?? ''));
        $code    = trim((string)($_REQUEST['code'] ?? ''));
        $typeCol = trim((string)($_REQUEST['type'] ?? ''));
        $payee   = (string)($_REQUEST['payee'] ?? '');
        $ptCol   = trim((string)($_REQUEST['payment_type'] ?? 'Outgoings'));

        $method  = trim((string)($_REQUEST['payment_method'] ?? 'BACS'));
        $cheque  = trim((string)($_REQUEST['chequeNo'] ?? ''));

        // Date -> unix
        $dateStr  = trim((string)($_REQUEST['date'] ?? ''));
        $dt       = DateTime::createFromFormat('d-m-Y', $dateStr);
        $dateUnix = $dt ? (string)$dt->getTimestamp() : (string)(is_numeric($dateStr) ? (int)$dateStr : time());

        $useVat = trim((string)($_REQUEST['use_vat'] ?? 'applyvat'));
        $vr = $_REQUEST['vatrate'] ?? 0;

        // vatrate can be "0.20" or "20" (or blank)
        $vrNum  = is_numeric($vr) ? (float)$vr : 0.0;
        if ($vrNum > 0 && $vrNum < 1.01) {
            $vrNum = $vrNum + 1.0;
        } elseif ($vrNum >= 1.01) {
            $vrNum = 1.0 + ($vrNum / 100.0);
        } else {
            $vrNum = 1.2;
        }

        // Amount is posted as GROSS
        $amount = (float)str_replace(',', '', (string)($_REQUEST['amount'] ?? '0'));
        $totalsRaw = trim((string)($_REQUEST['totals'] ?? '')); // "net|vat" from UI (supports manual VAT override)
        $net = 0.0;
        $vat = 0.0;

        if ($useVat === 'novat') {
            $vat = 0.0;
            $net = $amount;
        } elseif ($totalsRaw !== '' && strpos($totalsRaw, '|') !== false) {
            // Prefer explicit UI totals (covers manual VAT override)
            list($nStr, $vStr) = explode('|', $totalsRaw, 2);
            $net = (float)str_replace(',', '', $nStr);
            $vat = (float)str_replace(',', '', $vStr);
            if ($net < 0) $net = 0.0;
            if ($vat < 0) $vat = 0.0;
        } else {
            // Fallback to calculated VAT from rate
            $net = $amount / $vrNum;
            $vat = $amount - $net;
        }

        $net   = (float)round($net, 10);
        $vat   = (float)round($vat, 10);
        $gross = (float)round($net + $vat, 10);

        $totals    = number_format($net, 2, '.', '') . '|' . number_format($vat, 2, '.', '');
        $amountStr = number_format($gross, 2, '.', '');
        $vrStr     = (string)$vrNum;

        $vReg     = '';
        $vMileage = '';
        $vRate    = '';
        $vDetails = '';

        $sql = "INSERT INTO `expenses`
                (`id`,`employee`,`payee`,`payment_type`,`code`,`type`,`desc`,`date`,`amount`,`vatrate`,`totals`,
                 `vReg`,`vMileage`,`vRate`,`vDetails`,`payment_method`,`chequeNo`)
                VALUES(NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt = $con->prepare($sql) or die(mysqli_error($con));
        $stmt->bind_param(
            'ssssssssssssssss',
            $employee, $payee, $ptCol, $code, $typeCol, $details, $dateUnix,
            $amountStr, $vrStr, $totals,
            $vReg, $vMileage, $vRate, $vDetails, $method, $cheque
        );
        $stmt->execute();
        $stmt->close();

        echo 'success';
        break;
    }

    case 'update_outgoing': {
        $con = $GLOBALS['con'];

        $id = (int)($_REQUEST['id'] ?? 0);
        if ($id <= 0) {
            echo 'Invalid record id';
            break;
        }

        $details = trim((string)($_REQUEST['desc'] ?? $_REQUEST['details'] ?? ''));
        $code    = trim((string)($_REQUEST['code'] ?? ''));
        $typeCol = trim((string)($_REQUEST['type'] ?? ''));
        $payee   = (string)($_REQUEST['payee'] ?? '');
        $method  = trim((string)($_REQUEST['payment_method'] ?? 'BACS'));
        $cheque  = trim((string)($_REQUEST['chequeNo'] ?? ''));

        // Date -> unix
        $dateStr  = trim((string)($_REQUEST['date'] ?? ''));
        $dt       = DateTime::createFromFormat('d-m-Y', $dateStr);
        $dateUnix = $dt ? (string)$dt->getTimestamp() : (string)(is_numeric($dateStr) ? (int)$dateStr : time());

        // Net/VAT handling – same pattern as insert
        $totalsRaw = trim((string)($_REQUEST['totals'] ?? ''));
        $net = 0.0; $vat = 0.0;

        if ($totalsRaw !== '' && strpos($totalsRaw, '|') !== false) {
            list($nStr, $vStr) = explode('|', $totalsRaw, 2);
            $net = (float)str_replace(',', '', $nStr);
            $vat = (float)str_replace(',', '', $vStr);
            if ($net < 0) $net = 0.0;
            if ($vat < 0) $vat = 0.0;
        } else {
            $explicitVat = (float)str_replace(',', '', (string)($_REQUEST['vat'] ?? '0'));
            $explicitAmt = (float)str_replace(',', '', (string)($_REQUEST['amount'] ?? '0'));
            if ($explicitAmt > 0) {
                $vat = max(0.0, $explicitVat);
                $net = max(0.0, $explicitAmt - $vat);
            }
        }

        $gross  = (float)round($net + $vat, 10);
        $totals = number_format($net, 2, '.', '') . '|' . number_format($vat, 2, '.', '');

        $vr      = $_REQUEST['vatrate'] ?? 0;
        $amountStr = number_format($gross, 2, '.', '');
        $vrStr     = is_numeric($vr) ? (string)$vr : trim((string)$vr);

        // Optional: update linked invoice commission amount when requested
        $updateInvoiceFlag = !empty($_REQUEST['update_invoice']) && $_REQUEST['update_invoice'] === '1';

        if ($updateInvoiceFlag) {
            $isCommission = (
                strcasecmp($typeCol, 'Commission') === 0 ||
                strcasecmp($code, 'Commission') === 0
            );

            if ($isCommission && $details !== '') {
                if (preg_match('/invoice\s+(\d{1,10})/i', $details, $m)) {
                    $invPadded = $m[1];
                    $invNo = (int)ltrim($invPadded, '0');

                    if ($invNo > 0) {
                        $stmtInv = $con->prepare("UPDATE `invoices` SET `commission`=? WHERE `invNo`=?");
                        if ($stmtInv) {
                            $stmtInv->bind_param('si', $amountStr, $invNo);
                            $stmtInv->execute();
                            $stmtInv->close();
                        }
                    }
                }
            }
        }

        $sql = "UPDATE `expenses`
                SET `code`=?, `type`=?, `desc`=?, `date`=?, `amount`=?, `vatrate`=?, `totals`=?,
                    `payment_method`=?, `chequeNo`=?, `payee`=?
                WHERE `id`=? AND `payment_type`='Outgoings'";
        $stmt = $con->prepare($sql) or die(mysqli_error($con));
        $stmt->bind_param(
            'ssssssssssi',
            $code,
            $typeCol,
            $details,
            $dateUnix,
            $amountStr,
            $vrStr,
            $totals,
            $method,
            $cheque,
            $payee,
            $id
        );
        $stmt->execute();
        $stmt->close();

        echo 'success';
        break;
        
        
    }
    
    case "delete_outgoing":
         $stmt = $GLOBALS['con']->prepare("DELETE FROM `expenses`  WHERE `id`='" . $_REQUEST['id'] . "'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        echo "success";    
            
        break;
}