<?php
// Base + active boosts
$client_id = 0; $base_limit = 0;
if ($r = $con->query("SELECT client_id, surveyor_limit FROM subscription_params LIMIT 1")) {
  if ($row = $r->fetch_assoc()) { $client_id = (int)$row['client_id']; $base_limit = (int)$row['surveyor_limit']; }
}
$boost_qty = 0;
if (isset($admin_con) && $admin_con instanceof mysqli && $client_id > 0) {
  if ($stmt = $admin_con->prepare("SELECT COALESCE(SUM(qty),0) AS q FROM boost_requests WHERE client_id=? AND status='active'")) {
    $stmt->bind_param('i', $client_id);
    $stmt->execute();
    $stmt->bind_result($boost_qty);
    $stmt->fetch();
    $stmt->close();
  }
}
$effective_limit = $base_limit + (int)$boost_qty;

$live = 0;
if ($r = $con->query("SELECT COUNT(*) c FROM surveyor WHERE statuslive=1")) {
  if ($row = $r->fetch_assoc()) $live = (int)$row['c'];
}
$canCreate = ($live < $effective_limit);
// Check active surveyors against the limit
$activeSurveyorsQuery = "SELECT COUNT(*) AS active_surveyors FROM surveyor WHERE statuslive = 1";
$activeSurveyorsResult = mysqli_query($con, $activeSurveyorsQuery);
$activeSurveyorsRow = mysqli_fetch_assoc($activeSurveyorsResult);
$active_surveyors = $activeSurveyorsRow['active_surveyors'];

?>

<!-- Display Message or Form Based on Surveyor Limit -->
<div class="row">
    <?php if (!$canCreate): ?>
    <!-- Show Limit Reached Message -->
    <div class="note note-danger mb-3">
        <p>Surveyor limit reached. Please deactivate an existing surveyor or upgrade your subscription to add more
            surveyors. <button type="button" class="btn btn-secondary btn-sm ms-0" onclick="openBoostRequest()"
                    data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Request a temporary capacity boost">
                <i class="fad fa-rocket-launch"></i> Request Boost
            </button></p>
    </div>
    <div class="row">
        <div class="col-12 text-center"><a href="index.php?t=includes/master&p=surveyor.php&view=list"
                class="btn btn-info"><i class="fad fa-chevron-left"></i> Back to surveyor list</a></div>
    </div>
    <?php else: ?>
    <!-- Show Form if Within Limit -->
    <div class="note note-secondary mb-3">
        <p>Register your new surveyor. <small class="muted">Once all required fields have been added and you click
                "create," you will be taken to the detailed information screen to set up permissions and
                allocations.</small></p>
    </div>
    <form id="surveyorForm" class="form-horizontal">
        <fieldset>
            <div class="row">
                <?php require_once(ROOT_URL . '/forms/elements/surveyor_details.frm'); ?>

                <div class="spacer"></div>
                <input type="hidden" name="FUNCTION" value="insert">
                <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
            </div>
        </fieldset>
        <div class="col-12 text-center">
            <input id="btn_save" class="btn btn-info hidden" type="submit" name="submit" value="Submit" />
        </div>
    </form>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('navBox').innerHTML = `
    <li class="breadcrumb-item"><a href="index.php?t=includes/master&p=surveyor.php&view=list">Surveyors</a>
        <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i>
    </li>
    <li class="breadcrumb-item active">New Surveyor</li>`;
    document.getElementById('footerControls').innerHTML =
        '<button class="btn btn-secondary" onclick="triggerAction(\'btn_save\')">SAVE</button>'

})
document.getElementById('surveyorForm').addEventListener('submit', function(event) {

    event.preventDefault();
    const formData = new FormData(this);
    fetch(ROOT_URL + '/includes/surveyor/surveyor_functions.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(result => {
            result = result.trim();

            if (result === "limit_reached") {
                showResponse('warning',
                    'Surveyor limit reached. Please deactivate an existing surveyor or increase the subscription limit.'
                    );
            } else {
                // Redirect if there's no limit issue and the surveyor was added successfully
                window.location.href = 'index.php?t=includes/master&p=surveyor.php&view=edit&id=' + result;
            }
        })
        .catch(error => {
            showResponse('danger', 'An error occurred while processing your request.');
            console.error('Error:', error);
        });
});

function openBoostRequest() {
    // Inline modal for requesting a boost. The target script will be provided next.
    var dest = encodeURI(ROOT_URL + "/includes/surveyor/boost_request.php?tenant=" + TENANT_URL + "&client_id=<?= (int)$tenant_client_id ?>");
    loadModalContent(dest, "popupBox", "modal-md", 1060, "true", "Request Boost", "cancelBoost", function(){});
}
</script>