<?php
/**
 * Payment & Revenue Statistics (Super Admin)
 * GET /api/v1/payments/stats
 */

declare(strict_types=1);

use App\Core\Database;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();

if ($decoded['role'] !== 'super_admin') {
    json_error('هذه الصفحة لمدير النظام فقط.', 403);
}

$db = Database::getInstance();

try {
    // Total revenue
    $stmt = $db->query("SELECT COALESCE(SUM(amount_jod), 0) as total_revenue FROM payment_requests WHERE status = 'approved'");
    $totalRevenue = (float)$stmt->fetch()['total_revenue'];

    // This month revenue
    $stmt = $db->query("SELECT COALESCE(SUM(amount_jod), 0) as month_revenue FROM payment_requests WHERE status = 'approved' AND MONTH(verified_at) = MONTH(NOW()) AND YEAR(verified_at) = YEAR(NOW())");
    $monthRevenue = (float)$stmt->fetch()['month_revenue'];

    // Payment counts by status
    $stmt = $db->query("
        SELECT status, COUNT(*) as count 
        FROM payment_requests 
        GROUP BY status
    ");
    $statusCounts = [];
    while ($row = $stmt->fetch()) {
        $statusCounts[$row['status']] = (int)$row['count'];
    }

    // Active subscriptions count
    $stmt = $db->query("SELECT COUNT(*) as active FROM subscriptions WHERE status = 'active' AND current_period_end > NOW()");
    $activeSubscriptions = (int)$stmt->fetch()['active'];

    // Revenue by plan
    $stmt = $db->query("
        SELECT sp.name_ar, sp.name_en, COUNT(pr.id) as count, COALESCE(SUM(pr.amount_jod), 0) as revenue
        FROM payment_requests pr
        LEFT JOIN subscription_plans sp ON pr.plan_id = sp.id
        WHERE pr.status = 'approved'
        GROUP BY pr.plan_id
        ORDER BY revenue DESC
    ");
    $revenueByPlan = $stmt->fetchAll();

    // Recent payments (last 10)
    $stmt = $db->query("
        SELECT pr.id, pr.amount_jod, pr.status, pr.internal_reference, pr.bank_reference, pr.created_at, pr.verified_at,
               u.name AS payer_name, sp.name_ar AS plan_name
        FROM payment_requests pr
        LEFT JOIN users u ON pr.user_id = u.id
        LEFT JOIN subscription_plans sp ON pr.plan_id = sp.id
        ORDER BY pr.created_at DESC
        LIMIT 10
    ");
    $recentPayments = $stmt->fetchAll();

    json_success([
        'total_revenue'         => $totalRevenue,
        'month_revenue'         => $monthRevenue,
        'active_subscriptions'  => $activeSubscriptions,
        'payment_counts'        => $statusCounts,
        'revenue_by_plan'       => $revenueByPlan,
        'recent_payments'       => $recentPayments,
    ], 'إحصائيات الإيرادات والاشتراكات');

} catch (\Exception $e) {
    error_log("Payment Stats Error: " . $e->getMessage());
    json_error('حدث خطأ أثناء جلب الإحصائيات.', 500);
}
