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

$fee = $udata['AgriFarmerCardPdf_a'];
checkServiceStatus($udata, 'AgriFarmerCardPdf_a_status');
?>

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

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

    $aadhar    = $_POST['aadhar'];
    $language  = $_POST['language_Code'] ?? 'hi';
    $state     = $_POST['state_code'] ?? '';
    $appliedby = $udata['phone'];
    $debit_fee = $udata['balance'] - $fee;

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

        $request = [
            'aadhar'   => $aadhar,
            'language' => $language,
            'state'    => $state
        ];

        $resdata = agri_farmer_card_pdf_verification_api_run($request);

        $statusCode = $resdata['sampleCode'] ?? '';
        $errorMsg   = $resdata['error'] ?? '';

        if ($errorMsg) {
            echo "<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 PDF"
            );

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

            mysqli_query(
                $tng_conn,
                "INSERT INTO all_pdf_records
                 (service_name, name, username, number, pdf, date)
                 VALUES
                 (
                    'agri_farmer_pdf',
                    '{$resdata['fullname']}',
                    '{$udata['phone']}',
                    '{$resdata['aadhar']}',
                    '{$resdata['pdf']}',
                    '$timestamp'
                 )"
            );

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

            echo "<script>
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'PDF Generated Successfully',
                    timer: 1500,
                    showConfirmButton: false
                });
                setTimeout(()=>{ window.location='all_history.php'; },1500);
            </script>";
        }

    } else {
        echo "<script>
            Swal.fire('Low Balance', 'Please Recharge Wallet', 'error');
            setTimeout(()=>{ window.location='wallet.php'; },1500);
        </script>";
    }
}
?>

<style>
.card-shine {
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.15);
    transition: 0.3s;
}
.card-shine:hover {
    transform: translateY(-3px);
    box-shadow: 0 15px 40px rgba(0,0,0,0.25);
}
</style>

<div class="content-wrap">
<div class="main">
<div class="main-content">
<div class="page-wrapper">
<div class="page-content">

<div class="d-flex justify-content-center">
<div class="col-lg-4 col-md-6 col-sm-8">

<div class="card card-shine">
<div class="card-body">

<a href="javascript:history.back()" class="btn btn-light mb-3 w-100">
← Go Back
</a>

<div class="alert alert-danger text-center fw-bold">
Agri Farmer Card (All State) PDF
</div>

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

<div class="mb-3">
<label>Enter 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>Select Language</label>
<select name="language_Code" id="language_Code"
        class="form-control" required>
<option value="">Select Language</option>
</select>
</div>

<div class="mb-3">
<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-3">
<input class="form-control text-center fw-bold"
       value="Fee ₹ <?php echo $fee; ?>" readonly>
</div>

<button class="btn btn-success w-100" id="submitBtn">
Generate PDF
</button>

</form>

</div>
</div>

</div>
</div>

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

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

<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 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:"od",name:"Odisha"},{code:"pb",name:"Punjab"},
 {code:"rj",name:"Rajasthan"},{code:"tn",name:"Tamil Nadu"},
 {code:"ts",name:"Telangana"},{code:"up",name:"Uttar Pradesh"},
 {code:"wb",name:"West Bengal"},{code:"dl",name:"Delhi"},
 {code:"jk",name:"Jammu & Kashmir"},{code:"la",name:"Ladakh"},
 {code:"py",name:"Puducherry"}
];

languages.forEach(l=>{
 let o=document.createElement("option");
 o.value=l.code;o.text=l.name;
 language_Code.appendChild(o);
});
states.forEach(s=>{
 let o=document.createElement("option");
 o.value=s.code;o.text=s.name;
 state_code.appendChild(o);
});

/* ARE YOU SURE + DOUBLE CLICK SAFE */
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:'Are you sure?',
   text:'PDF generate hogi aur wallet se fee deduct hogi',
   icon:'warning',
   showCancelButton:true,
   confirmButtonText:'Yes, Proceed',
   cancelButtonText:'Cancel'
 }).then((result)=>{
   if(result.isConfirmed){
     submitting=true;
     btn.disabled=true;
     btn.innerText='Processing...';
     form.submit();
   }
 });
});

});
</script>

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