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

// Fee and Service Status Check
$fee = $udata['AgriFarmerCardPdf_a'] ?? 30;
checkServiceStatus($udata, 'AgriFarmerCardPdf_a_status');

$appliedby = $udata['phone'];
$balance   = $udata['balance'];

/**
 * Agri Farmer API Run (SQL se API Key & URL fetch karega)
 */
function agri_farmer_card_pdf_verification_api_run($uid, $state) {
    $apiKey = JkL_get('TheNextGenAPI', 'tng_apikey'); 
    $baseUrl = JkL_get('TheNextGenAPI', 'tng_apiurl');
    
    // ApiNexus New URL structure
    $url = "https://" . rtrim($baseUrl, "/") . "/api/v1/AgriStak/approvedFarmersPdf.php?apiKey=$apiKey&uidNumber=$uid&state=$state";

    $resJson = http_get($url); 
    return json_decode($resJson, true) ?? [];
}

/* ===============================
   FORM SUBMIT HANDLER
================================ */
if (isset($_POST['aadhar'])) {

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

    // 1. Balance Check
    if ($balance < $fee) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire('Low Balance','Please Recharge Wallet','error').then(()=>{ window.location='wallet.php'; });
        </script>";
        exit;
    }

    // 2. Execute API
    $resdata = agri_farmer_card_pdf_verification_api_run($aadhar, $state);

    // 3. Response Handling
    if (isset($resdata['status']) && $resdata['status'] === "success") {
        
        date_default_timezone_set('Asia/Kolkata');
        $timestamp = date("Y-m-d H:i:s");
        $parentPhone = $udata['parent'] ?? null;

        /* Commission Update */
        addCommission($tng_conn, $appliedby, $fee, $parentPhone, "Agri Farmer Card PDF");

        /* Balance Deduct */
        mysqli_query($tng_conn, "UPDATE users SET balance = balance - $fee WHERE phone='$appliedby'");

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

        /* Save to PDF History Table (Base64 Format) */
        $pdf_content = mysqli_real_escape_string($tng_conn, $resdata['pdfBase64']);
        $cust_name   = "Farmer (" . $aadhar . ")";

        // Adding data:application/pdf;base64 prefix for direct preview/download
        $full_base64 = "data:application/pdf;base64," . $pdf_content;

        mysqli_query($tng_conn, "INSERT INTO all_pdf_records (service_name, name, username, number, pdf, date) 
                     VALUES ('agri_farmer_pdf', '$cust_name', '$appliedby', '$aadhar', '$full_base64', '$timestamp')");

        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon:'success',
                title:'Success',
                text:'Farmer Card Generated Successfully',
                timer:1500,
                showConfirmButton:false
            }).then(()=>{ window.location='all_history.php'; });
        </script>";
    } else {
        $errorMsg = $resdata['message'] ?? 'Farmer Record Not Found or API Error';
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>Swal.fire('Error', '$errorMsg', 'error');</script>";
    }
}
?>

<style>
.card-shine { border-radius:15px; box-shadow:0 10px 30px rgba(0,0,0,0.15); transition:.3s; }
.card-shine:hover { transform:translateY(-3px); box-shadow:0 15px 40px rgba(0,0,0,0.25); }
.form-label { font-weight: 600; color: #444; }
</style>

<div class="content-wrap">
    <div class="page-wrapper">
        <div class="page-content d-flex justify-content-center">
            <div class="col-lg-4 col-md-6 col-sm-10">
                <div class="card card-shine">
                    <div class="card-body">
                        <a href="javascript:history.back()" class="btn btn-light btn-sm mb-3">← Go Back</a>
                        <div class="alert alert-success text-center fw-bold small">AGRI FARMER CARD PDF</div>

                        <form method="POST" id="pdfForm">
                            <div class="mb-3">
                                <label class="form-label">Aadhaar Number</label>
                                <input type="text" name="aadhar" class="form-control" maxlength="12" minlength="12" placeholder="12 Digit Aadhaar" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Select State</label>
                                <select name="state_code" id="state_code" class="form-control" required>
                                    <option value="">Select State</option>
                                </select>
                            </div>

                            <div class="mb-4">
                                <div class="p-2 bg-light rounded text-center fw-bold text-primary">
                                    Service Charge: ₹ <?= $fee; ?>
                                </div>
                            </div>

                            <button type="submit" id="submitBtn" class="btn btn-success w-100 fw-bold py-2">
                                Generate Farmer PDF
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
    const states = [
    // --- 28 States ---
    {code:"ap", name:"Andhra Pradesh"},
    {code:"ar", name:"Arunachal Pradesh"},
    {code:"as", name:"Assam"},
    {code:"br", name:"Bihar"},
    {code:"cg", name:"Chhattisgarh"},
    {code:"ga", name:"Goa"},
    {code:"gj", name:"Gujarat"},
    {code:"hr", name:"Haryana"},
    {code:"hp", name:"Himachal Pradesh"},
    {code:"jh", name:"Jharkhand"},
    {code:"ka", name:"Karnataka"},
    {code:"kl", name:"Kerala"},
    {code:"mp", name:"Madhya Pradesh"},
    {code:"mh", name:"Maharashtra"},
    {code:"mn", name:"Manipur"},
    {code:"ml", name:"Meghalaya"},
    {code:"mz", name:"Mizoram"},
    {code:"nl", name:"Nagaland"},
    {code:"od", name:"Odisha"},
    {code:"pb", name:"Punjab"},
    {code:"rj", name:"Rajasthan"},
    {code:"sk", name:"Sikkim"},
    {code:"tn", name:"Tamil Nadu"},
    {code:"ts", name:"Telangana"},
    {code:"tr", name:"Tripura"},
    {code:"up", name:"Uttar Pradesh"},
    {code:"uk", name:"Uttarakhand"},
    {code:"wb", name:"West Bengal"},
    
    // --- 8 Union Territories ---
    {code:"an", name:"Andaman and Nicobar Islands"},
    {code:"ch", name:"Chandigarh"},
    {code:"dn", name:"Dadra and Nagar Haveli and Daman and Diu"},
    {code:"dl", name:"Delhi (NCT)"},
    {code:"jk", name:"Jammu and Kashmir"},
    {code:"la", name:"Ladakh"},
    {code:"ld", name:"Lakshadweep"},
    {code:"py", name:"Puducherry"}
];
    const stateSelect = document.getElementById("state_code");
    states.forEach(s => {
        let o = document.createElement("option");
        o.value = s.code; o.text = s.name;
        stateSelect.appendChild(o);
    });

    let submitting = false;
    const form = document.getElementById("pdfForm");
    const btn = document.getElementById("submitBtn");

    form.addEventListener("submit", function(e) {
        e.preventDefault();
        if (submitting) return;

        Swal.fire({
            title: 'Confirm Request?',
            text: 'Wallet se ₹<?= $fee ?> deduct honge.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            confirmButtonText: 'Yes, Generate'
        }).then((result) => {
            if (result.isConfirmed) {
                submitting = true;
                btn.disabled = true;
                btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Processing...';
                form.submit();
            }
        });
    });
});
</script>