<?php
/**
 * SAMPLE: How to integrate payment with search functionality
 * 
 * This file shows how to modify your search code to deduct credits
 */

// ============================================
// 1. MOBILE SEARCH WITH PAYMENT
// ============================================

require_once(__DIR__ . '/config/config.php');
require_once(__DIR__ . '/classes/Database.php');
require_once(__DIR__ . '/classes/Payment.php');

session_start();

// Check user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$userId = $_SESSION['user_id'];
$db = Database::getInstance();
$payment = new Payment();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mobile_number'])) {
    $mobileNumber = $_POST['mobile_number'];
    $searchCost = MOBILE_SEARCH_COST; // From config.php (usually 1)
    
    // ============= STEP 1: Check Balance =============
    $balance = $payment->getBalance($userId);
    
    if ($balance < $searchCost) {
        $_SESSION['error'] = 'Insufficient balance. Please buy credits.';
        header('Location: user/payments.php');
        exit;
    }
    
    // ============= STEP 2: Deduct Credits =============
    $result = $payment->deductCredits($userId, $searchCost, 'Mobile Search - ' . $mobileNumber);
    
    if (!$result['status']) {
        $_SESSION['error'] = $result['message'];
        header('Location: user/dashboard.php');
        exit;
    }
    
    // ============= STEP 3: Perform Search =============
    try {
        // Call your mobile API
        $mobileApiUrl = MOBILE_API_URL . urlencode($mobileNumber);
        $response = file_get_contents($mobileApiUrl);
        $data = json_decode($response, true);
        
        // ============= STEP 4: Save to Database =============
        $searchData = [
            'user_id' => $userId,
            'type' => 'mobile',
            'query' => $mobileNumber,
            'response_json' => $response,
            'cost' => $searchCost,
            'status' => $data ? 'success' : 'failed',
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $db->insert('search_logs', $searchData);
        
        // ============= STEP 5: Return Results =============
        if ($data) {
            $_SESSION['search_result'] = $data;
            $_SESSION['success'] = 'Search completed successfully!';
        } else {
            $_SESSION['error'] = 'Search failed. Please try again.';
        }
        
    } catch (Exception $e) {
        error_log('Search Error: ' . $e->getMessage());
        $_SESSION['error'] = 'An error occurred during search.';
        
        // Refund credits if search failed
        $payment->addCredits($userId, $searchCost, 'Refund - Search Failed');
    }
    
    header('Location: user/dashboard.php');
    exit;
}

?>

<?php
/**
 * ============================================
 * 2. AADHAAR SEARCH WITH PAYMENT
 * ============================================
 */

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['aadhaar_number'])) {
    $aadhaarNumber = $_POST['aadhaar_number'];
    $searchCost = AADHAAR_SEARCH_COST; // From config.php (usually 5)
    
    $balance = $payment->getBalance($userId);
    
    if ($balance < $searchCost) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Insufficient balance',
            'redirectTo' => 'user/payments.php'
        ]);
        exit;
    }
    
    // Deduct credits
    $result = $payment->deductCredits($userId, $searchCost, 'Aadhaar Search');
    
    if (!$result['status']) {
        echo json_encode([
            'status' => 'error',
            'message' => $result['message']
        ]);
        exit;
    }
    
    // Perform search
    try {
        $aadhaarApiUrl = AADHAAR_API_URL . urlencode($aadhaarNumber);
        $response = file_get_contents($aadhaarApiUrl);
        $data = json_decode($response, true);
        
        $db->insert('search_logs', [
            'user_id' => $userId,
            'type' => 'aadhaar',
            'query' => substr($aadhaarNumber, -4), // Store only last 4 digits
            'response_json' => $response,
            'cost' => $searchCost,
            'status' => $data ? 'success' : 'failed',
            'created_at' => date('Y-m-d H:i:s')
        ]);
        
        echo json_encode([
            'status' => 'success',
            'data' => $data,
            'message' => 'Search completed'
        ]);
        
    } catch (Exception $e) {
        // Refund on error
        $payment->addCredits($userId, $searchCost, 'Refund - Aadhaar Search Failed');
        
        echo json_encode([
            'status' => 'error',
            'message' => 'Search failed: ' . $e->getMessage()
        ]);
    }
    
    exit;
}

?>

<?php
/**
 * ============================================
 * 3. DASHBOARD WIDGET (Show Balance)
 * ============================================
 * 
 * Add this to your dashboard page:
 */

$payment = new Payment();
$currentBalance = $payment->getBalance($_SESSION['user_id']);
$lastTransactions = $payment->getTransactionHistory($_SESSION['user_id'], 5);

?>

<!-- Add to user/dashboard.php -->
<div class="sidebar-widget">
    <h5>💳 Wallet Balance</h5>
    <div class="balance-display">
        <h3>₹<?php echo number_format($currentBalance, 2); ?></h3>
        <p class="text-muted">Available Credits</p>
    </div>
    
    <?php if ($currentBalance < 5): ?>
    <a href="payments.php" class="btn btn-primary btn-block">
        <i class="fas fa-shopping-cart"></i> Buy Credits
    </a>
    <?php endif; ?>
    
    <div class="recent-transactions">
        <h6>Recent Transactions</h6>
        <ul class="list-unstyled">
            <?php foreach ($lastTransactions as $txn): ?>
            <li>
                <span class="badge badge-<?php echo $txn['type']; ?>">
                    <?php echo ucfirst($txn['type']); ?>
                </span>
                <strong><?php echo $txn['type'] === 'credit' ? '+' : '-'; ?>₹<?php echo $txn['amount']; ?></strong>
                <br>
                <small class="text-muted"><?php echo $txn['description']; ?></small>
            </li>
            <?php endforeach; ?>
        </ul>
    </div>
</div>

<?php
/**
 * ============================================
 * 4. ADMIN DASHBOARD STATS
 * ============================================
 * 
 * Add this to admin dashboard:
 */

$db = Database::getInstance();

$stats = [
    'total_revenue' => $db->fetch(
        'SELECT SUM(amount) as total FROM payment_orders WHERE status = "completed"'
    )['total'] ?? 0,
    
    'total_searches' => $db->fetch(
        'SELECT COUNT(*) as total FROM search_logs WHERE status = "success"'
    )['total'] ?? 0,
    
    'total_credits_sold' => $db->fetch(
        'SELECT SUM(amount) as total FROM payment_orders WHERE status = "completed"'
    )['total'] ?? 0,
    
    'pending_payments' => $db->fetch(
        'SELECT COUNT(*) as total FROM payment_orders WHERE status = "pending"'
    )['total'] ?? 0
];

?>

<!-- Display in admin dashboard -->
<div class="stat-card">
    <h6>Total Revenue</h6>
    <h3>₹<?php echo number_format($stats['total_revenue'], 2); ?></h3>
</div>

<div class="stat-card">
    <h6>Credits Sold</h6>
    <h3><?php echo $stats['total_searches']; ?></h3>
</div>

<?php
/**
 * ============================================
 * 5. ERROR HANDLING & MESSAGES
 * ============================================
 */

// In your page, display session messages:
if (isset($_SESSION['error'])) {
    echo '<div class="alert alert-danger">' . htmlspecialchars($_SESSION['error']) . '</div>';
    unset($_SESSION['error']);
}

if (isset($_SESSION['success'])) {
    echo '<div class="alert alert-success">' . htmlspecialchars($_SESSION['success']) . '</div>';
    unset($_SESSION['success']);
}

?>

<?php
/**
 * ============================================
 * IMPLEMENTATION CHECKLIST
 * ============================================
 * 
 * [ ] 1. Include Payment class in your search page
 * [ ] 2. Check user is logged in
 * [ ] 3. Get user balance before search
 * [ ] 4. Check if balance >= search cost
 * [ ] 5. Deduct credits using $payment->deductCredits()
 * [ ] 6. If deduction fails, redirect to payments page
 * [ ] 7. Perform API search
 * [ ] 8. Save search log to database
 * [ ] 9. On error, refund credits to user
 * [ ] 10. Show balance widget in dashboard
 * [ ] 11. Update admin statistics
 * [ ] 12. Test end-to-end payment + search flow
 * 
 * ============================================
 */

?>
