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

$showPdf = false;
$pdfUrl = '';

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

    $application_no = "FLX_" . rand(100000, 999999);
    $type = ($card_type == "chip") ? "2" : "1";
    $color = ($background == "B") ? "true" : "false";

    $price_row = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT price FROM pricing WHERE service_name='Driving_Licence_Pdf'"));
    $fee = $price_row['price'];
    $username = $udata['phone'];
    $wallet = $udata['balance'];

    if ($wallet >= $fee) {
        $debit_fee = $wallet - $fee;
        $api_key = urlencode($flexsecure_key);
        $url = "https://" . htmlspecialchars($flexsecureapiurl) . "/serviceApi/FlexSecureV1/DL/dl_link.php?apiKey=$api_key&dlNo=$dl&dob=$dob&color=$color&type=$card_type";

        $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 || !$response) {
            echo "<script>
                Swal.fire('API Error', 'Failed to connect to the service. Try again later.', 'error');
                setTimeout(() => { window.location.href = 'DL_Instant_flx'; }, 3000);
            </script>";
        } else {
            $resdata = json_decode($response, true);

            if (!$resdata || json_last_error() !== JSON_ERROR_NONE) {
                echo "<script>
                    Swal.fire('Response Error', 'Invalid response from API. Please try again later.', 'error');
                    setTimeout(() => { window.location.href = 'DL_Instant_flx'; }, 3000);
                </script>";
            } elseif (!empty($resdata['message'])) {
                $error = htmlspecialchars($resdata['message']);
                echo "<script>
                    Swal.fire('API Error', '$error', 'warning');
                    setTimeout(() => { window.location.href = 'DL_Instant_flx'; }, 3000);
                </script>";
            } elseif (empty($resdata['a4'])) {
                echo "<script>
                    Swal.fire('PDF Generation Failed', 'The A4 PDF was not generated. Please contact admin.', 'error');
                    setTimeout(() => { window.location.href = 'DL_Instant_flx'; }, 3000);
                </script>";
            } else {
                $front = $resdata['front'] ?? '';
                $back = $resdata['back'] ?? '';
                $a4 = $resdata['a4'];

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

                if ($debit) {
                    $insert = mysqli_query($ahk_conn, "INSERT INTO dlprint (application_no, username, dl_no, dob, response, status, fee, front, back, pdf) VALUES ('$application_no','$username','$dl', '$dob', '$response','success', '$fee', '$front','$back','$a4');");

                    if ($insert) {
                        $showPdf = true;
                        $pdfUrl = (strpos($a4, 'data:application/pdf;base64,') === 0) ? $a4 : 'data:application/pdf;base64,' . $a4;

                        echo "<script>
                            Swal.fire('Success', 'DL: $dl downloaded. App No: $application_no', 'success');
                        </script>";
                    }
                }
            }
        }
    } else {
        echo "<script>
            Swal.fire('Insufficient Balance', 'Your wallet balance is low. 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</li>
                    </ol>
                </nav>
            </div>
            <div class="btn-group">
                <a href="DL_Instant_flx_list" class="btn btn-success">
                    <i class="bi bi-list-ul me-1"></i> All 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>
                                <div class="form-group mb-3">
                                    <label for="background">Card Background</label>
                                    <select name="background" class="form-control" required>
                                        <!--<option value="B">Blue</option>-->
                                        <option value="W">White</option>
                                    </select>
                                </div>
                                <div class="form-group mb-3">
                                    <label for="card_type">Card Type</label>
                                    <select name="card_type" class="form-control" required>
                                        <option value="nochip">Without Chip</option>
                                        <option value="chip">With Chip</option>
                                    </select>
                                    <input type="hidden" name="b2" value="Bittu">
                                </div>
                                <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>

                <!-- Right Side (70%) PDF Preview -->
                <div class="col-lg-8">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title text-center">PDF Preview</h4>
                            <?php if ($showPdf && $pdfUrl): ?>
                                <div class="text-end mb-2">
                                    <a href="<?php echo $pdfUrl; ?>" download="DL_A4.pdf" class="btn btn-success btn-sm">Download PDF</a>
                                </div>
                                <iframe src="<?php echo $pdfUrl; ?>" style="width:100%; height:600px;" frameborder="0"></iframe>
                            <?php else: ?>
                                <div class="alert alert-info text-center">No PDF Preview Available</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </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;
    }

    /* Optional: Align spinner better inside the button */
    #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 () {
            // Disable button
            submitBtn.disabled = true;
            // Update text
            btnText.textContent = 'Processing...';
            // Show spinner
            btnSpinner.classList.remove('d-none');
        });
    });
</script>

<noscript>
    <div class="alert alert-danger mt-2 text-center">
        JavaScript is required to submit this form properly.
    </div>
</noscript>

<!--end page wrapper -->
<?php 
include('footer.php');
?>
<!-- Bootstrap JS -->
<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>
<script>
		$(document).ready(function() {
			$('#example').DataTable();
		  } );
	</script>
	
	<script>
		$(document).ready(function() {
			var table = $('#example2').DataTable( {
				lengthChange: false,
				buttons: [ 'copy', 'excel', 'pdf', 'print']
			} );
		 
			table.buttons().container()
				.appendTo( '#example2_wrapper .col-md-6:eq(0)' );
		} );
	</script>
	
</body>



</html>