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

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

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

/**
 * Dynamic API Call (SQL se API Key & URL fetch karega)
 */
function Learning_Licence_API_Run($appNo) {
    $apiKey = JkL_get('TheNextGenAPI', 'tng_apikey'); 
    $baseUrl = JkL_get('TheNextGenAPI', 'tng_apiurl');
    
    // API URL Structure as per ApiNexus
    $url = "https://" . rtrim($baseUrl, "/") . "/api/v1/LL_application_pdf?apiKey=$apiKey&applicationNo=$appNo";

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

if (!empty($_POST['applicationNo'])) {

    $applicationNo = trim($_POST['applicationNo']);
    $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 = Learning_Licence_API_Run($applicationNo);

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

        // Commission & Balance Update
        addCommission($tng_conn, $appliedby, $fee, $parentPhone, "Learning Licence PDF");
        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', 'Learning Licence PDF', '1', 'Debit')");

        // Save Record to DB
        $pdf_base64 = mysqli_real_escape_string($tng_conn, $resdata['pdf']);
        $app_num = mysqli_real_escape_string($tng_conn, $resdata['app_number']);
        $cust_name = "LL Holder (" . $app_num . ")";

        mysqli_query($tng_conn, "INSERT INTO all_pdf_records (service_name, name, username, number, pdf, date) 
            VALUES ('learning_licence_pdf', '$cust_name', '$appliedby', '$app_num', 'data:application/pdf;base64,$pdf_base64', '$timestamp')");

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

<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 shadow-lg" style="border-radius:20px; border:none;">
                    <div class="card-body p-4">
                        <a href="javascript:history.back()" class="btn btn-sm btn-light mb-3">← Back</a>
                        <h5 class="text-center fw-bold text-primary mb-4">LL PDF Verification</h5>

                        <form method="POST" id="llForm">
                            <div class="mb-3">
                                <label class="form-label fw-semibold">Application Number</label>
                                <input type="text" name="applicationNo" class="form-control rounded-pill" placeholder="Enter Application No." required>
                            </div>

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

                            <button type="submit" id="submitBtn" class="btn btn-primary w-100 rounded-pill fw-bold py-2">
                                Generate & Download 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.getElementById("llForm").addEventListener("submit", function(e) {
    e.preventDefault();
    Swal.fire({
        title: 'Confirm Action?',
        text: 'Wallet se ₹<?= $fee ?> deduct honge.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, Process'
    }).then((result) => {
        if (result.isConfirmed) {
            const btn = document.getElementById("submitBtn");
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Processing...';
            this.submit();
        }
    });
});
</script>