<?php
/**
 * API: Payments Endpoints
 * Routes:
 * POST /api/v1/payments/initiate - Start payment
 * GET /api/v1/payments - Get payment history
 * GET /api/v1/payments/{id} - Get payment details
 */

require_once __DIR__ . '/../../app/controller/PaymentController.php';

$paymentController = new \App\Controller\PaymentController($db);

// Check authentication
$apiKey = $_GET['api_key'] ?? $_POST['api_key'] ?? null;
if (!$apiKey) {
    http_response_code(401);
    echo json_encode(['error' => 'API key required']);
    exit;
}

$stmt = $db->prepare('SELECT id FROM users WHERE api_key = ? AND status = "active"');
$stmt->execute([$apiKey]);
$user = $stmt->fetch(\PDO::FETCH_ASSOC);

if (!$user) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid API key']);
    exit;
}

$userId = $user['id'];

switch ($method) {
    case 'GET':
        if ($action === '') {
            getPaymentHistory($db, $userId);
        } elseif ($action) {
            getPayment($db, $userId, $action);
        }
        break;
        
    case 'POST':
        if ($action === 'initiate') {
            initiatePayment($db, $userId, $input);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}

/**
 * Initiate payment
 */
function initiatePayment($db, $userId, $input) {
    try {
        $amount = $input['amount'] ?? null;
        $currency = $input['currency'] ?? 'UGX';
        
        if (!$amount || $amount < 5000) {
            http_response_code(400);
            echo json_encode(['error' => 'Minimum deposit: 5,000 UGX']);
            return;
        }
        
        if ($amount > 5000000) {
            http_response_code(400);
            echo json_encode(['error' => 'Maximum deposit: 5,000,000 UGX']);
            return;
        }
        
        // Check daily limit
        $stmt = $db->prepare('
            SELECT COALESCE(SUM(amount), 0) as total
            FROM payments
            WHERE user_id = ?
            AND DATE(created_at) = CURDATE()
            AND status IN ("completed", "pending")
        ');
        $stmt->execute([$userId]);
        $todayTotal = $stmt->fetch(\PDO::FETCH_ASSOC)['total'];
        
        if (($todayTotal + $amount) > 10000000) {
            http_response_code(400);
            echo json_encode(['error' => 'Daily limit exceeded']);
            return;
        }
        
        // Create payment record
        $reference = 'PAY-' . uniqid() . '-' . $userId;
        
        $insertStmt = $db->prepare('
            INSERT INTO payments (user_id, amount, currency, reference, status, created_at)
            VALUES (?, ?, ?, ?, "pending", NOW())
        ');
        $insertStmt->execute([$userId, $amount, $currency, $reference]);
        $paymentId = $db->lastInsertId();
        
        // Get Marzpay configuration
        $marzpayKey = getenv('MARZPAY_API_KEY');
        $marzpaySecret = getenv('MARZPAY_SECRET_KEY');
        
        // Create Marzpay payment URL
        $paymentUrl = "https://marzpay.io/pay?key=$marzpayKey&amount=$amount&reference=$reference";
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'payment_id' => $paymentId,
            'reference' => $reference,
            'amount' => $amount,
            'currency' => $currency,
            'payment_url' => $paymentUrl
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Payment initiation failed: ' . $e->getMessage()]);
    }
}

/**
 * Get payment history
 */
function getPaymentHistory($db, $userId) {
    try {
        $page = $_GET['page'] ?? 1;
        $limit = $_GET['limit'] ?? 10;
        
        $page = max(1, intval($page));
        $limit = min(50, max(1, intval($limit)));
        $offset = ($page - 1) * $limit;
        
        // Get total
        $countStmt = $db->prepare('SELECT COUNT(*) as total FROM payments WHERE user_id = ?');
        $countStmt->execute([$userId]);
        $total = $countStmt->fetch(\PDO::FETCH_ASSOC)['total'];
        
        // Get payments
        $stmt = $db->prepare('
            SELECT id, amount, currency, reference, status, created_at, completed_at
            FROM payments
            WHERE user_id = ?
            ORDER BY created_at DESC
            LIMIT ? OFFSET ?
        ');
        $stmt->execute([$userId, $limit, $offset]);
        $payments = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'data' => $payments,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total
            ]
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}

/**
 * Get payment details
 */
function getPayment($db, $userId, $paymentId) {
    try {
        $stmt = $db->prepare('
            SELECT id, amount, currency, reference, status, created_at, completed_at
            FROM payments
            WHERE id = ? AND user_id = ?
        ');
        $stmt->execute([$paymentId, $userId]);
        $payment = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        if (!$payment) {
            http_response_code(404);
            echo json_encode(['error' => 'Payment not found']);
            return;
        }
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'data' => $payment
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}
?>
