<?php

$isFarmerAjax = isset($_POST['farmer_ajax']);

if ($isFarmerAjax) {
    ob_start();
}

require_once("../layouts/members/head.php");

function farmerPageJsonResponse($data, $httpCode = 200)
{
    if (ob_get_length()) {
        ob_clean();
    }

    http_response_code($httpCode);
    header('Content-Type: application/json; charset=UTF-8');
    header('Cache-Control: no-store, no-cache, must-revalidate');

    echo json_encode(
        $data,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );
    exit;
}

/*
|--------------------------------------------------------------------------
| AJAX permission
|--------------------------------------------------------------------------
*/
if ($isFarmerAjax) {

    $allowedUserTypes = [
        'Master Distributor',
        'Distributor',
        'Retailer'
    ];

    if (
        ($user_data['farmer_services'] ?? 'NO') !== 'YES' ||
        !in_array(
            $user_data['usertype'] ?? '',
            $allowedUserTypes,
            true
        )
    ) {
        farmerPageJsonResponse([
            'status'  => 'error',
            'message' => 'Permission denied.'
        ], 403);
    }
}

/*
|--------------------------------------------------------------------------
| Load all state statuses
|--------------------------------------------------------------------------
*/
if (
    $isFarmerAjax &&
    $_POST['farmer_ajax'] === 'load_states'
) {
    $uidNumber = trim((string) ($_POST['uidNumber'] ?? ''));

    if (!preg_match('/^[0-9]{12}$/', $uidNumber)) {
        farmerPageJsonResponse([
            'status'  => 'error',
            'message' => 'Invalid Aadhaar number.'
        ], 422);
    }

    $stateResponse = farmeragri_state_server_api();

    $stateData = is_string($stateResponse)
        ? json_decode($stateResponse, true)
        : null;

    if (!is_array($stateData)) {
        farmerPageJsonResponse([
            'status'  => 'error',
            'message' => 'State response unavailable.'
        ], 502);
    }

    farmerPageJsonResponse($stateData);
}

/*
|--------------------------------------------------------------------------
| Check selected state
|--------------------------------------------------------------------------
*/
if (
    $isFarmerAjax &&
    $_POST['farmer_ajax'] === 'check_state'
) {
    $uidNumber = trim((string) ($_POST['uidNumber'] ?? ''));
    $state     = strtolower(trim((string) ($_POST['state'] ?? '')));

    if (!preg_match('/^[0-9]{12}$/', $uidNumber)) {
        farmerPageJsonResponse([
            'status'  => 'error',
            'message' => 'Invalid Aadhaar number.'
        ], 422);
    }

    if (!preg_match('/^[a-z]{2,3}$/', $state)) {
        farmerPageJsonResponse([
            'status'  => 'error',
            'message' => 'Invalid state.'
        ], 422);
    }

    $stateResponse = farmeragri_state_check_api([
        'uidNumber' => $uidNumber,
        'state'     => $state
    ]);

    $stateData = is_string($stateResponse)
        ? json_decode($stateResponse, true)
        : null;

    if (!is_array($stateData)) {
        farmerPageJsonResponse([
            'status'  => 'error',
            'message' => 'State check response unavailable.'
        ], 502);
    }

    farmerPageJsonResponse($stateData);
}

/*
|--------------------------------------------------------------------------
| Main page
|--------------------------------------------------------------------------
*/
if ($user_data['farmer_services'] == "YES") {

    if (in_array(
        $user_data['usertype'],
        ['Master Distributor', 'Distributor', 'Retailer'],
        true
    )) {

        $response  = null;
        $pdfBase64 = null;
        $pdfSrc    = null;
        ?>

<style>
.certificate-type-card {
    cursor: pointer;
    transition: all .15s ease;
}

.certificate-type-card.active-type {
    background: #f8fbff;
    box-shadow: 0 0 0 2px rgba(0, 123, 255, .18);
}

.state-list-box {
    max-height: 440px;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 4px;
}

.state-item {
    cursor: pointer;
    border: 1px solid #ddd;
    border-left-width: 4px;
    border-radius: 5px;
    padding: 7px 8px;
    margin-bottom: 6px;
    background: #fff;
    transition: all .15s ease;
}

.state-item:hover {
    background: #f7f9fb;
    transform: translateY(-1px);
}

.state-item.selected-state {
    border-color: #007bff;
    background: #eef6ff;
}

.state-green {
    border-left-color: #28a745;
}

.state-yellow {
    border-left-color: #ffc107;
}

.state-red {
    border-left-color: #dc3545;
}

.state-name {
    font-size: 12px;
    line-height: 1.2;
    color: #222;
}

.state-short {
    font-size: 10px;
}

.state-message {
    display: block;
    margin-top: 3px;
    font-size: 10px;
    line-height: 1.2;
    color: #777;
}

.state-mark {
    display: inline-block;
    width: 9px;
    height: 9px;
    border-radius: 50%;
    margin-right: 5px;
}

.mark-green {
    background: #28a745;
}

.mark-yellow {
    background: #ffc107;
}

.mark-red {
    background: #dc3545;
}

.state-loader {
    display: none;
    padding: 20px;
    text-align: center;
}

.state-search {
    height: 38px;
    font-size: 13px;
}

.state-legend {
    font-size: 11px;
}

.farmer-result-box {
    border: 1px solid #ddd;
    border-radius: 5px;
    overflow: hidden;
}

.farmer-result-row {
    display: flex;
    justify-content: space-between;
    gap: 15px;
    padding: 11px 12px;
    border-bottom: 1px solid #eee;
}

.farmer-result-row:last-child {
    border-bottom: 0;
}

.farmer-result-label {
    font-size: 13px;
    font-weight: 600;
    color: #555;
}

.farmer-result-value {
    text-align: right;
    font-size: 13px;
    font-weight: 600;
    word-break: break-word;
}

.no-state-found {
    display: none;
    font-size: 12px;
}
</style>

<div class="row">

    <div class="col-md-4 mb-2">

        <div class="card text-danger">

            <div class="card-header bg-primary text-white py-2">

                <div class="d-flex align-items-center">

                    <span class="mr-auto">
                        <?= htmlspecialchars(file_name()) ?>
                    </span>

                    <button type="button"
                            class="btn btn-dark btn-sm ml-auto"
                            onclick="history.back()">

                        <i class="fas fa-arrow-left"></i>
                        Back
                    </button>

                </div>
            </div>

            <div class="p-3 text-dark">

<?php
if (isset($_POST['submit'])) {

    $uidNumber = trim((string) ($_POST['uidNumber'] ?? ''));

    $certType = strtolower(
        trim((string) ($_POST['cert_type'] ?? 'advance'))
    );

    if (!in_array($certType, ['advance', 'new', 'old'], true)) {
        $certType = 'advance';
    }

    $language = $certType === 'old'
        ? strtolower(trim((string) ($_POST['language_Code'] ?? '')))
        : 'en';

    $validUid = preg_match('/^[0-9]{12}$/', $uidNumber);

    $validLanguage =
        $certType !== 'old' ||
        $language !== '';

    if ($validUid && $validLanguage) {

        $amount      = (float) $user_data['agriFarmer_fee'];
        $old_balance = (float) $user_data['balance'];
        $new_balance = $old_balance - $amount;

        if ($old_balance >= $amount) {

            $order_id = order_txn_id();

            $request = [
                'uidNumber' => $uidNumber,
                'language'  => $language,
                'state'     => strtolower(
                    trim((string) ($_POST['selected_state'] ?? ''))
                )
            ];

            if ($certType === 'advance') {

                $responseApi = farmeragri_api_run3($request);

                $serviceName =
                    "Agri_Farmer_Certificate_Advance_New";

                $description =
                    "Rs.{$amount} Debited for Advance New Farmer Certificate";

            } elseif ($certType === 'old') {

                $responseApi = farmeragri_api_run2($request);

                $serviceName =
                    "Agri_Farmer_Certificate_Old";

                $description =
                    "Rs.{$amount} Debited for Old Farmer Certificate";

            } else {

                $responseApi = farmeragri_api_run($request);

                $serviceName =
                    "Agri_Farmer_Certificate_Normal_New";

                $description =
                    "Rs.{$amount} Debited for Normal New Farmer Certificate";
            }

            $response = is_string($responseApi)
                ? json_decode($responseApi, true)
                : null;

            if (!is_array($response)) {
                $response = [
                    'status' => 'error',
                    'error'  => 'Invalid API response.'
                ];
            }

            $responseStatus = strtolower(
                trim((string) ($response['status'] ?? ''))
            );

            $responseStatusCode =
                (string) ($response['statusCode'] ?? '');

            $apiSuccess =
                $responseStatus === 'success' ||
                $responseStatus === '100' ||
                $responseStatusCode === '100';

            if ($apiSuccess) {

                $pdfBase64 =
                    $response['pdf'] ??
                    $response['data']['pdf'] ??
                    null;

                if (!empty($pdfBase64)) {

                    if (
                        strpos(
                            $pdfBase64,
                            'data:application/pdf;base64,'
                        ) === 0
                    ) {
                        $pdfSrc = $pdfBase64;
                    } else {
                        $pdfSrc =
                            "data:application/pdf;base64," .
                            $pdfBase64;
                    }
                }

                $updateSuccess = db_update(
                    "members",
                    ["balance" => $new_balance],
                    "user_id='{$user_data['user_id']}'"
                );

                if ($updateSuccess) {

                    db_insert("reports", [
                        'site_id'        => $site_data['site_id'],
                        'user_id'        => $user_data['user_id'],
                        'username'       => $user_data['username'],
                        'name'           => $user_data['name'],
                        'operator'       => $user_data['usertype'],
                        'parent_id'      => $user_data['parent_id'],
                        'order_id'       => $order_id,
                        'service'        => $serviceName,
                        'type'           => "Debit",
                        'account_number' => $uidNumber,
                        'app_type'       => $serviceName,
                        'amount'         => $amount,
                        'main_amount'    => $amount,
                        'old_balance'    => $old_balance,
                        'new_balance'    => $new_balance,
                        'txn_id'         => $order_id,
                        'ref_id'         => $uidNumber,
                        'description'    => $description,
                        'date_time'      => current_timestamp(),
                        'status'         => "Success"
                    ]);

                    $farmerName =
                        $response['name'] ??
                        $response['farmerName'] ??
                        $response['data']['name'] ??
                        'N/A';

                    $mobileNo =
                        $response['mobileNumber'] ??
                        $response['data']['mobileNumber'] ??
                        'N/A';

                    $whamessage =
                        "Dear {$user_data['name']},\n" .
                        "Your Farmer Certificate request has been completed.\n\n" .
                        "Type: " . strtoupper($certType) . "\n" .
                        "Name: {$farmerName}\n" .
                        "Mobile: {$mobileNo}\n\n" .
                        "Regards,\n{$site_data['brand']}";

                    send_sms(
                        $user_data['mobile'],
                        $whamessage
                    );

                    awal_alert_msg(
                        "Farmer Certificate Generated Successfully",
                        "success"
                    );

                } else {

                    awal_alert_msg(
                        "Wallet debit failed. Contact support.",
                        "error"
                    );
                }

            } else {

                $errorMessage =
                    $response['error'] ??
                    $response['message'] ??
                    $response['statusMessage'] ??
                    'API Error';

                awal_alert_msg($errorMessage, 'error');
            }

        } else {

            awal_alert_msg(
                "Insufficient Wallet Balance!",
                'error'
            );
        }

    } else {

        if (!$validUid) {

            awal_alert_msg(
                "Please enter a valid 12-digit Aadhaar number.",
                'error'
            );

        } elseif (!$validLanguage) {

            awal_alert_msg(
                "Please select a language.",
                'error'
            );

        } else {

            awal_alert_msg(
                "Please Fill All Valid Details!",
                'error'
            );
        }
    }
}
?>

<form action=""
      method="POST"
      class="row"
      id="farmerForm">

    <div class="col-md-12 mb-3">

        <label>Select Certificate Type</label>

        <div class="row">

            <div class="col-12 mb-2">

                <label id="advanceTypeCard"
                       class="card certificate-type-card active-type p-2 text-center border-success">

                    <input type="radio"
                           name="cert_type"
                           value="advance"
                           checked>

                    <strong>Advance New</strong>
                </label>
            </div>

            <div class="col-6">

                <label id="newTypeCard"
                       class="card certificate-type-card p-2 text-center border-primary">

                    <input type="radio"
                           name="cert_type"
                           value="new">

                    <strong>Normal New</strong>
                </label>
            </div>

            <div class="col-6">

                <label id="oldTypeCard"
                       class="card certificate-type-card p-2 text-center border-danger">

                    <input type="radio"
                           name="cert_type"
                           value="old">

                    <strong>Old</strong>
                </label>
            </div>

        </div>
    </div>

    <div class="col-md-12 mb-3">

        <label>Enter Aadhaar Number</label>

        <input type="text"
               name="uidNumber"
               id="uidNumber"
               placeholder="Enter Aadhaar Number"
               minlength="12"
               maxlength="12"
               inputmode="numeric"
               autocomplete="off"
               class="form-control"
               oninput="this.value=this.value.replace(/[^0-9]/g,'').slice(0,12);"
               required>
    </div>

    <div class="col-md-12 mb-3"
         id="languageSection"
         style="display:none;">

        <label>Select Language</label>

        <select name="language_Code"
                id="language_Code"
                class="form-control">

            <option value="">
                Select Local Language
            </option>
        </select>
    </div>

    <input type="hidden"
           name="selected_state"
           id="selectedState"
           value="">

    <div class="col-md-12 mb-3 d-flex justify-content-between">

        <button type="button"
                class="btn btn-secondary">

            ₹ <?= htmlspecialchars($user_data['agriFarmer_fee']) ?>
        </button>

        <button type="submit"
                name="submit"
                class="btn btn-primary"
                onclick="return validateFarmerForm();">

            Submit
        </button>
    </div>

</form>

            </div>
        </div>
    </div>

    <!-- Right side -->
    <div class="col-md-8 mb-2">

        <div id="advanceResponseCard"
             class="card mb-2">

            <div class="card-header bg-success text-white py-2">

                <div class="d-flex align-items-center">

                    <span class="mr-auto">
                        Advance State Status
                    </span>

                    <button type="button"
                            id="changeStateButton"
                            class="btn btn-light btn-sm"
                            style="display:none;">

                        <i class="fas fa-exchange-alt"></i>
                        Change State
                    </button>

                </div>
            </div>

            <div class="card-body">

                <div id="advanceInstruction"
                     class="alert alert-info">

                    Enter a 12-digit Aadhaar number to check states.
                </div>

                <div id="stateLoader"
                     class="state-loader">

                    <div class="spinner-border text-primary"></div>

                    <div class="mt-2">
                        Checking state servers...
                    </div>
                </div>

                <!-- Search and state list -->
                <div id="stateSelectionSection"
                     style="display:none;">

                    <div class="form-group mb-2">

                        <div class="input-group">

                            <div class="input-group-prepend">

                                <span class="input-group-text">
                                    <i class="fas fa-search"></i>
                                </span>
                            </div>

                            <input type="text"
                                   id="stateSearch"
                                   class="form-control state-search"
                                   placeholder="Search state name or code...">
                        </div>
                    </div>

                    <div class="state-legend mb-2">

                        <span class="mr-3">
                            <span class="state-mark mark-green"></span>
                            Server Available
                        </span>

                        <span class="mr-3">
                            <span class="state-mark mark-yellow"></span>
                            Delay Server
                        </span>

                        <span>
                            <span class="state-mark mark-red"></span>
                            Server Down
                        </span>
                    </div>

                    <div class="state-list-box">

                        <div id="stateList" class="row"></div>

                        <div id="noStateFound"
                             class="alert alert-warning no-state-found">

                            No state found.
                        </div>
                    </div>
                </div>

                <div id="stateCheckLoader"
                     class="state-loader">

                    <div class="spinner-border text-success"></div>

                    <div class="mt-2">
                        Checking farmer details...
                    </div>
                </div>

                <!-- Farmer result -->
                <div id="farmerStatusSection"
                     style="display:none;">

                    <div class="card border-success">

                        <div class="card-header bg-success text-white py-2">
                            Farmer Status
                        </div>

                        <div class="card-body p-2">

                            <div class="farmer-result-box">

                                <div class="farmer-result-row">

                                    <span class="farmer-result-label">
                                        State
                                    </span>

                                    <span class="farmer-result-value"
                                          id="resultState">
                                        -
                                    </span>
                                </div>

                                <div class="farmer-result-row">

                                    <span class="farmer-result-label">
                                        Farmer Name
                                    </span>

                                    <span class="farmer-result-value"
                                          id="resultFarmerName">
                                        -
                                    </span>
                                </div>

                                <div class="farmer-result-row">

                                    <span class="farmer-result-label">
                                        Approval Status
                                    </span>

                                    <span class="farmer-result-value"
                                          id="resultApprovalStatus">
                                        -
                                    </span>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <?php if (!empty($pdfSrc)) { ?>

            <div class="card">

                <div class="card-header bg-success text-white">

                    Farmer Certificate PDF Preview

                    <a href="<?= htmlspecialchars($pdfSrc, ENT_QUOTES, 'UTF-8') ?>"
                       download="Farmer_Certificate.pdf"
                       class="btn btn-warning btn-sm float-right text-dark">

                        <i class="fas fa-download"></i>
                        Download
                    </a>
                </div>

                <div class="card-body p-0">

                    <iframe
                        src="<?= htmlspecialchars($pdfSrc, ENT_QUOTES, 'UTF-8') ?>"
                        width="100%"
                        height="600"
                        style="border:none;">
                    </iframe>
                </div>
            </div>

        <?php } ?>

    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {

    const languages = [
        {code: "hi", name: "Hindi"},
        {code: "bn", name: "Bengali"},
        {code: "ta", name: "Tamil"},
        {code: "te", name: "Telugu"},
        {code: "mr", name: "Marathi"},
        {code: "gu", name: "Gujarati"},
        {code: "kn", name: "Kannada"},
        {code: "ml", name: "Malayalam"},
        {code: "pa", name: "Punjabi"},
        {code: "ur", name: "Urdu"},
        {code: "as", name: "Assamese"},
        {code: "or", name: "Odia"}
    ];

    const languageSelect =
        document.getElementById("language_Code");

    const languageSection =
        document.getElementById("languageSection");

    const uidInput =
        document.getElementById("uidNumber");

    const advanceCard =
        document.getElementById("advanceResponseCard");

    const advanceInstruction =
        document.getElementById("advanceInstruction");

    const stateLoader =
        document.getElementById("stateLoader");

    const stateSelectionSection =
        document.getElementById("stateSelectionSection");

    const stateSearch =
        document.getElementById("stateSearch");

    const stateList =
        document.getElementById("stateList");

    const noStateFound =
        document.getElementById("noStateFound");

    const selectedState =
        document.getElementById("selectedState");

    const stateCheckLoader =
        document.getElementById("stateCheckLoader");

    const farmerStatusSection =
        document.getElementById("farmerStatusSection");

    const changeStateButton =
        document.getElementById("changeStateButton");

    let lastLoadedAadhaar = "";
    let aadhaarTimer = null;

    /*
    |--------------------------------------------------------------------------
    | Languages
    |--------------------------------------------------------------------------
    */
    languages.forEach(function (language) {

        const option = document.createElement("option");

        option.value = language.code;
        option.textContent = language.name;

        languageSelect.appendChild(option);
    });

    /*
    |--------------------------------------------------------------------------
    | Certificate type
    |--------------------------------------------------------------------------
    */
    document.querySelectorAll(
        'input[name="cert_type"]'
    ).forEach(function (radio) {

        radio.addEventListener("change", function () {
            updateCertificateType(this.value);
        });
    });

    function getCertificateType() {

        const selected = document.querySelector(
            'input[name="cert_type"]:checked'
        );

        return selected ? selected.value : "advance";
    }

    function updateCertificateType(type) {

        document.getElementById("advanceTypeCard")
            .classList.remove("active-type");

        document.getElementById("newTypeCard")
            .classList.remove("active-type");

        document.getElementById("oldTypeCard")
            .classList.remove("active-type");

        languageSection.style.display = "none";
        languageSelect.required = false;

        if (type === "advance") {

            document.getElementById("advanceTypeCard")
                .classList.add("active-type");

            advanceCard.style.display = "block";
            languageSelect.value = "";

            if (uidInput.value.length === 12) {
                loadStateServers();
            }

        } else if (type === "old") {

            document.getElementById("oldTypeCard")
                .classList.add("active-type");

            languageSection.style.display = "block";
            languageSelect.required = true;
            advanceCard.style.display = "none";

        } else {

            document.getElementById("newTypeCard")
                .classList.add("active-type");

            languageSelect.value = "";
            advanceCard.style.display = "none";
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Aadhaar input
    |--------------------------------------------------------------------------
    */
    uidInput.addEventListener("input", function () {

        clearTimeout(aadhaarTimer);
        resetStateResponse();

        if (
            getCertificateType() === "advance" &&
            this.value.length === 12
        ) {
            aadhaarTimer = setTimeout(function () {
                loadStateServers();
            }, 400);
        }
    });

    function resetStateResponse() {

        lastLoadedAadhaar = "";
        selectedState.value = "";
        stateList.innerHTML = "";
        stateSearch.value = "";

        stateSelectionSection.style.display = "none";
        farmerStatusSection.style.display = "none";
        changeStateButton.style.display = "none";
        noStateFound.style.display = "none";

        document.getElementById("resultState").textContent = "-";
        document.getElementById("resultFarmerName").textContent = "-";
        document.getElementById("resultApprovalStatus").textContent = "-";

        advanceInstruction.style.display = "block";
        advanceInstruction.textContent =
            "Enter a 12-digit Aadhaar number to check states.";
    }

    /*
    |--------------------------------------------------------------------------
    | Load all states
    |--------------------------------------------------------------------------
    */
    async function loadStateServers() {

        const uidNumber = uidInput.value.trim();

        if (!/^[0-9]{12}$/.test(uidNumber)) {
            return;
        }

        if (
            lastLoadedAadhaar === uidNumber &&
            stateList.children.length > 0
        ) {
            stateSelectionSection.style.display = "block";
            return;
        }

        lastLoadedAadhaar = uidNumber;

        selectedState.value = "";
        stateList.innerHTML = "";

        advanceInstruction.style.display = "none";
        stateSelectionSection.style.display = "none";
        farmerStatusSection.style.display = "none";
        changeStateButton.style.display = "none";
        stateLoader.style.display = "block";

        const formData = new FormData();

        formData.append("farmer_ajax", "load_states");
        formData.append("uidNumber", uidNumber);

        try {

            const apiResponse = await fetch(window.location.href, {
                method: "POST",
                body: formData,
                credentials: "same-origin",
                headers: {
                    "X-Requested-With": "XMLHttpRequest"
                }
            });

            const data = await apiResponse.json();

            stateLoader.style.display = "none";

            if (!data || !data.states) {
                return;
            }

            renderStateList(data.states);
            stateSelectionSection.style.display = "block";
            stateSearch.focus();

        } catch (error) {

            stateLoader.style.display = "none";
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Render states
    |--------------------------------------------------------------------------
    */
    function renderStateList(states) {

        stateList.innerHTML = "";

        Object.keys(states).forEach(function (stateKey) {

            const state = states[stateKey] || {};

            const statusCode =
                String(state.statusCode || "");

            const apiColor =
                String(state.status || "").toLowerCase();

            let color = "yellow";
            let mark = "mark-yellow";

            if (
                apiColor === "green" ||
                statusCode === "100"
            ) {
                color = "green";
                mark = "mark-green";

            } else if (
                apiColor === "red" ||
                ["200", "400", "401", "404", "500"]
                    .includes(statusCode)
            ) {
                color = "red";
                mark = "mark-red";
            }

            const column = document.createElement("div");

            column.className = "col-md-4 col-sm-6 state-column";

            column.dataset.search = (
                String(state.stateName || stateKey) + " " +
                String(state.stateShort || "") + " " +
                String(state.statusMessage || "")
            ).toLowerCase();

            const item = document.createElement("div");

            item.className =
                "state-item state-" + color;

            item.dataset.state = String(
                state.stateShort || stateKey
            ).toLowerCase();

            const heading = document.createElement("div");

            heading.className =
                "d-flex justify-content-between align-items-center";

            const stateName = document.createElement("strong");
            stateName.className = "state-name";

            const colorMark = document.createElement("span");
            colorMark.className = "state-mark " + mark;

            stateName.appendChild(colorMark);

            stateName.appendChild(
                document.createTextNode(
                    state.stateName || stateKey
                )
            );

            const stateShort = document.createElement("span");

            stateShort.className =
                "badge badge-light state-short";

            stateShort.textContent =
                state.stateShort ||
                stateKey.toUpperCase();

            heading.appendChild(stateName);
            heading.appendChild(stateShort);

            const statusMessage = document.createElement("small");

            statusMessage.className = "state-message";

            statusMessage.textContent =
                state.statusMessage || "";

            item.appendChild(heading);
            item.appendChild(statusMessage);

            item.addEventListener("click", function () {

                document.querySelectorAll(".state-item")
                    .forEach(function (card) {
                        card.classList.remove("selected-state");
                    });

                item.classList.add("selected-state");

                selectedState.value =
                    item.dataset.state;

                /*
                 * Hide states immediately after selection
                 */
                stateSelectionSection.style.display = "none";

                checkSelectedState(
                    item.dataset.state
                );
            });

            column.appendChild(item);
            stateList.appendChild(column);
        });
    }

    /*
    |--------------------------------------------------------------------------
    | Search state
    |--------------------------------------------------------------------------
    */
    stateSearch.addEventListener("input", function () {

        const searchValue =
            this.value.trim().toLowerCase();

        let visibleCount = 0;

        document.querySelectorAll(".state-column")
            .forEach(function (column) {

                const matches =
                    column.dataset.search.includes(searchValue);

                column.style.display =
                    matches ? "block" : "none";

                if (matches) {
                    visibleCount++;
                }
            });

        noStateFound.style.display =
            visibleCount === 0 ? "block" : "none";
    });

    /*
    |--------------------------------------------------------------------------
    | Check selected state
    |--------------------------------------------------------------------------
    */
    async function checkSelectedState(state) {

        const uidNumber = uidInput.value.trim();

        if (
            !/^[0-9]{12}$/.test(uidNumber) ||
            !state
        ) {
            return;
        }

        farmerStatusSection.style.display = "none";
        changeStateButton.style.display = "none";
        stateCheckLoader.style.display = "block";

        const formData = new FormData();

        formData.append("farmer_ajax", "check_state");
        formData.append("uidNumber", uidNumber);
        formData.append("state", state);

        try {

            const apiResponse = await fetch(window.location.href, {
                method: "POST",
                body: formData,
                credentials: "same-origin",
                headers: {
                    "X-Requested-With": "XMLHttpRequest"
                }
            });

            const data = await apiResponse.json();

            stateCheckLoader.style.display = "none";

            const success =
                String(data.status || "").toLowerCase() === "success" ||
                String(data.status || "") === "100" ||
                String(data.statusCode || "") === "100";

            if (!success) {

                /*
                 * Reopen state list if selected state fails
                 */
                stateSelectionSection.style.display = "block";
                changeStateButton.style.display = "none";
                return;
            }

            const farmerName =
                data.farmerName ||
                data.name ||
                "-";

            const approvalStatus =
                data.approvalStatus ||
                data.statusMessage ||
                "-";

            document.getElementById("resultState")
                .textContent =
                    data.state || state.toUpperCase();

            document.getElementById("resultFarmerName")
                .textContent = farmerName;

            const approvalElement =
                document.getElementById("resultApprovalStatus");

            approvalElement.textContent = approvalStatus;

            approvalElement.style.color =
                data.approvalStatusColor || "#28a745";

            farmerStatusSection.style.display = "block";
            changeStateButton.style.display = "inline-block";

        } catch (error) {

            stateCheckLoader.style.display = "none";
            stateSelectionSection.style.display = "block";
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Change selected state
    |--------------------------------------------------------------------------
    */
    changeStateButton.addEventListener("click", function () {

        farmerStatusSection.style.display = "none";
        changeStateButton.style.display = "none";
        stateSelectionSection.style.display = "block";

        stateSearch.value = "";

        document.querySelectorAll(".state-column")
            .forEach(function (column) {
                column.style.display = "block";
            });

        noStateFound.style.display = "none";
        stateSearch.focus();
    });

    updateCertificateType("advance");
});

function validateFarmerForm() {

    const uidNumber = document
        .getElementById("uidNumber")
        .value
        .trim();

    const certType = document.querySelector(
        'input[name="cert_type"]:checked'
    ).value;

    const language = document
        .getElementById("language_Code")
        .value;

    if (!/^[0-9]{12}$/.test(uidNumber)) {
        alert("Please enter a valid 12-digit Aadhaar number.");
        return false;
    }

    if (certType === "old" && language === "") {
        alert("Please select language.");
        return false;
    }

    return confirm(
        "Are you sure you want to generate this certificate?"
    );
}
</script>

<?php
    } else {
        require_once("404.php");
    }

} else {

    awal_alert_msg(
        'You Do Not Have Any Farmer Service Active!',
        'info',
        'dashboard'
    );
}

require_once("../layouts/members/foot.php");
?>