<?php //ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
// includes/finance/invoices/save_invoice.php
if (file_exists('../../../../' . ($_REQUEST['tenant'] ?? '') . '/config.php')) require_once('../../../../' . $_REQUEST['tenant'] . '/config.php');
if (file_exists('/config.php')) require_once('/config.php');
header('Content-Type: application/json');

function fail($m){ echo json_encode(['status'=>'error','message'=>$m]); exit; }

/* -------- inputs -------- */
$client = (int)($_POST['clientnumber'] ?? 0);
$agent  = (int)($_POST['agent_number'] ?? 0);
$broker = (int)($_POST['broker_number'] ?? 0);

$commission    = isset($_POST['commission']) ? number_format((float)$_POST['commission'], 2, '.', '') : '0.00';
$invoiceNotes  = trim($_POST['invoiceNotes'] ?? '');
$purchaseOrder = trim($_POST['purchaseOrder'] ?? '');

$target = trim($_POST['target'] ?? '');
$filter = trim($_POST['filter'] ?? '');
if ($target === '') $target = ($client > 0 || $agent > 0 || $broker > 0) ? 'client' : 'blank';
if ($filter === '') $filter = ($target === 'blank') ? 'Blank' : 'Contract Renewal';
if ($target !== 'blank' && $client <= 0) fail('Missing client number');

$totals  = (string)($_POST['totals'] ?? '');
if ($totals === '') fail('Missing items or totals');

$vatrate = (float)($_POST['vatrate'] ?? '0.2');
$date     = isset($_POST['date']) ? (int)$_POST['date'] : (isset($_POST['invoice_date']) ? (int)strtotime($_POST['invoice_date']) : time());
$date_due = isset($_POST['date_due']) ? (int)$_POST['date_due'] : (int)strtotime('+30 days', $date);

/* -------- address -------- */
// Prefer posted JSON. For blank invoices build from form fields. Else fallback to DB.
$address_arr = null;

if (!empty($_POST['address'])) {
    $tmp = json_decode($_POST['address'], true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($tmp)) $address_arr = $tmp;
}

if ($address_arr === null && $target === 'blank') {
    $bn  = trim($_POST['billing_name']     ?? '');
    $b1  = trim($_POST['billing1']         ?? '');
    $b2  = trim($_POST['billing2']         ?? '');
    $bt  = trim($_POST['billing_town']     ?? '');
    $bc  = trim($_POST['billing_county']   ?? '');
    $bp  = trim($_POST['billing_postcode'] ?? '');
    $em  = trim($_POST['billing_email']    ?? '');

    $address_arr = [
        'client_name'      => $bn,   // Name becomes client_name for blanks
        'billing_name'     => $bn,
        'billing1'         => $b1,
        'billing2'         => $b2,
        'billing_town'     => $bt,
        'billing_county'   => $bc,
        'billing_postcode' => $bp,
        'email'            => $em,
        'contract_number'  => '',
        'agent_number'     => 0,
        'agent_name'       => '',
        'broker_number'    => 0,
        'broker_name'      => '',
        'commission'       => $commission
    ];
}

if ($address_arr === null) {
    // legacy hierarchy for non-blank
    $bn=$b1=$b2=$bt=$bc=$bp=$em=$cn=''; $an=''; $brn='';
    if ($broker > 0) {
        $q = $con->query("SELECT * FROM brokers WHERE broker_number = {$broker} LIMIT 1");
        if ($q && $q->num_rows){ $r=$q->fetch_assoc();
            $bn=$r['billing_name']; $b1=$r['billing1']; $b2=$r['billing2'];
            $bt=$r['billing_town']; $bc=$r['billing_county']; $bp=$r['billing_postcode'];
            $em=$r['email']; $brn=$r['broker_name'];
        }
    } elseif ($agent > 0) {
        $q = $con->query("SELECT * FROM agents WHERE agent_number = {$agent} LIMIT 1");
        if ($q && $q->num_rows){ $r=$q->fetch_assoc();
            $bn=$r['billing_name']; $b1=$r['billing1']; $b2=$r['billing2'];
            $bt=$r['billing_town']; $bc=$r['billing_county']; $bp=$r['billing_postcode'];
            $em=$r['email']; $an=$r['agent_name'];
        }
    } elseif ($client > 0) {
        $q = $con->query("SELECT * FROM clientdetails WHERE clientnumber = {$client} LIMIT 1");
        if ($q && $q->num_rows){ $r=$q->fetch_assoc();
            $bn=$r['billing_name']; $b1=$r['billing1']; $b2=$r['billing2'];
            $bt=$r['billing_town']; $bc=$r['billing_county']; $bp=$r['billing_postcode'];
            $em=$r['billing_email']; $cn=$r['contract_number'];
        }
    }
    $address_arr = [
        'client_name'      => $client,
        'billing_name'     => $bn,
        'billing1'         => $b1,
        'billing2'         => $b2,
        'billing_town'     => $bt,
        'billing_county'   => $bc,
        'billing_postcode' => $bp,
        'email'            => $em,
        'contract_number'  => $cn,
        'agent_number'     => $agent,
        'agent_name'       => $an,
        'broker_number'    => $broker,
        'broker_name'      => $brn,
        'commission'       => $commission
    ];
}

if ($target === 'blank' && empty($address_arr['client_name'])) {
    $address_arr['client_name'] = $address_arr['billing_name'] ?? '';
}

$address_serialized = serialize($address_arr);

/* -------- items (simple & robust) -------- */
$items_serialized = '';
$items_raw = $_POST['items'] ?? '[]';

if (is_array($items_raw)) {
    $items_serialized = serialize($items_raw);
} elseif (is_string($items_raw)) {
    $items_raw = trim($items_raw);
    // Try JSON
    $dec = json_decode($items_raw, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($dec)) {
        $items_serialized = serialize($dec);
    } else {
        // Try PHP-serialized
        $dec = @unserialize($items_raw);
        if (is_array($dec)) {
            $items_serialized = serialize($dec);
        }
    }
}

if ($items_serialized === '') fail('Missing items or totals');

/* -------- insert -------- */
$sql = "
INSERT INTO invoices (
  client, agent, broker, address, items, totals, notes, vatrate, date, date_due,
  date_paid, sent, status, payment_type, chequeNo, commission, commission_paid, filter, target, purchase_order
) VALUES (
  ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
  NULL, 0, 1, '', 0, ?, '0', ?, ?, ?
)";
$stmt = $con->prepare($sql);
if (!$stmt) fail('Prepare failed: '.$con->error);

/* 14 vars; types must match */
$stmt->bind_param(
    'iiissssdiissss',
    $client,             // i
    $agent,              // i
    $broker,             // i
    $address_serialized, // s
    $items_serialized,   // s
    $totals,             // s
    $invoiceNotes,       // s
    $vatrate,            // d
    $date,               // i
    $date_due,           // i
    $commission,         // s
    $filter,             // s
    $target,             // s
    $purchaseOrder       // s
);

if ($stmt->execute()) {
    echo json_encode(['status'=>'success','invoice_id'=>$stmt->insert_id]);
} else {
    fail('Execution failed: '.$stmt->error);
}

$stmt->close();
exit;