<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');

$fee = $udata['AgriFarmerCard_status_fee']; 
checkServiceStatus($udata, 'AgriFarmerCard_status');

if (isset($_POST['aadhar'])) {

    $aadhar    = trim($_POST['aadhar']);
    $state     = $_POST['state_code'] ?? '';
    $appliedby = $udata['phone'];
    $debit_fee = $udata['balance'] - $fee;

    if ($udata['balance'] >= $fee) {

        $request = ['aadhar' => $aadhar, 'state' => $state];
        $resdata = agri_farmer_card_status_verification_api_run($request);
        $statusCode = $resdata['sampleCode'] ?? '';
        $errorMsg = $resdata['error'] ?? '';

        if ($errorMsg) {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire('Error', '$errorMsg', 'error');
            </script>";
        } elseif ($statusCode === "200") {

            date_default_timezone_set('Asia/Kolkata');
            $timestamp = date("Y-m-d H:i:s");
            $parentPhone = $udata['parent'] ?? null;

            addCommission($tng_conn, $appliedby, $fee, $parentPhone, "Agri Farmer Card Status");
            mysqli_query($tng_conn, "UPDATE users SET balance = balance - $fee WHERE phone='$appliedby'");

            $base64Json = base64_encode(json_encode($resdata, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
            $farmerName = mysqli_real_escape_string($tng_conn, $resdata['farmerName'] ?? 'FARMER');
            
            mysqli_query($tng_conn, "INSERT INTO all_pdf_records
                (service_name, name, username, number, pdf, date)
                VALUES ('agri_farmer_status', '$farmerName', '{$udata['phone']}', '$aadhar', '$base64Json', '$timestamp')");

            mysqli_query($tng_conn, "INSERT INTO wallethistory
                (userid, amount, balance, purpose, status, type)
                VALUES ('$appliedby','$fee','$debit_fee','Agri Farmer Card Status','1','Debit')");

            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: 'Status Generated Successfully',
                    timer: 2000,
                    showConfirmButton: false
                }).then(()=>{ window.location='all_history.php'; });
            </script>";
        }
    } else {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire('Low Balance', 'Please Recharge Wallet', 'error');
            setTimeout(()=>{ window.location='wallet.php'; },1500);
        </script>";
    }
}
?>

<style>
.card-shine {
    border-radius: 20px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    transition: .3s;
    border: none;
}
.card-shine:hover {
    transform: translateY(-3px);
    box-shadow: 0 18px 40px rgba(0,0,0,0.15);
}
.container-center {
    min-height: 85vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
}
.form-label {
    font-weight: 600;
    font-size: 13px;
    margin-bottom: 6px;
    color: #333;
}
.single-line {
    width: 100%;
    height: 1px;
    background: linear-gradient(90deg, transparent, #e2e8f0, #e2e8f0, #e2e8f0, transparent);
    margin: 20px 0;
}
</style>

<div class="content-wrap">
<div class="main">
<div class="page-wrapper">
<div class="container-center">
<div class="page-content w-100 d-flex justify-content-center">

<div class="col-lg-5 col-md-7 col-sm-10">
<div class="card card-shine">
<div class="card-body p-4">

<a href="javascript:history.back()" class="btn btn-light mb-4 w-100 py-2" style="border-radius: 12px;">
    ← Go Back
</a>

<div class="text-center mb-4">
    <h5 class="fw-bold mb-1" style="color: #1e293b;">🌾 Agri Farmer Card Status</h5>
    <p class="text-muted small">Check Farmer Card Status (All States)</p>
</div>

<form method="POST" id="statusForm">

<div class="mb-3">
    <label class="form-label">AADHAAR NUMBER *</label>
    <input type="text" name="aadhar" id="aadhar" class="form-control"
           placeholder="Enter 12-digit Aadhaar Number" maxlength="12"
           style="border-radius: 12px; padding: 12px;" 
           onkeyup="this.value = this.value.replace(/[^0-9]/g, '');" required>
    <small class="text-muted">Example: 123456789012</small>
</div>

<div class="mb-3">
    <label class="form-label">SELECT STATE *</label>
    <select name="state_code" id="state_code" class="form-select" style="border-radius: 12px; padding: 12px;" required>
        <option value="">Select State / UT</option>

        <option value="an">Andaman and Nicobar Islands</option>
        <option value="ap">Andhra Pradesh</option>
        <option value="ar">Arunachal Pradesh</option>
        <option value="as">Assam</option>
        <option value="br">Bihar</option>
        <option value="ch">Chandigarh</option>
        <option value="ct">Chhattisgarh</option>
        <option value="dn">Dadra and Nagar Haveli and Daman and Diu</option>
        <option value="dl">Delhi</option>
        <option value="ga">Goa</option>
        <option value="gj">Gujarat</option>
        <option value="hr">Haryana</option>
        <option value="hp">Himachal Pradesh</option>
        <option value="jk">Jammu and Kashmir</option>
        <option value="jh">Jharkhand</option>
        <option value="ka">Karnataka</option>
        <option value="kl">Kerala</option>
        <option value="la">Ladakh</option>
        <option value="ld">Lakshadweep</option>
        <option value="mp">Madhya Pradesh</option>
        <option value="mh">Maharashtra</option>
        <option value="mn">Manipur</option>
        <option value="ml">Meghalaya</option>
        <option value="mz">Mizoram</option>
        <option value="nl">Nagaland</option>
        <option value="or">Odisha</option>
        <option value="py">Puducherry</option>
        <option value="pb">Punjab</option>
        <option value="rj">Rajasthan</option>
        <option value="sk">Sikkim</option>
        <option value="tn">Tamil Nadu</option>
        <option value="ts">Telangana</option>
        <option value="tr">Tripura</option>
        <option value="up">Uttar Pradesh</option>
        <option value="ut">Uttarakhand</option>
        <option value="wb">West Bengal</option>
    </select>
</div>

<div class="single-line"></div>

<div class="d-flex justify-content-between align-items-center mb-4">
    <span class="fw-semibold" style="color: #475569;">💰 SERVICE CHARGE</span>
    <span class="fw-bold fs-5" style="color: #1e293b;">₹ <?= number_format($fee, 2) ?></span>
</div>

<button type="submit" class="btn btn-success w-100 py-2" id="submitBtn" 
        style="border-radius: 12px; font-weight: 600; font-size: 16px;">
    🔍 CHECK STATUS
</button>

</form>

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

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

<?php include('../template/tngweb/footer.php'); ?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// Aadhar validation
function validateAadhar(aadhar) {
    return /^[0-9]{12}$/.test(aadhar);
}

let submitting = false;
document.getElementById("statusForm").addEventListener("submit", function(e) {
    e.preventDefault();
    if (submitting) return;

    var aadhar = document.getElementById("aadhar").value;
    if(!validateAadhar(aadhar)) {
        Swal.fire('Invalid Aadhaar', 'Please enter valid 12-digit Aadhaar number', 'error');
        return;
    }

    var state = document.getElementById("state_code").value;
    if(state == "") {
        Swal.fire('Invalid Input', 'Please select State', 'error');
        return;
    }

    Swal.fire({
        title: 'Confirm?',
        text: 'Farmer Card Status check hoga aur wallet se fee deduct hogi',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Proceed',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#10b981'
    }).then((result) => {
        if (result.isConfirmed) {
            submitting = true;
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('submitBtn').innerText = 'Processing...';
            this.submit();
        }
    });
});
</script>

<script src="../template/tngweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>
</html>