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

$fee = $udata['Lerning_Licence_pdf_fee'] ?? 30;
checkServiceStatus($udata, 'Lerning_Licence_pdf_fee_status');

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


if (!empty($_POST['value']) && !empty($_POST['type'])) {

    $value = trim($_POST['value']);
    $type  = trim($_POST['type']);
    $dob   = trim($_POST['dob'] ?? '');
    $debit_fee = $balance - $fee;

    if ($balance < $fee) {
        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>";
        exit;
    }

    $request = [
        'value' => $value,
        'type'  => $type,
        'dob'   => $dob
    ];

    $resdata = Lerning_license_to_pdf_verification_api_run($request);

    if (($resdata['sampleCode'] ?? '') !== "200") {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire(
                'Verification Failed',
                '".($resdata['error'] ?? 'Service Error')."',
                'error'
            );
        </script>";
    }
    else {

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


        addCommission(
            $tng_conn,
            $appliedby,
            $fee,
            $parentPhone,
            "Learning Licence PDF"
        );

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


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


        mysqli_query(
            $tng_conn,
            "INSERT INTO all_pdf_records
            (service_name,name,username,number,pdf,date)
            VALUES
            (
                'learning_licence_pdf',
                '".mysqli_real_escape_string($tng_conn,$resdata['fullname'])."',
                '$appliedby',
                '".mysqli_real_escape_string($tng_conn, $resdata['licNum'] ?? $resdata['applNum'] ?? $value)."',
                '".mysqli_real_escape_string($tng_conn,$resdata['pdf'])."',
                '$timestamp'
            )"
        );

   
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
        Swal.fire({
            icon:'success',
            title:'Success',
            text:'Learning Licence PDF Generated Successfully',
            timer:1500,
            showConfirmButton:false
        }).then(()=>{
            window.location='all_history.php';
        });
        </script>";
    }
}
?>

<!-- ===============================
     LUXURY UI
================================ -->
<style>
.ll-card{
    border-radius:18px;
    box-shadow:0 20px 45px rgba(0,0,0,.25);
    background:linear-gradient(135deg,#ffffff,#eef2ff);
}
.ll-title{
    background:linear-gradient(90deg,#1e3c72,#2a5298);
    color:#fff;
    padding:12px;
    border-radius:12px;
    text-align:center;
    font-weight:600;
}
.ll-btn{
    background:linear-gradient(45deg,#0f2027,#203a43,#2c5364);
    border:none;
    border-radius:50px;
    padding:12px;
    color:#fff;
    font-weight:600;
}
.ll-btn:hover{ transform:scale(1.04); }
</style>

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

<div class="row justify-content-center">
<div class="col-lg-4 col-md-6">

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

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

<div class="ll-title mb-3">
Learning Licence PDF Verification
</div>

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

<div class="mb-3">
<label class="fw-semibold">Licence / Application / Mobile Number</label>
<input type="text" name="value" class="form-control" required>
</div>

<div class="mb-3">
<label class="fw-semibold">Select Type</label>
<select name="type" id="typeSelect" class="form-control" onchange="toggleDOB()" required>
    <option value="">Select</option>
    <option value="licnum">Licence Number</option>
    <option value="applnum">Application Number</option>
    <option value="mobile">Mobile Number</option>
</select>
</div>

<div class="mb-3" id="dobField" style="display:none;">
<label class="fw-semibold">Date of Birth</label>
<input type="text" name="dob" id="dob" class="form-control" placeholder="DD-MM-YYYY">
</div>

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

<button type="submit" id="submitBtn" class="ll-btn w-100">
Generate PDF
</button>

</form>

</div>
</div>

</div>
</div>

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

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

<!-- ===============================
     CONFIRM + DOUBLE SUBMIT SAFE
================================ -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function toggleDOB(){
    const t = document.getElementById('typeSelect').value;
    const d = document.getElementById('dobField');
    const i = document.getElementById('dob');
    if(t === 'mobile'){
        d.style.display='block';
        i.required=true;
    } else {
        d.style.display='none';
        i.required=false;
        i.value='';
    }
}

document.addEventListener("DOMContentLoaded", function () {

let submitting = false;
const form = document.getElementById("llForm");
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((r)=>{
    if(r.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/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>
</html>
