<?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 from pricing architecture
$price_check = $conn->query("SELECT price FROM pricing WHERE service_name = 'mobile_to_pan'");
$service_price = ($price_check && $price_check->num_rows > 0) ? $price_check->fetch_assoc()['price'] : 0.00;

// 3. API Config Fetch from TitanPayment System
$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['find_pan'])) {
    $cust_name = trim($_POST['cust_name']);
    $mobile    = preg_replace('/[^0-9]/', '', $_POST['mobile']);
    
    // Wallet Check
    $user_wallet = $conn->query("SELECT wallet FROM users WHERE id = '$uid'")->fetch_assoc()['wallet'];
    
    if (empty($cust_name) || strlen($mobile) !== 10) {
        $swal_msg = "Swal.fire('Invalid Input!', 'Please enter a valid Name and 10-digit Mobile 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 matching vendor architecture
      
        
         $endpoint = "https://www.maxxapi.site/S1mm2p?api_key=demooo&name=" . urlencode($cust_name) . "&mobile=" . urlencode($mobile);
        $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);
            
            // Flexible layout structural checks
            $status = $data['status'] ?? ($data['result']['status'] ?? '');
            
            if ($status == '200' || $status == '100' || strtolower($status) === 'success') {
                $source = (isset($data['pan_no']) || isset($data['pan'])) ? $data : ($data['result'] ?? []);
                
                $pan_no   = strtoupper(mysqli_real_escape_string($conn, $source['pan_no'] ?? $source['pan'] ?? ''));
                $rname    = mysqli_real_escape_string($conn, $source['name'] ?? $cust_name);
                $rmobile  = mysqli_real_escape_string($conn, $source['mobile'] ?? $mobile);
                $date_time = date('Y-m-d H:i:s');
                
                try {
                    $conn->begin_transaction();
                    
                    // Deduct Balance Securely
                    $new_balance = $user_wallet - $service_price;
                    $conn->query("UPDATE users SET wallet = '$new_balance' WHERE id = '$uid'");
                    
                    // Save to History Table (mobile_pan_history)
                    $insert_history = "INSERT INTO mobile_pan_history (name, mobile, pan, username, date) 
                                       VALUES ('$rname', '$rmobile', '$pan_no', '$u_name', '$date_time')";
                    $conn->query($insert_history);
                    
                    // Save Audit Footprints (wallethistory)
                    $insert_log = "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) 
                                   VALUES ('$u_name', '$service_price', '$new_balance', 'Mobile to PAN', '1', 'Debit')";
                    $conn->query($insert_log);
                    
                    $conn->commit();
                    
                    $successData = [
                        "name" => $rname,
                        "mobile" => $rmobile,
                        "pan_no" => $pan_no
                    ];
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $swal_msg = "Swal.fire('Database Error!', 'Process aborted due to transactional rollback.', '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 Account Transaction History logs
$history = $conn->query("SELECT * FROM mobile_pan_history 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">Mobile To <span class="text-info fw-medium">PAN</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-search-panel me-2"></i>Find PAN 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-3">
                        <label class="form-label fw-bold text-900">Customer Full Name <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="fas fa-user"></i></span>
                            <input type="text" class="form-control shadow-none" name="cust_name" placeholder="Enter Full Name" required>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold text-900">Mobile Number <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="fas fa-phone"></i></span>
                            <input type="text" class="form-control shadow-none text-center" name="mobile" placeholder="Enter 10-Digit Mobile" maxlength="10" pattern="\d{10}" oninput="this.value=this.value.replace(/\D/g,'')" required>
                        </div>
                    </div>
                    
                    <button class="btn btn-info w-100 fw-bold shadow-none py-2" type="submit" name="find_pan">
                        <i class="fas fa-search me-2"></i> Search 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>Search History</h5>
            </div>
            <div class="card-body p-3">
                <div class="table-responsive">
                    <table id="mobilePanTable" class="table table-bordered table-hover text-center align-middle m-0">
                        <thead class="table-dark">
                            <tr>
                                <th>ID</th>
                                <th>Date</th>
                                <th>Name</th>
                                <th>Mobile</th>
                                <th>PAN Number</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><?= htmlspecialchars($r['name']) ?></td>
                                <td><?= htmlspecialchars($r['mobile']) ?></td>
                                <td class="fw-bold text-primary"><?= htmlspecialchars($r['pan']) ?></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() {
        $('#mobilePanTable').DataTable({
            "order": [[ 0, "desc" ]]
        });
    });

    <?php echo $swal_msg; ?>

    <?php if ($successData) { ?>
        Swal.fire({
            icon: 'success',
            title: 'PAN Found Successfully',
            html: `
            <div class="text-start p-2" style="font-size: 14px;">
                <p class="mb-1"><b>Name :</b> <?= $successData['name'] ?></p>
                <p class="mb-1"><b>Mobile :</b> <?= $successData['mobile'] ?></p>
                <p class="mb-0 text-success"><b>PAN Number :</b> <strong><?= $successData['pan_no'] ?></strong></p>
            </div>`
        });
    <?php } ?>

    function viewSlip(d){
        Swal.fire({
            title: 'Mobile to PAN Receipt',
            html: `
            <div class="text-start p-2" style="font-size: 14px;">
                <p class="mb-1"><b>Customer Name :</b> ${d.name}</p>
                <p class="mb-1"><b>Mobile Number :</b> ${d.mobile}</p>
                <p class="mb-1 text-primary"><b>PAN Number :</b> <strong>${d.pan}</strong></p>
                <p class="mb-0"><b>Date/Time :</b> ${d.date}</p>
            </div>`,
            showCancelButton: true,
            confirmButtonText: '<i class="fas fa-print me-1"></i> Print Slip',
            cancelButtonText: 'Close'
        }).then((result)=>{
            if(result.isConfirmed){
                window.print();
            }
        });
    }
</script>

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