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

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

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

    // ---- Inputs ----
    $employee = trim((string)($_REQUEST['employee'] ?? ''));
    $type     = trim((string)($_REQUEST['type'] ?? ''));
    $details  = trim((string)($_REQUEST['desc'] ?? $_REQUEST['details'] ?? ''));
    $payee    = trim((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());

    // VAT rate normalisation (store original string in DB; compute fraction for maths)
    $vrRaw = (string)($_REQUEST['vatrate'] ?? '0.20');
    $vrNum = (float)str_replace(',', '.', $vrRaw);
    if ($vrNum > 1.01 && $vrNum < 2.01) { $rate = $vrNum - 1.0; }      // 1.20 -> 0.20
    elseif ($vrNum >= 2.01)            { $rate = $vrNum / 100.0; }     // 20   -> 0.20
    else                                { $rate = max(0.0, $vrNum); }  // 0.20 -> 0.20

    $code  = '';              // not used
    $ptCol = 'Expenses';
    $fmt   = fn($n) => number_format((float)$n, 2, '.', '');
    $isMileage = (strcasecmp($type, 'Mileage') === 0);

    // Common prepared statement SQL
    $sql = "INSERT INTO `expenses`
            (`employee`,`payment_type`,`code`,`type`,`desc`,`date`,`amount`,`vatrate`,`totals`,
             `vReg`,`vMileage`,`vRate`,`vDetails`,`payment_method`,`chequeNo`,`payee`)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    if ($isMileage) {
        // --- Mileage: create TWO records (Fuel + Mileage) ---
        $mGross = isset($_REQUEST['returnTotal']) ? (float)$_REQUEST['returnTotal'] : 0.0;
        $mNet   = isset($_REQUEST['returnNet'])   ? (float)$_REQUEST['returnNet']   : 0.0; // fuel net
        $mVat   = isset($_REQUEST['returnVat'])   ? (float)$_REQUEST['returnVat']   : 0.0; // fuel VAT

        if ($mGross <= 0 || $mNet < 0 || $mVat < 0) {
            echo 'error:missing_mileage_totals';
            break;
        }

        // Vehicle audit fields
        $vReg     = trim((string)($_REQUEST['vReg']     ?? ''));
        $vMileage = trim((string)($_REQUEST['vMileage'] ?? ''));
        $vRate    = trim((string)($_REQUEST['vRate']    ?? $_REQUEST['returnRate'] ?? ''));
        $vDetails = $details; // per rule: same as desc

        // Start atomic insert
        $con->begin_transaction();

        // 1) Fuel record (VAT-bearing portion only)
        $fuelType    = 'Fuel';
        $fuelDesc    = 'Fuel element of mileage claim – ' . $details;
        $fuelAmount  = $mNet + $mVat;                    // gross fuel element
        $fuelTotals  = $fmt($mNet) . '|' . $fmt($mVat);  // net|vat

        $stmt = $con->prepare($sql) or die(mysqli_error($con));
        $stmt->bind_param(
            'ssssssssssssssss',
            $employee, $ptCol, $code, $fuelType, $fuelDesc, $dateUnix,
            $fmt($fuelAmount), $vrRaw, $fuelTotals,
            $vReg, $vMileage, $vRate, $vDetails,
            $method, $cheque, $payee
        );
        if (!$stmt->execute()) { $con->rollback(); echo 'error:fuel_insert_failed'; $stmt->close(); break; }
        $stmt->close();

        // 2) Mileage record (full claim reimbursement)
        $mileTotals = $fmt($mNet) . '|' . $fmt($mVat);
        $stmt = $con->prepare($sql) or die(mysqli_error($con));
        $stmt->bind_param(
            'ssssssssssssssss',
            $employee, $ptCol, $code, $type, $details, $dateUnix,
            $fmt($mGross), $vrRaw, $mileTotals,
            $vReg, $vMileage, $vRate, $vDetails,
            $method, $cheque, $payee
        );
        if (!$stmt->execute()) { $con->rollback(); echo 'error:mileage_insert_failed'; $stmt->close(); break; }
        $stmt->close();

        $con->commit();
        echo 'success';
        break;
    }

    // --- Standard expense (single record) ---
    // IMPORTANT: Amount is now treated as GROSS (VAT-inclusive by default)
    $rawAmount = (string)($_REQUEST['amount'] ?? '0');
    $grossIn   = (float)str_replace(',', '', $rawAmount);
    $useVat    = (($_REQUEST['use_vat'] ?? $_REQUEST['vatMode'] ?? 'applyvat') === 'applyvat');

    $net = 0.0; $vat = 0.0; $gross = 0.0;
    if ($useVat) {
        $gross = round($grossIn, 2);
        $div   = 1.0 + (float)$rate;
        if ($div <= 0) { $div = 1.0; }
        $net = round($gross / $div, 2);
        $vat = round($gross - $net, 2);
    } else {
        $gross = round($grossIn, 2);
        $net   = $gross;
        $vat   = 0.00;
    }

    $amountToStore = $fmt($gross);
    $totals        = $fmt($net) . '|' . $fmt($vat);

    // Clear mileage fields
    $vReg = $vMileage = $vRate = $vDetails = '';

    $stmt = $con->prepare($sql) or die(mysqli_error($con));
    $stmt->bind_param(
        'ssssssssssssssss',
        $employee, $ptCol, $code, $type, $details, $dateUnix,
        $amountToStore, $vrRaw, $totals,
        $vReg, $vMileage, $vRate, $vDetails,
        $method, $cheque, $payee
    );
    $stmt->execute();
    $stmt->close();

    echo 'success';
    break;
}


    case "update_expense":
        $id = isset($_REQUEST['id']) ? (int)$_REQUEST['id'] : 0;
        if ($id <= 0) { echo "error:invalid_id"; break; }

        // Block mileage edits
        $chk = mysqli_query($GLOBALS['con'], "SELECT `vMileage` FROM `expenses` WHERE `id`=" . $id . " LIMIT 1");
        $rr  = $chk ? mysqli_fetch_assoc($chk) : null;
        if ($rr && (int)$rr['vMileage'] === 1) { echo "error:mileage_locked"; break; }

        $employee = trim((string)($_REQUEST['employee'] ?? ''));
        $type     = trim((string)($_REQUEST['type'] ?? ''));
        $desc     = trim((string)($_REQUEST['desc'] ?? ''));
        $method   = trim((string)($_REQUEST['payment_method'] ?? 'BACS'));

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

        $net   = isset($_REQUEST['net']) ? (float)$_REQUEST['net'] : 0.0;
        $vat   = isset($_REQUEST['vat']) ? (float)$_REQUEST['vat'] : 0.0;
        $gross = isset($_REQUEST['gross']) ? (float)$_REQUEST['gross'] : ($net + $vat);

        if ($net < 0 || $vat < 0 || $gross < 0) { echo "error:invalid_amounts"; break; }

        $totals = number_format($net, 2, '.', '') . '|' . number_format($vat, 2, '.', '');

        $stmt = $GLOBALS['con']->prepare("UPDATE `expenses` SET `employee`=?, `type`=?, `desc`=?, `date`=?, `amount`=?, `totals`=?, `payment_method`=? WHERE `id`=? LIMIT 1");
        if (!$stmt) { echo "error:prepare_failed"; break; }
        $stmt->bind_param('sssidssi', $employee, $type, $desc, $dateUnix, $gross, $totals, $method, $id);
        $ok = $stmt->execute();
        $stmt->close();

        echo $ok ? "success" : "error:update_failed";
    break;

    case "edit":
        $p=str_replace("'","&#39;",$_REQUEST['payee']);
        $d=str_replace("'","&#39;",$_REQUEST['details']);
        $date=strtotime($_REQUEST['date']);
        $a=$_REQUEST['amount'];
        $v=$_REQUEST['vat'];
        $vr=1.2;
        if($v=="1"){
            $net=($a/$vr);
            $vat=$a-$net;
            $totals=$net."|".$vat;
        }
        if($v=="0"){
            $totals=$a."|0.00";
        }

        if($_REQUEST['type']=="payee"){
        $sql=mysqli_query($GLOBALS['con'],"UPDATE `expenses` SET `payee`='".$p."',`desc`='".$d."', `amount`='".$_REQUEST['amount']."', `totals`='".$totals."', `date`='".$date."' WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
        }
        if($_REQUEST['type']=="employee"){
            $sql=mysqli_query($GLOBALS['con'],"UPDATE `expenses` SET `employee`='".$p."',`desc`='".$d."', `amount`='".$_REQUEST['amount']."', `totals`='".$totals."', `date`='".$date."' WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
            }

            $shouldUpdateInvoice = !empty($_REQUEST['update_invoice']) && $_REQUEST['update_invoice'] === '1';

if ($shouldUpdateInvoice && !empty($_REQUEST['id'])) {
    $expenseId = (int)$_REQUEST['id'];

    // Load the current expense row to confirm it's a commission outgoing and to read the description
    $stmt = $GLOBALS['con']->prepare(
        "SELECT `payment_type`, `code`, `type`, `desc`
         FROM `expenses`
         WHERE `id` = ?"
    );
    if ($stmt) {
        $stmt->bind_param('i', $expenseId);
        if ($stmt->execute()) {
            $res = $stmt->get_result();
            if ($row = $res->fetch_assoc()) {
                $pt    = strtolower($row['payment_type'] ?? '');
                $code  = strtolower($row['code'] ?? '');
                $etype = strtolower($row['type'] ?? '');
                $desc  = $row['desc'] ?? '';

                // Your detection rules:
                // payment_type = Outgoings (or Expenses)
                // code or type = Commission
                // desc contains "Commission payment in respect of invoice 000016"
                if (
                    ($pt === 'outgoings' || $pt === 'expenses') &&
                    ($code === 'commission' || $etype === 'commission') &&
                    preg_match('/invoice\s+(\d{1,10})/i', $desc, $m)
                ) {
                    // Strip leading zeros from "000016" → 16
                    $invPadded = $m[1];
                    $invNo = (int)ltrim($invPadded, '0');

                    if ($invNo > 0) {
                        // Use the edited amount as the new commission value
                        $amountClean = isset($_REQUEST['amount'])
                            ? str_replace(',', '', $_REQUEST['amount'])
                            : '0';

                        $stmt2 = $GLOBALS['con']->prepare(
                            "UPDATE `invoices`
                             SET `commission` = ?
                             WHERE `invNo` = ?"
                        );
                        if ($stmt2) {
                            $stmt2->bind_param('si', $amountClean, $invNo);
                            $stmt2->execute();
                            $stmt2->close();
                        }
                    }
                }
            }
        }
        $stmt->close();
    }
}
        echo $_REQUEST['type'];
    break;

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