<?php
require_once("../includes/session.php");
require_once("../includes/config.php");

if (!in_array($udata['type'], ['Master Distributor', 'Distributor', 'Retailer', 'admin'])) {
    require_once("404.php");
    exit;
}

if (!isset($udata['aadhaar_lookup_service']) || $udata['aadhaar_lookup_service'] != 'YES') {
    echo '<script>
        Swal.fire("Access Denied", "Aadhaar Lookup service not active!", "info");
        setTimeout(function(){ window.location="index.php"; }, 2000);
    </script>';
    exit;
}

$result_data = null;
$error_message = '';
$sim_list = [];

if (isset($_POST['search'])) {
    $aadhaar_number = trim($_POST['aadhaar_number']);
    
    if (empty($aadhaar_number)) {
        $error_message = 'Please enter Aadhaar number!';
    } else if (!preg_match('/^[0-9]{12}$/', $aadhaar_number)) {
        $error_message = 'Enter valid 12-digit Aadhaar number!';
    } else {
        $amount = floatval($udata['aadhaar_lookup_fee'] ?? 50);
        $old_balance = floatval($udata['balance'] ?? 0);
        
        if ($old_balance < $amount) {
            $error_message = 'Insufficient Balance! Need: ₹' . $amount;
        } else {
            // Call API (Replace with your actual API)
            $api_url = "https://yourapi.com/aadhaar-lookup?aadhaar=" . $aadhaar_number . "&api_key=" . $flexsecure_key;
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $api_url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 15,
                CURLOPT_SSL_VERIFYPEER => false
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode == 200) {
                $apiData = json_decode($response, true);
                
                if (isset($apiData['status']) && $apiData['status'] == 'success') {
                    // Deduct balance
                    $new_balance = $old_balance - $amount;
                    mysqli_query($ahk_conn, "UPDATE users SET balance = $new_balance WHERE phone = '{$udata['phone']}'");
                    
                    // Insert transaction
                    $simCount = isset($apiData['data']['sim_list']) ? count($apiData['data']['sim_list']) : 0;
                    
                    $reportSql = "INSERT INTO reports (
                        site_id, user_id, username, name, operator, parent_id, order_id, service, type,
                        account_number, app_type, amount, main_amount, old_balance, new_balance,
                        txn_id, ref_id, description, date_time, status
                    ) VALUES (
                        1, '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['type']}', 0,
                        'AL" . time() . "', 'Aadhaar Lookup', 'Debit', 'XXXX-XXXX-" . substr($aadhaar_number,-4) . "', 'Lookup',
                        $amount, $amount, $old_balance, $new_balance, 'AL" . time() . "', '$aadhaar_number',
                        'Aadhaar Lookup - Rs.$amount debit', NOW(), 'Success'
                    )";
                    mysqli_query($ahk_conn, $reportSql);
                    
                    // Insert lookup history
                    $lookupSql = "INSERT INTO lookup_history (
                        username, user_id, lookup_type, search_input, result_data, sim_count,
                        fee_charged, status, api_response, date_time
                    ) VALUES (
                        '{$udata['name']}', '{$udata['phone']}', 'aadhaar', '$aadhaar_number',
                        '" . mysqli_real_escape_string($ahk_conn, json_encode($apiData['data'])) . "', $simCount,
                        $amount, 'Success', '" . mysqli_real_escape_string($ahk_conn, $response) . "', NOW()
                    )";
                    mysqli_query($ahk_conn, $lookupSql);
                    
                    $result_data = $apiData['data'];
                    $sim_list = $apiData['data']['sim_list'] ?? [];
                } else {
                    $error_message = $apiData['message'] ?? 'API Error!';
                }
            } else {
                $error_message = 'API connection failed!';
            }
        }
    }
}

include('../template/ahkweb/header.php');
?>

<style>
.result-card {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    color: white;
    border-radius: 15px;
    padding: 25px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
.sim-card {
    background: white;
    color: #333;
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 10px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}
</style>

<div class="page-wrapper">
    <div class="page-content">
        <div class="row">
            <div class="col-md-5 mb-3">
                <div class="card">
                    <div class="card-header text-white py-2" style="background:linear-gradient(135deg,#f093fb,#f5576c);">
                        <span><i class="fas fa-fingerprint"></i> Aadhaar SIM Lookup</span>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success py-2 text-center mb-3">
                            <strong>⚡ INSTANT - All Linked SIMs</strong>
                        </div>
                        
                        <?php if($error_message): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle"></i> <?php echo $error_message; ?>
                        </div>
                        <?php endif; ?>
                        
                        <form method="POST">
                            <div class="mb-3">
                                <label><strong>Aadhaar Number <span class="text-danger">*</span></strong></label>
                                <input type="text" name="aadhaar_number" class="form-control" placeholder="12-digit Aadhaar" 
                                       maxlength="12" oninput="this.value=this.value.replace(/[^0-9]/g,'')" required>
                            </div>
                            
                            <div class="d-flex justify-content-between">
                                <button type="button" class="btn btn-secondary">₹<?php echo number_format($udata['aadhaar_lookup_fee'] ?? 50, 2); ?></button>
                                <button type="submit" name="search" class="btn text-white" style="background:linear-gradient(135deg,#f093fb,#f5576c);">
                                    <i class="fas fa-search"></i> Search Now
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-7 mb-3">
                <?php if($result_data): ?>
                <div class="result-card">
                    <h4 class="mb-3"><i class="fas fa-check-circle"></i> Linked SIM Cards (<?php echo count($sim_list); ?>)</h4>
                    
                    <div class="mb-3" style="background:rgba(255,255,255,0.2);padding:12px;border-radius:8px;">
                        <strong>🆔 Aadhaar:</strong> XXXX-XXXX-<?php echo substr($_POST['aadhaar_number'], -4); ?>
                    </div>
                    
                    <?php if(!empty($sim_list)): ?>
                        <?php foreach($sim_list as $index => $sim): ?>
                        <div class="sim-card">
                            <h6><i class="fas fa-sim-card"></i> SIM #<?php echo ($index + 1); ?></h6>
                            <div class="row">
                                <div class="col-6">
                                    <small class="text-muted">Mobile Number</small>
                                    <div><strong><?php echo $sim['mobile'] ?? 'N/A'; ?></strong></div>
                                </div>
                                <div class="col-6">
                                    <small class="text-muted">Operator</small>
                                    <div><strong><?php echo $sim['operator'] ?? 'N/A'; ?></strong></div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="alert alert-warning">No SIM cards linked to this Aadhaar!</div>
                    <?php endif; ?>
                </div>
                <?php else: ?>
                <div class="card">
                    <div class="card-body text-center py-5">
                        <i class="fas fa-search fa-4x text-muted mb-3"></i>
                        <h5 class="text-muted">Enter Aadhaar Number to Search</h5>
                        <p class="text-muted">Find all SIM cards linked with Aadhaar!</p>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include('../admin/footers.php'); ?>