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

header('Content-Type: application/json');

$clientnumber = intval($_GET['clientnumber'] ?? 0);

$response = [
    'billing' => '',
    'account' => '',
    'invoicenumber' => '',
    'broker_number' => 0,
    'agent_number' => 0,
    'is_broker' => false,
    'is_agent' => false,
    'commission' => null,
    'has_contract_fee' => false,
    'contract_fee' => 0.00
];

// Get next invoice number padded to 6 digits
$nextQuery = $con->query("SELECT MAX(invNo) AS maxnum FROM invoices");
$next = 1;
if ($nextQuery && $row = $nextQuery->fetch_assoc()) {
    $next = (int)($row['maxnum'] ?? 0) + 1;
}
$response['invoicenumber'] = str_pad($next, 6, "0", STR_PAD_LEFT);

// Load client
$q = $con->query("SELECT * FROM clientdetails WHERE clientnumber = $clientnumber LIMIT 1");
if ($q && $q->num_rows) {
    $client = $q->fetch_assoc();

    // Billing Info
    ob_start();
    echo '<p class="m-2"><strong>Name:</strong> ' . htmlspecialchars((string)($client['billing_name'] ?? '')) . '</p>';
    echo '<p class="m-2"><strong>Billing1:</strong> ' . htmlspecialchars((string)($client['billing1'] ?? '')) . '</p>';
    echo '<p class="m-2"><strong>Billing2:</strong> ' . htmlspecialchars((string)($client['billing2'] ?? '')) . '</p>';
    echo '<p class="m-2"><strong>Town:</strong> ' . htmlspecialchars((string)($client['billing_town'] ?? '')) . '</p>';
    echo '<p class="m-2"><strong>County:</strong> ' . htmlspecialchars((string)($client['billing_county'] ?? '')) . '</p>';
    echo '<p class="m-2"><strong>Postcode:</strong> ' . htmlspecialchars((string)($client['billing_postcode'] ?? '')) . '</p>';
    $response['billing'] = ob_get_clean();

    // Contract fee (SAFE)
    $rawFee = $client['rate_per_hour'] ?? '';
    $feeFloat = is_numeric($rawFee) ? (float)$rawFee : 0.0;
    $response['contract_fee'] = $feeFloat;
    $response['has_contract_fee'] = ($feeFloat > 0);

    // Account Info
    $contract = htmlspecialchars((string)($client['contract_number'] ?? ''));
    $agent = '';
    $broker = '';

    if (!empty($client['agent_number'])) {
        $agent_id = intval($client['agent_number']);
        $aq = $con->query("SELECT agent_name FROM agents WHERE agent_number = $agent_id LIMIT 1");
        if ($aq && $aq->num_rows) {
            $agent = (string)($aq->fetch_assoc()['agent_name'] ?? '');
        }
        $response['agent_number'] = $agent_id;
        $response['is_agent'] = true;
    }

    if (!empty($client['broker_number'])) {
        $broker_id = intval($client['broker_number']);
        $bq = $con->query("SELECT broker_name FROM brokers WHERE broker_number = $broker_id LIMIT 1");
        if ($bq && $bq->num_rows) {
            $broker = (string)($bq->fetch_assoc()['broker_name'] ?? '');
        }
        $response['broker_number'] = $broker_id;
        $response['is_broker'] = true;
    }

    ob_start();
    echo '<p class="m-2"><strong>Contract:</strong> ' . $contract . '</p>';
    echo '<p class="m-2"><strong>Contract Fee:</strong> GBP ' . number_format($feeFloat, 2) . '</p>';

    if ($broker) {
        echo '<p class="m-2"><strong>Broker:</strong> ' . htmlspecialchars($broker) . '</p>';
    } elseif ($agent) {
        echo '<p class="m-2"><strong>Agent:</strong> ' . htmlspecialchars($agent) . '</p>';
    }

    if (!empty($client['term_years'])) {
        echo '<p class="m-2"><strong>Term:</strong> ' . htmlspecialchars((string)$client['term_years']) . ' year(s)</p>';
    }

    if (!empty($client['incepton_date'])) {
        echo '<p class="m-2"><strong>Inception Date:</strong> ' . date('d-m-Y', $client['incepton_date']) . '</p>';
    }

    if (!empty($client['renewal_date'])) {
        echo '<p class="m-2"><strong>Renewal Date:</strong> ' . date('d-m-Y', $client['renewal_date']) . '</p>';
    }

    $countSql = "SELECT COUNT(*) as total FROM itemdetails WHERE clientnumber = ? AND statuslive = 1";
    $countStmt = $con->prepare($countSql);
    $countStmt->bind_param('i', $clientnumber);
    $countStmt->execute();
    $itemCount = $countStmt->get_result()->fetch_assoc()['total'] ?? 0;
    $countStmt->close();

    echo '<p class="m-2"><strong>Active Assets:</strong> ' . intval($itemCount) . '</p>';

    $response['account'] = ob_get_clean();

    // Only attach commission if it's a broker
    if ($response['is_broker'] && isset($client['commission'], $client['comType'])) {
        $comType = (int)$client['comType'];
        $comVal = is_numeric($client['commission']) ? (float)$client['commission'] : 0.0;

        $response['commission'] = [
            'type' => $comType,
            'value' => $comVal,
            'label' => ($comType === 0)
                ? rtrim(rtrim(number_format($comVal, 2), '0'), '.') . '%'
                : 'GBP ' . number_format($comVal, 2)
        ];
    }
}

echo json_encode($response);