<?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['mobile_lookup_service']) || $udata['mobile_lookup_service'] != 'YES') {
    echo '<script>
        Swal.fire("Access Denied", "Mobile Lookup service not active!", "info");
        setTimeout(function(){ window.location="index.php"; }, 2000);
    </script>';
    exit;
}

$result_data = null;
$error_message = '';

if (isset($_POST['search'])) {
    $mobile_number = trim($_POST['mobile_number']);
    
    if (empty($mobile_number)) {
        $error_message = 'Please enter mobile number!';
    } else if (!preg_match('/^[0-9]{10}$/', $mobile_number)) {
        $error_message = 'Enter valid 10-digit mobile number!';
    } else {
        $amount = floatval($udata['mobile_lookup_fee'] ?? 10);
        $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/mobile-lookup?mobile=" . $mobile_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
                    $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,
                        'ML" . time() . "', 'Mobile Lookup', 'Debit', '$mobile_number', 'Lookup',
                        $amount, $amount, $old_balance, $new_balance, 'ML" . time() . "', '$mobile_number',
                        'Mobile 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']}', 'mobile', '$mobile_number',
                        '" . mysqli_real_escape_string($ahk_conn, json_encode($apiData['data'])) . "', 1,
                        $amount, 'Success', '" . mysqli_real_escape_string($ahk_conn, $response) . "', NOW()
                    )";
                    mysqli_query($ahk_conn, $lookupSql);
                    
                    $result_data = $apiData['data'];
                } 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, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px;
    padding: 25px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
.result-item {
    background: rgba(255,255,255,0.1);
    padding: 12px;
    border-radius: 8px;
    margin-bottom: 10px;
}
</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 bg-purple text-white py-2">
                        <span><i class="fas fa-mobile-alt"></i> Mobile Number Lookup</span>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success py-2 text-center mb-3">
                            <strong>⚡ INSTANT RESULT</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>Mobile Number <span class="text-danger">*</span></strong></label>
                                <input type="text" name="mobile_number" class="form-control" placeholder="10-digit mobile" 
                                       maxlength="10" 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['mobile_lookup_fee'] ?? 10, 2); ?></button>
                                <button type="submit" name="search" class="btn btn-purple">
                                    <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> SIM Owner Details</h4>
                    
                    <div class="result-item">
                        <strong>📱 Mobile Number:</strong><br>
                        <?php echo $result_data['mobile'] ?? 'N/A'; ?>
                    </div>
                    
                    <div class="result-item">
                        <strong>👤 Subscriber Name:</strong><br>
                        <?php echo $result_data['subscriber_name'] ?? 'N/A'; ?>
                    </div>
                    
                    <div class="result-item">
                        <strong>📡 Operator:</strong><br>
                        <?php echo $result_data['operator'] ?? 'N/A'; ?>
                    </div>
                    
                    <div class="result-item">
                        <strong>🆔 ID Number:</strong><br>
                        <?php echo $result_data['id_number'] ?? 'N/A'; ?>
                    </div>
                    
                    <div class="result-item">
                        <strong>📍 Address:</strong><br>
                        <?php echo $result_data['address'] ?? 'N/A'; ?>
                    </div>
                </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 Mobile Number to Search</h5>
                        <p class="text-muted">Instant SIM owner details in seconds!</p>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
.bg-purple { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important; }
.btn-purple { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; }
.btn-purple:hover { background: linear-gradient(135deg, #764ba2 0%, #667eea 100%); color: white; }
</style>

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