<?php
include('header.php');

if (isset($_POST['b2']) && $_POST['b2'] === "Bittu") {
    $dl = mysqli_real_escape_string($ahk_conn, $_POST['dl']);
    $dob_input = mysqli_real_escape_string($ahk_conn, $_POST['dob']);

    $application_no = "FLX_" . rand(100000, 999999);

    $price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM pricing WHERE service_name='Driving_Licence_Pdf'"));
    $fee = $price['price'];

    $username = $udata['phone'];
    $wallet = $udata['balance'];

    if ($wallet >= $fee) {
        $debit_fee = $wallet - $fee;
        $api_key = urlencode($flexsecure_key);
        $baseUrl = htmlspecialchars($flexsecureapiurl);

        $url = "https://{$baseUrl}/api/v1/dlVerificationPDF-Chip.php?apiKey={$api_key}&dlNo={$dl}&dob={$dob_input}";

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ]);
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if ($httpCode != 200) {
            echo "<script>Swal.fire('API Error', 'Connection issue with API.', 'error'); setTimeout(() => { window.location.href = 'DL_Instant_flx_blue'; }, 2000);</script>";
            exit;
        }

         $resdata = json_decode($response, true);
        $api_dob = isset($resdata['dob']) ? mysqli_real_escape_string($ahk_conn, $resdata['dob']) : $dob_input;

        if (isset($resdata['status']) && $resdata['status'] === "100" && !empty($resdata['pdf'])) {
            $pdfRaw = $resdata['pdf'];

            $debit = mysqli_query($ahk_conn, "UPDATE users SET balance='$debit_fee' WHERE phone='$username'");
            if ($debit) {
                mysqli_query($ahk_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type)
                    VALUES ('$username','$fee','$debit_fee','Driving Licence Blue PDF','1','Debit')");

                mysqli_query($ahk_conn, "INSERT INTO dlprint2 (application_no, username, dl_no, dob, response, status, fee, front, back, pdf)
                    VALUES ('$application_no','$username','$dl', '$api_dob', '" . mysqli_real_escape_string($ahk_conn, $response) . "', 'success', '$fee', '', '', '" . mysqli_real_escape_string($ahk_conn, $pdfRaw) . "')");
            }

            echo "<script>Swal.fire('Success', 'DL downloaded successfully.', 'success'); setTimeout(() => { window.location.href = 'DL_Instant_flx_blue_list'; }, 2000);</script>";
        } else {
            // Extract meaningful message if available
            $apiMessage = isset($resdata['message']) && !empty($resdata['message']) 
                ? $resdata['message'] 
                : 'DL not found or PDF not generated.';
            
            // Optionally log error response in DB or file if needed here

            echo "<script>Swal.fire('Error', " . json_encode($apiMessage) . ", 'error'); setTimeout(() => { window.location.href = 'DL_Instant_flx_blue'; }, 2000);</script>";
        }
    } else {
        echo "<script>Swal.fire('Oops', 'Wallet Balance Insufficient! Please Recharge', 'error'); setTimeout(() => { window.location.href = 'wallet'; }, 2000);</script>";
    }
}
?>

<div class="page-wrapper">
    <div class="page-content">
        <!-- Breadcrumb with Action Buttons -->
        <div class="page-breadcrumb d-flex align-items-center justify-content-between mb-4 p-3 bg-white rounded shadow-sm">
            <div class="d-flex align-items-center">
                <div class="breadcrumb-title pe-3">Services</div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 ps-2">
                        <li class="breadcrumb-item active text-muted" aria-current="page">Driving Licence Blue</li>
                    </ol>
                </nav>
            </div>
            <div class="btn-group">
                <a href="DL_Instant_flx_blue_list" class="btn btn-success">
                    <i class="bi bi-list-ul me-1"></i> All Blue DL Pdf List
                </a>
                <a href="javascript:history.back()" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left me-1"></i> Back
                </a>
            </div>
        </div>

        <div class="container-fluid pt-4 px-4">
            <div class="row">
                <!-- Left Side (30%) -->
                <div class="col-lg-4 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <div class="p-3 mb-4 rounded text-white" style="background: linear-gradient(135deg, #0062E6, #33AEFF);">
                                <h3 class="text-center m-0 text-white">
                                    <i class="bi bi-file-earmark-pdf-fill me-2"></i>
                                    <strong>Driving Licence Download </strong>
                                </h3>
                            </div>
                            <form method="post" id="dlprint">
                                <div class="form-group mb-3">
                                    <label for="dl">Driving Licence Number</label>
                                    <input type="text" class="form-control" name="dl" required>
                                </div>
                                <div class="form-group mb-3">
                                    <label for="dob">D.O.B</label>
                                    <input type="text" class="form-control" name="dob" placeholder="DD-MM-YYYY" required>
                                </div>
                                <input type="hidden" name="b2" value="Bittu">
                                <button type="submit" class="btn btn-primary w-100 d-flex align-items-center justify-content-center" id="submitBtn">
                                    <span id="btnText">Submit</span>
                                    <span id="btnSpinner" class="spinner-border spinner-border-sm d-none ms-2" role="status" aria-hidden="true"></span>
                                </button>
                                <div class="text-center mt-3">
                                    <div class="fee-container">
                                        <h5 class="text-warning">Application Fee:
                                            <?php  
                                                $price = mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT price FROM pricing WHERE service_name='Driving_Licence_Pdf'")); 
                                                echo "₹" . $price['price'];
                                            ?>
                                        </h5>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div> <!-- end col -->
            </div>
        </div>
    </div>
</div>

<style>
    .fee-container {
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        padding: 10px 15px;
        max-width: 300px;
        margin: auto;
    }
    .fee-container h5 {
        color: #ff9800;
        font-size: 18px;
        font-weight: 600;
        margin: 0;
    }
    #submitBtn .spinner-border {
        vertical-align: middle;
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('dlprint');
    const submitBtn = document.getElementById('submitBtn');
    const btnText = document.getElementById('btnText');
    const btnSpinner = document.getElementById('btnSpinner');

    form.addEventListener('submit', function () {
        submitBtn.disabled = true;
        btnText.textContent = 'Processing...';
        btnSpinner.classList.remove('d-none');
    });
});
</script>

<?php include('footer.php'); ?>
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<!--plugins-->
<script src="../template/ahkweb/assets/js/jquery.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/plugins/chartjs/chart.min.js"></script>
<script src="../template/ahkweb/assets/plugins/vectormap/jquery-jvectormap-2.0.2.min.js"></script>
<script src="../template/ahkweb/assets/plugins/vectormap/jquery-jvectormap-world-mill-en.js"></script>
<script src="../template/ahkweb/assets/plugins/jquery.easy-pie-chart/jquery.easypiechart.min.js"></script>
<script src="../template/ahkweb/assets/plugins/sparkline-charts/jquery.sparkline.min.js"></script>
<script src="../template/ahkweb/assets/plugins/jquery-knob/excanvas.js"></script>
<script src="../template/ahkweb/assets/plugins/jquery-knob/jquery.knob.js"></script>
<script>
$(function() {
    $(".knob").knob();
});
</script>
<script src="../template/ahkweb/assets/js/index.js"></script>
<!--app JS-->
<script src="../template/ahkweb/assets/js/app.js"></script>
<!-- datatable -->
<script src="../template/ahkweb/assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
	<script src="../template/ahkweb/assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>