<?php
ob_start();
// 1. Session & Auth Control
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

require_once('../titancore/titanconfig.php');
require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];
$u_name = $_SESSION['user_name'] ?? 'User';

$swal_msg = "";
$successData = null;

// 2. Pricing Fetch
$price_check = $conn->query("SELECT price FROM pricing WHERE service_name = 'pan_details_verify'");
$service_price = ($price_check && $price_check->num_rows > 0) ? $price_check->fetch_assoc()['price'] : 2.00;

// 3. API Config Fetch from TitanPayment
$api_settings = $conn->query("SELECT titanurl, titan_api_key FROM TitanPayment WHERE id = 1")->fetch_assoc();
$TitanApi_Url = $api_settings['titanurl'] ?? '';
$api_key = $api_settings['titan_api_key'] ?? '';

if (empty($TitanApi_Url) || empty($api_key)) {
    echo "<script>alert('System Error: TitanPayment API URL or Key is not configured. Contact Admin.'); window.location.href='titanhome.php';</script>";
    exit();
}

// 4. Handle Verification Logic
if (isset($_POST['verify_btn'])) {
    $input_pan = strtoupper(mysqli_real_escape_string($conn, preg_replace('/[^A-Z0-9]/', '', $_POST['pan_no'])));
    
    // Wallet Check
    $user_wallet = $conn->query("SELECT wallet FROM users WHERE id = '$uid'")->fetch_assoc()['wallet'];
    
    if (!preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]$/', $input_pan)) {
        $swal_msg = "Swal.fire('Invalid Input!', 'Please enter a valid 10-character PAN number.', 'error');";
    } elseif ($user_wallet < $service_price) {
        $swal_msg = "Swal.fire('Low Balance!', 'You need ₹$service_price in your wallet to use this service.', 'warning');";
    } else {
        // Build API URL dynamically matching your system config
    $endpoint = "https://www.maxxapi.site/S1pandetails?api_key=2311e32848008d9eabd5fdb2db10b19e0614e81e5fd206743357469c6ec1ebd2&panno=" . urlencode($input_pan);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $api_response = curl_exec($ch);
        curl_close($ch);
        
        if ($api_response) {
            $data = json_decode($api_response, true);
            
            // Check status at root or inside result array
            $status = $data['status'] ?? ($data['result']['status'] ?? '');
            
            if ($status == '200' || $status == '100' || $status == 'success') {
                
                // Flexible mapping to support nested or flat layout structures safely
                $source = (isset($data['name'])) ? $data : ($data['result'] ?? []);
                
                $name   = strtoupper(mysqli_real_escape_string($conn, $source['name'] ?? ''));
                $father = strtoupper(mysqli_real_escape_string($conn, $source['father'] ?? $source['fathername'] ?? ''));
                $gender = strtoupper(mysqli_real_escape_string($conn, $source['gender'] ?? ''));
                $dob    = mysqli_real_escape_string($conn, $source['dob'] ?? '');
                $application_no = mysqli_real_escape_string($conn, $source['application_no'] ?? '');
                $date_time = date('Y-m-d H:i:s');
                
                // Deduct Wallet Balance
                $new_balance = $user_wallet - $service_price;
                $conn->query("UPDATE users SET wallet = '$new_balance' WHERE id = '$uid'");
                
                // Save to History Table (pan_verify_hkb)
                $insert_history = "INSERT INTO pan_verify_hkb (name, fathername, gender, dob, pan, username, date) 
                                   VALUES ('$name', '$father', '$gender', '$dob', '$input_pan', '$u_name', '$date_time')";
                
                // Save to Wallet Transaction Log
                $insert_log = "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) 
                               VALUES ('$u_name', '$service_price', '$new_balance', 'PAN Verification', '1', 'Debit')";
                
                if ($conn->query($insert_history) && $conn->query($insert_log)) {
                    $successData = [
                        "pan_no" => $input_pan,
                        "name" => $name,
                        "father" => $father,
                        "dob" => $dob,
                        "gender" => $gender,
                        "application_no" => $application_no
                    ];
                } else {
                    $swal_msg = "Swal.fire('Database Error!', 'Verified successfully but history logging failed.', 'error');";
                }
                
            } else {
                $err = $data['message'] ?? ($data['result']['message'] ?? 'Verification failed or invalid API response.');
                $swal_msg = "Swal.fire('Failed!', '" . addslashes($err) . "', 'error');";
            }
        } else {
            $swal_msg = "Swal.fire('Server Error!', 'Could not connect to the Master API Server.', 'error');";
        }
    }
}

// Fetch Logged Records
$history = $conn->query("SELECT * FROM pan_verify_hkb WHERE username='$u_name' ORDER BY id DESC");
?>

<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">

<div class="row mb-3">
    <div class="col">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <div class="icon-item bg-info-subtle shadow-none me-3">
                        <span class="fas fa-check-circle text-info fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-info fs-10 mb-0">Identity Services</h6>
                        <h4 class="text-primary fw-bold mb-0">PAN <span class="text-info fw-medium">Verify</span></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 justify-content-center">
    <div class="col-lg-4">
        <div class="card h-100">
            <div class="card-header bg-light border-bottom">
                <h5 class="mb-0 text-primary fw-bold text-center"><i class="fas fa-fingerprint me-2"></i>Verify Details</h5>
            </div>
            <div class="card-body bg-body-tertiary p-4">
                <div class="alert alert-info border-0 d-flex align-items-center mb-4">
                    <i class="fas fa-rupee-sign fs-3 me-3 text-info"></i>
                    <p class="mb-0 fs-11">Verification charge: <strong>₹<?php echo number_format($service_price, 2); ?></strong> will be deducted from your wallet upon success.</p>
                </div>
                
                <form method="POST">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-900">PAN Card Number <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="fas fa-id-card"></i></span>
                            <input type="text" class="form-control shadow-none text-center text-uppercase" name="pan_no" placeholder="ABCDE1234F" maxlength="10" oninput="this.value=this.value.toUpperCase().replace(/[^A-Z0-9]/g,'')" required>
                        </div>
                    </div>
                    
                    <button class="btn btn-info w-100 fw-bold shadow-none py-2" type="submit" name="verify_btn">
                        <i class="fas fa-search me-2"></i> Verify PAN Details
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card h-100">
            <div class="card-header bg-light border-bottom">
                <h5 class="mb-0 text-primary fw-bold"><i class="fas fa-list me-2"></i>Verification History</h5>
            </div>
            <div class="card-body p-3">
                <div class="table-responsive">
                    <table id="panTable" class="table table-bordered table-hover text-center align-middle m-0">
                        <thead class="table-dark">
                            <tr>
                                <th>ID</th>
                                <th>Date</th>
                                <th>PAN</th>
                                <th>Name</th>
                                <th>Father</th>
                                <th>DOB</th>
                                <th>Gender</th>
                                <th>Slip</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($r = $history->fetch_assoc()) { ?>
                            <tr>
                                <td>#<?= $r['id'] ?></td>
                                <td><?= date('d M Y h:i A', strtotime($r['date'])) ?></td>
                                <td class="fw-bold text-primary"><?= htmlspecialchars($r['pan']) ?></td>
                                <td><?= htmlspecialchars($r['name']) ?></td>
                                <td><?= htmlspecialchars($r['fathername']) ?></td>
                                <td><?= htmlspecialchars($r['dob']) ?></td>
                                <td><?= htmlspecialchars($r['gender']) ?></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-info shadow-none" onclick='viewSlip(<?= json_encode($r) ?>)'>
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function() {
        $('#panTable').DataTable({
            "order": [[ 0, "desc" ]]
        });
    });

    <?php echo $swal_msg; ?>

    <?php if ($successData) { ?>
        Swal.fire({
            icon: 'success',
            title: 'PAN Verified Successfully',
            html: `
            <div class="text-start p-2" style="font-size: 14px;">
                <p class="mb-1"><b>PAN No :</b> <?= $successData['pan_no'] ?></p>
                <p class="mb-1"><b>Name :</b> <?= $successData['name'] ?></p>
                <p class="mb-1"><b>Father :</b> <?= $successData['father'] ?></p>
                <p class="mb-1"><b>DOB :</b> <?= $successData['dob'] ?></p>
                <p class="mb-1"><b>Gender :</b> <?= $successData['gender'] ?></p>
                <p class="mb-0"><b>Application No :</b> <?= $successData['application_no'] ?></p>
            </div>`
        });
    <?php } ?>

    function viewSlip(d){
        Swal.fire({
            title: 'PAN Verification Slip',
            html: `
            <div class="text-start p-2" style="font-size: 14px;">
                <p class="mb-1"><b>PAN :</b> ${d.pan}</p>
                <p class="mb-1"><b>Name :</b> ${d.name}</p>
                <p class="mb-1"><b>Father :</b> ${d.fathername}</p>
                <p class="mb-1"><b>DOB :</b> ${d.dob}</p>
                <p class="mb-1"><b>Gender :</b> ${d.gender}</p>
                <p class="mb-0"><b>Date :</b> ${d.date}</p>
            </div>`,
            showCancelButton: true,
            confirmButtonText: '<i class="fas fa-print me-1"></i> Print',
            cancelButtonText: 'Close'
        }).then((result)=>{
            if(result.isConfirmed){
                window.print();
            }
        });
    }
</script>

<?php 
require_once('../titancore/TitanFooter.php'); 
ob_end_flush();
?>