<?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($msg) {
    echo json_encode(['status' => 'error', 'message' => $msg]);
    exit;
}

$client = isset($_POST['clientnumber']) ? intval($_POST['clientnumber']) : 0;
if (!$client) fail("Missing client number");

$agent  = isset($_POST['agent_number']) ? intval($_POST['agent_number']) : 0;
$broker = isset($_POST['broker_number']) ? intval($_POST['broker_number']) : 0;

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


// Pull billing info based on hierarchy
$billing_name = $billing1 = $billing2 = $billing_town = $billing_county = $billing_postcode = $email = $contract_number = '';
$agent_name = $broker_name = '';

if ($broker > 0) {
    $bq = $con->query("SELECT * FROM brokers WHERE broker_number = $broker LIMIT 1");
    if ($bq && $bq->num_rows) {
        $b = $bq->fetch_assoc();
        $billing_name = $b['billing_name'];
        $billing1 = $b['billing1'];
        $billing2 = $b['billing2'];
        $billing_town = $b['billing_town'];
        $billing_county = $b['billing_county'];
        $billing_postcode = $b['billing_postcode'];
        $email = $b['email'];
        $broker_name = $b['broker_name'];
    }
} elseif ($agent > 0) {
    $aq = $con->query("SELECT * FROM agents WHERE agent_number = $agent LIMIT 1");
    if ($aq && $aq->num_rows) {
        $a = $aq->fetch_assoc();
        $billing_name = $a['billing_name'];
        $billing1 = $a['billing1'];
        $billing2 = $a['billing2'];
        $billing_town = $a['billing_town'];
        $billing_county = $a['billing_county'];
        $billing_postcode = $a['billing_postcode'];
        $email = $a['email'];
        $agent_name = $a['agent_name'];
    }
} else {
    $cq = $con->query("SELECT * FROM clientdetails WHERE clientnumber = $client LIMIT 1");
    if ($cq && $cq->num_rows) {
        $c = $cq->fetch_assoc();
        $billing_name = $c['billing_name'];
        $billing1 = $c['billing1'];
        $billing2 = $c['billing2'];
        $billing_town = $c['billing_town'];
        $billing_county = $c['billing_county'];
        $billing_postcode = $c['billing_postcode'];
        $email = $c['billing_email'];
        $contract_number = $c['contract_number'];
    }
}

$address = [
    'client_name' => $client,
    'billing_name' => $billing_name,
    'billing1' => $billing1,
    'billing2' => $billing2,
    'billing_town' => $billing_town,
    'billing_county' => $billing_county,
    'billing_postcode' => $billing_postcode,
    'email' => $email,
    'contract_number' => $contract_number,
    'agent_number' => $agent,
    'agent_name' => $agent_name,
    'broker_number' => $broker,
    'broker_name' => $broker_name,
    'commission' => $commission
];

$address_serialized = serialize($address);
$items_serialized = isset($_POST['items']) ? serialize($_POST['items']) : '';
$totals = $_POST['totals'] ?? '';
$vatrate = $_POST['vatrate'] ?? '0.2';
$date = isset($_POST['invoice_date']) ? strtotime($_POST['invoice_date']) : time();
$date_due = strtotime('+30 days', $date);
$filter = $_POST['filter'] ?? '';
$target = $_POST['target'] ?? '';

$stmt = $con->prepare("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 (?, ?, ?, ?, ?, ?, ?,?, ?, ?, '', 0, 1, '', 0, ?, '0', ?, ?,?)");

if (!$stmt) fail("Prepare failed: " . $con->error);

$stmt->bind_param(
    'iiisssssisssss',
    $client,
    $agent,
    $broker,
    $address_serialized,
    $items_serialized,
    $totals,
    $invoiceNotes,
    $vatrate,
    $date,
    $date_due,
    $commission,
    $filter,
    $target,
    $purchaseOrder
);

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

$stmt->close();
exit;