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

$clientnumber = intval($_GET['clientnumber']);
$response = [
    'billing' => '',
    'account' => '',
    'invoicenumber' => '',
    'broker_number' => 0,
    'is_broker' => false,
    'commission' => null
];

// 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'] + 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->num_rows) {
    $client = $q->fetch_assoc();

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

    // Account Info
    $contract = htmlspecialchars($client['contract_number']);
    $fee = number_format($client['rate_per_hour'], 2);
    $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 = $aq->fetch_assoc()['agent_name'];
        }
    }

    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 = $bq->fetch_assoc()['broker_name'];
        }
        $response['broker_number'] = $broker_id;
        $response['is_broker'] = true;
    }

    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 = $aq->fetch_assoc()['agent_name'];
    }
    $response['agent_number'] = $agent_id;
    $response['is_agent'] = 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((float)$fee, 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($client['term_years']) . ' year(s)</p>';
    }

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

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

    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'])) {
        $response['commission'] = [
            'type' => intval($client['comType']),
            'value' => floatval($client['commission']),
            'label' => $client['commission'] . ($client['comType'] == 0 ? '%' : ' GBP')
        ];
    }
}

echo json_encode($response);