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

$fee = isset($udata['dl_pdf_fee']) ? (int)$udata['dl_pdf_fee'] : 30;
checkServiceStatus($udata, 'dl_pdf_fee_status');

/**
 * Dynamic API Call
 */
function dl_pdf_verification_v1_api_run($request) {
    $getData = http_build_query([
        'apiKey' => JkL_get('TheNextGenAPI', 'tng_apikey'), 
        'dlNo'   => $request['dl_number'],
        'dob'    => $request['dob']
    ]);

    $baseUrl = JkL_get('TheNextGenAPI', 'tng_apiurl');
    $url = "https://" . rtrim($baseUrl, "/") . "/serviceApi/TargetApiV1/DL/dl_link.php?$getData";

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

if (isset($_POST['dl_number'], $_POST['dob'])) {
    $dl_number = trim($_POST['dl_number']);
    $dob       = trim($_POST['dob']);
    $appliedby = $udata['phone'];
    $debit_fee = $udata['balance'] - $fee;

    if ($udata['balance'] >= $fee) {
        $request = ['dl_number' => $dl_number, 'dob' => $dob];
        $resdata = dl_pdf_verification_v1_api_run($request);

        if (isset($resdata['result']['status']) && $resdata['result']['status'] === 'success') {
            date_default_timezone_set('Asia/Kolkata');
            $timestamp = date("Y-m-d H:i:s");

            // Commission & Balance Update
            $parentPhone = $udata['parent'] ?? null;
            addCommission($tng_conn, $appliedby, $fee, $parentPhone, "DL PDF Verification");
            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', 'DL PDF Verification','1','Debit')");

            // Save Base64 PDF to DB
            $pdf_base64 = mysqli_real_escape_string($tng_conn, $resdata['result']['base64pdf']);
            $cust_name  = mysqli_real_escape_string($tng_conn, $resdata['result']['name'] ?? 'DL Holder');

            mysqli_query($tng_conn, "INSERT INTO all_pdf_records (service_name, name, username, number, pdf, date) 
                         VALUES ('dl_pdf', '$cust_name', '$appliedby', '$dl_number', '$pdf_base64', '$timestamp')");

            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({icon:'success', title:'Success', text:'DL PDF Generated', timer:1500, showConfirmButton:false})
                .then(()=>{ window.location='all_history.php'; });
            </script>";
        } else {
            $msg = $resdata['result']['message'] ?? 'API Error';
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>Swal.fire('Error','$msg','error');</script>";
        }
    } else {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>Swal.fire('Low Balance','Please Recharge','error').then(()=>{window.location='wallet.php';});</script>";
    }
}
?>

<div class="content-wrap">
    <div class="main">
        <div class="page-wrapper">
            <div class="page-content d-flex justify-content-center">
                <div class="col-lg-4 col-md-6 col-sm-8">
                    <div class="card card-shine" style="border-radius:16px; box-shadow:0 12px 32px rgba(0,0,0,0.15);">
                        <div class="card-body">
                            <a href="javascript:history.back()" class="btn btn-sm btn-light mb-3">← Back</a>
                            <h5 class="text-center fw-bold mb-4">DL PDF Verification</h5>

                            <form method="POST" id="dlForm">
                                <div class="mb-3">
                                    <label class="form-label">DL Number</label>
                                    <input type="text" name="dl_number" class="form-control" placeholder="UP55XXXXXXXXXXXX" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Date of Birth</label>
                                    <input type="text" name="dob" class="form-control" placeholder="DD-MM-YYYY" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Charge</label>
                                    <input class="form-control text-center fw-bold" value="₹ <?= $fee ?>" readonly style="background:#f8f9fa;">
                                </div>
                                <button type="submit" class="btn btn-success w-100 fw-bold" id="submitBtn">Generate & Download</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

<script>
document.getElementById("dlForm").addEventListener("submit", function(e) {
    e.preventDefault();
    Swal.fire({
        title: 'Confirm Request?',
        text: 'Fee ₹<?= $fee ?> deduct hogi.',
        icon: 'warning',
        showCancelButton: true,
        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>