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

// Set timezone
date_default_timezone_set("Asia/Kolkata");

// Initialize variables
$resdata = null;
$error_message = '';

// Check if PAN is submitted
if (isset($_POST['verify_pan'])) {
    $pan_no = trim($_POST['pan_no']);

    // Basic PAN validation
    if (!preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/i', $pan_no)) {
        $error_message = "Invalid PAN format.";
    } else {
        $username = $udata['phone'];

        // Fetch price from DB
        $price_result = mysqli_query($ahk_conn, "SELECT price FROM pricing WHERE service_name='pan_details_verify' LIMIT 1");
        $price_row = mysqli_fetch_assoc($price_result);
        $fee = (float)($price_row['price'] ?? 0);

        $wallet_amount = (float)$udata['balance'];

        // Check wallet balance
        if ($wallet_amount < $fee) {
            echo "<script>
                document.addEventListener('DOMContentLoaded', function () {
                    Swal.fire({
                        icon: 'error',
                        title: 'Insufficient Balance',
                        text: 'Your wallet balance is too low to process this request',
                    }).then(() => {
                        window.location.href = 'wallet.php';
                    });
                });
            </script>";
            exit;
        }

        // ====================== PARI PRINT URL (Clean & Recommended) ======================
        $url = $auth_url . "api_service/panDetails_api.php?" . http_build_query([
            'api_key'    => $api_key,
            'secret_key' => $secret_key,
            'pan_no'     => $pan_no
        ]);

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => ["cache-control: no-cache"],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            $error_message = "cURL Error: $err";
        } else {
            $json = json_decode($response, true);

            if (isset($json['status']) && $json['status'] === 'success') {
                // Prepare data
                $name         = $json['name'] ?? '';
                $fathername   = $json['fathername'] ?? '';
                $gender       = $json['gender'] ?? '';
                $dob          = $json['dob'] ?? '';
                $aadhaarLinked = $json['aadharno'] ?? '';

                $time_hkb = date('d/m/Y g:i:s A');

                // Start transaction
                mysqli_begin_transaction($ahk_conn);

                try {
                    // Deduct fee
                    mysqli_query($ahk_conn, "UPDATE users SET balance = balance - $fee 
                        WHERE phone = '" . mysqli_real_escape_string($ahk_conn, $username) . "'");

                    // Insert PAN verification record
                    $stmt = mysqli_prepare($ahk_conn, 
                        "INSERT INTO pan_verify_hkb (name, fathername, gender, dob, pan, username, date) 
                         VALUES (?, ?, ?, ?, ?, ?, ?)");
                    mysqli_stmt_bind_param($stmt, "sssssss", $name, $fathername, $gender, $dob, $pan_no, $username, $time_hkb);
                    mysqli_stmt_execute($stmt);
                    mysqli_stmt_close($stmt);

                    // Wallet History
                    $new_balance = $wallet_amount - $fee;
                    $stmt2 = mysqli_prepare($ahk_conn, 
                        "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) 
                         VALUES (?, ?, ?, 'PAN Details Verify', '1', 'Debit')");
                    mysqli_stmt_bind_param($stmt2, "sdd", $username, $fee, $new_balance);
                    mysqli_stmt_execute($stmt2);
                    mysqli_stmt_close($stmt2);

                    mysqli_commit($ahk_conn);

                    // Set response for display
                    $resdata = [
                        'statusCode'    => 100,
                        'pan_no'        => $pan_no,
                        'name'          => $name,
                        'fathername'    => $fathername,
                        'gender'        => $gender,
                        'dob'           => $dob,
                        'aadhaarLinked' => $aadhaarLinked,
                    ];

                } catch (Exception $e) {
                    mysqli_rollback($ahk_conn);
                    $error_message = "Database error: " . $e->getMessage();
                }
            } else {
                $error_message = $json['message'] ?? $json['msg'] ?? "Failed to verify PAN.";
            }
        }
    }
}
?>

<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">Pan Details Find</li>
                    </ol>
                </nav>
            </div>
            <div class="btn-group">
                <a href="javascript:history.back()" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left me-1"></i> Back
                </a>
            </div>
        </div>
        <!--end breadcrumb-->

        <div class="container-fluid pt-4 px-4">
            <div class="row">
                <!-- Left Side: Form Section -->
                <div class="col-lg-5 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h3 class="card-title text-dark text-center"><strong>Pan Number To Pan Details Find Instant</strong></h3>
                            
                            <!-- Powered By Section -->
                            <div class="text-center mt-2 mb-3">
                                <div style="background:#f8f9fa;padding:8px;border-radius:6px;">
                                    <small style="font-weight:600;">
                                        ⚡ Powered by <span style="color:#0d6efd;">APIADDA.IN</span>
                                    </small>
                                </div>
                            </div>
                            
                        </div>
                        <div class="card-body">
                            <a href="Pan_Advance_flex" class="btn btn-dark w-100 mb-3">Pan Advance Instant Pan e-PAN Pdf Download</a>
                            <form action="" method="post" id="pan_verification" novalidate>
                                <div class="mb-3">
                                    <label for="pan_no" class="form-label">Pan Number</label>
                                    <input type="text" required class="form-control" name="pan_no" id="pan_no" placeholder="Enter Pan Number" maxlength="10" pattern="[A-Za-z]{5}[0-9]{4}[A-Za-z]{1}" value="<?= isset($_POST['pan_no']) ? htmlspecialchars($_POST['pan_no']) : '' ?>">
                                </div>
                                <button type="submit" name="verify_pan" class="btn btn-primary w-100"><i class="fa fa-check-circle"></i> Verify PAN</button>

                                <div class="mt-3 text-center fee-container">
                                    <h5 class="text-warning">
                                        Application Fee: 
                                        <?php
                                        $price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT price FROM pricing WHERE service_name='pan_details_verify' LIMIT 1"));
                                        echo "₹" . htmlspecialchars($price['price'] ?? '0');
                                        ?>
                                    </h5>
                                </div>

                                <?php if ($error_message): ?>
                                    <div class="alert alert-danger mt-3" role="alert">
                                        <?= htmlspecialchars($error_message); ?>
                                    </div>
                                <?php endif; ?>
                            </form>
                        </div>
                    </div>
                </div>

               <!-- Right Side: PAN Details -->
<div class="col-lg-6">
    <?php if (!empty($resdata) && $resdata['statusCode'] == 100): ?>
        <div class="card" style="background-color: #f8f9fa;" id="printSection">
            <div class="card-body">
                <h5 class="mb-3">PAN Details</h5>
                <table class="table table-bordered table-striped">
                    <tbody>
                        <?php if (!empty($resdata['pan_no'])): ?>
                            <tr><th>Pan Number</th><td><?= htmlspecialchars($resdata['pan_no']); ?></td></tr>
                        <?php endif; ?>
                        <?php if (!empty($resdata['name'])): ?>
                            <tr><th>Name</th><td><?= htmlspecialchars($resdata['name']); ?></td></tr>
                        <?php endif; ?>
                        <?php if (!empty($resdata['fathername'])): ?>
                            <tr><th>Father Name</th><td><?= htmlspecialchars($resdata['fathername']); ?></td></tr>
                        <?php endif; ?>
                        <?php if (!empty($resdata['dob'])): ?>
                            <tr><th>Date of Birth</th><td><?= htmlspecialchars($resdata['dob']); ?></td></tr>
                        <?php endif; ?>
                        <?php if (!empty($resdata['gender'])): ?>
                            <tr><th>Gender</th><td><?= htmlspecialchars($resdata['gender']); ?></td></tr>
                        <?php endif; ?>
                        <?php if (isset($resdata['aadhaarLinked']) && $resdata['aadhaarLinked'] !== ''): ?>
                            <tr><th>Aadhaar Status</th><td><?= htmlspecialchars($resdata['aadhaarLinked']); ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                <div class="text-end">
                    <button class="btn btn-primary" onclick="printBill()">🖨️ Print</button>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

            </div>
        </div>
    </div>
</div>
<?php if (!empty($resdata) && $resdata['statusCode'] == 100): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            Swal.fire({
                icon: 'success',
                title: 'PAN detail fetched successfully',
                text: '<?= htmlspecialchars($resdata['pan_no']); ?>',
                confirmButtonText: 'OK'
            });
        });
    </script>
<?php endif; ?>


<script>
function printBill() {
    var printContents = document.getElementById('printSection').innerHTML;
    var originalContents = document.body.innerHTML;

    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
    
}
</script>

    <script src="../template/ahkweb/assets/js/bootstrap.bundle.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/js/app.js"></script>
    <script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
</body>
</html>