<?php
/**
 * QUICK REFERENCE: Payment Class Methods
 * 
 * Usage:
 * $payment = new Payment();
 * 
 * All examples assume $userId is set to the user ID
 */

// ============================================
// 1. GET USER WALLET BALANCE
// ============================================
$balance = $payment->getBalance($userId);
// Returns: float (e.g., 100.50)

echo "Current Balance: ₹" . $balance;


// ============================================
// 2. ADD CREDITS TO WALLET
// ============================================
$payment->addCredits($userId, 50, 'Bonus Credits');
// Parameters:
// - $userId (int): User ID
// - $amount (float): Amount to add
// - $description (string): Reason for credit

// Returns: true on success


// ============================================
// 3. DEDUCT CREDITS FROM WALLET
// ============================================
$result = $payment->deductCredits($userId, 5, 'Aadhaar Search');
// Parameters:
// - $userId (int): User ID
// - $amount (float): Amount to deduct
// - $description (string): Reason for debit

// Returns: ['status' => bool, 'message' => string]

if (!$result['status']) {
    echo "Error: " . $result['message']; // "Insufficient balance"
}


// ============================================
// 4. CREATE PAYMENT ORDER
// ============================================
$orderId = $payment->createPaymentOrder($userId, 250, 'Premium');
// Parameters:
// - $userId (int): User ID
// - $amount (float): Order amount
// - $packageName (string): Package name (optional)

// Returns: string (order ID) or false


// ============================================
// 5. CONFIRM/VERIFY PAYMENT
// ============================================
$result = $payment->confirmPayment($orderId, 'TRANS123456', 'razorpay');
// Parameters:
// - $orderId (string): Payment order ID
// - $transactionId (string): Payment transaction ID
// - $paymentMethod (string): 'razorpay', 'manual_upi', 'manual_approval'

// Returns: ['status' => bool, 'message' => string]


// ============================================
// 6. GET TRANSACTION HISTORY
// ============================================
$transactions = $payment->getTransactionHistory($userId, 10);
// Parameters:
// - $userId (int): User ID
// - $limit (int): Number of records to fetch (default: 20)

// Returns: array of transactions
// Each transaction contains:
// [
//   'id' => 1,
//   'user_id' => 5,
//   'type' => 'credit' or 'debit',
//   'amount' => 100.00,
//   'description' => 'Mobile Search',
//   'balance_after' => 450.00,
//   'created_at' => '2025-11-19 10:30:45'
// ]


// ============================================
// 7. GET PAYMENT PACKAGES
// ============================================
$packages = $payment->getPaymentPackages();
// Returns: array of packages
// [
//   [
//     'id' => 1,
//     'name' => 'Basic',
//     'credits' => 10,
//     'price' => 50,
//     'description' => '10 Mobile Searches'
//   ],
//   ...
// ]


// ============================================
// PRACTICAL EXAMPLES
// ============================================

// Example 1: Complete Search with Payment
// -----------------------------------------
$payment = new Payment();
$userId = $_SESSION['user_id'];

// Check balance
$balance = $payment->getBalance($userId);
if ($balance < 5) {
    echo "Insufficient balance. Please buy credits.";
    exit;
}

// Deduct credits
$result = $payment->deductCredits($userId, 5, 'Aadhaar Search');
if (!$result['status']) {
    echo $result['message'];
    exit;
}

// Proceed with actual search
// ... your API call code here ...


// Example 2: Admin Manual Credit Addition
// ----------------------------------------
$payment = new Payment();
$userId = 5; // Target user

// Add promotional credit
$payment->addCredits($userId, 100, 'Promotional Bonus - Diwali Offer');

// Get updated balance
$newBalance = $payment->getBalance($userId);
echo "New balance for user: ₹" . $newBalance;


// Example 3: Generate Payment Report
// -----------------------------------
$payment = new Payment();

$packages = $payment->getPaymentPackages();
foreach ($packages as $pkg) {
    echo "Package: " . $pkg['name'] . " - ₹" . $pkg['price'] . " for " . $pkg['credits'] . " credits\n";
}


// ============================================
// DATABASE QUERIES (Direct Access)
// ============================================

$db = Database::getInstance();

// Get user wallet
$wallet = $db->fetch('SELECT * FROM wallets WHERE user_id = ?', [$userId]);

// Get all transactions for user
$transactions = $db->fetchAll(
    'SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC',
    [$userId]
);

// Get payment statistics
$stats = $db->fetch(
    'SELECT COUNT(*) as total_orders, SUM(amount) as total_revenue FROM payment_orders WHERE status = "completed"',
    []
);


// ============================================
// PAGE INTEGRATION CHECKLIST
// ============================================

/*
To integrate payment system in a page:

1. Include Payment class
   require_once(__DIR__ . '/../classes/Payment.php');

2. Initialize
   $payment = new Payment();

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

4. Get user balance (optional)
   $balance = $payment->getBalance($_SESSION['user_id']);

5. Use payment methods as needed
   - Check balance before search
   - Deduct credits on successful search
   - Show wallet in sidebar

*/


// ============================================
// ERROR HANDLING
// ============================================

try {
    $result = $payment->deductCredits($userId, 10, 'Test');
    
    if ($result['status']) {
        echo "Success: Credits deducted";
    } else {
        echo "Error: " . $result['message'];
    }
} catch (Exception $e) {
    error_log("Payment Error: " . $e->getMessage());
    echo "A payment error occurred";
}


// ============================================
// CONFIGURATION
// ============================================

/*
Update payment packages in Payment.php:

public function getPaymentPackages() {
    return [
        [
            'id' => 1,
            'name' => 'Basic',
            'credits' => 10,
            'price' => 50,
            'description' => '10 Mobile Searches'
        ],
        // Add more packages...
    ];
}

Update costs in config/config.php:
define('MOBILE_SEARCH_COST', 1);
define('AADHAAR_SEARCH_COST', 5);
*/

?>
