<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';

apply_cors();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    send_error('Method not allowed.', 405);
}

require_admin();
$pdo = getDbConnection();

// ---- Core user counts ----
$totalUsers   = (int) $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'USER'")->fetchColumn();
$blockedUsers = (int) $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'USER' AND is_blocked = 1")->fetchColumn();
$trialUsers   = (int) $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'USER' AND validity_days <= 2")->fetchColumn();

$activeUsers = (int) $pdo->query(
    "SELECT COUNT(*) FROM users
     WHERE role = 'USER' AND is_blocked = 0
     AND DATE_ADD(activated_at, INTERVAL validity_days DAY) >= NOW()"
)->fetchColumn();

$expiredUsers = (int) $pdo->query(
    "SELECT COUNT(*) FROM users
     WHERE role = 'USER' AND is_blocked = 0
     AND DATE_ADD(activated_at, INTERVAL validity_days DAY) < NOW()"
)->fetchColumn();

$paidUsers = (int) $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'USER' AND validity_days > 2")->fetchColumn();

// ---- Revenue & payments ----
$totalRevenue = (float) $pdo->query(
    "SELECT COALESCE(SUM(amount),0) FROM payment_transactions WHERE status IN ('SUCCESS','VERIFIED')"
)->fetchColumn();

$pendingPayments = (int) $pdo->query(
    "SELECT COUNT(*) FROM payment_transactions WHERE status = 'PENDING'"
)->fetchColumn();

$successfulPayments = (int) $pdo->query(
    "SELECT COUNT(*) FROM payment_transactions WHERE status IN ('SUCCESS','VERIFIED')"
)->fetchColumn();

// ---- Calls & automation ----
$totalCalls  = (int) $pdo->query('SELECT COUNT(*) FROM call_logs')->fetchColumn();
$totalSent   = (int) $pdo->query(
    "SELECT COUNT(*) FROM call_logs WHERE status IN ('SMS Sent','WhatsApp Sent','WhatsApp Business Sent')"
)->fetchColumn();
$totalFailed = (int) $pdo->query("SELECT COUNT(*) FROM call_logs WHERE status = 'Delivery Failed'")->fetchColumn();

// ---- Referral / banners ----
$activeBanners = (int) $pdo->query('SELECT COUNT(*) FROM banners WHERE is_active = 1')->fetchColumn();

// ---- 14-day user growth chart ----
$growthStmt = $pdo->query(
    "SELECT DATE(created_at) AS d, COUNT(*) AS c
     FROM users WHERE role = 'USER' AND created_at >= (NOW() - INTERVAL 14 DAY)
     GROUP BY DATE(created_at) ORDER BY d ASC"
);
$growthChart = $growthStmt->fetchAll();

// ---- 14-day revenue chart ----
$revenueStmt = $pdo->query(
    "SELECT DATE(created_at) AS d, COALESCE(SUM(amount),0) AS total
     FROM payment_transactions WHERE status IN ('SUCCESS','VERIFIED') AND created_at >= (NOW() - INTERVAL 14 DAY)
     GROUP BY DATE(created_at) ORDER BY d ASC"
);
$revenueChart = $revenueStmt->fetchAll();

// ---- 14-day call activity chart ----
$callChart = $pdo->query(
    "SELECT DATE(created_at) AS d, COUNT(*) AS c
     FROM call_logs WHERE created_at >= (NOW() - INTERVAL 14 DAY)
     GROUP BY DATE(created_at) ORDER BY d ASC"
)->fetchAll();

send_success([
    'users' => [
        'total'   => $totalUsers,
        'active'  => $activeUsers,
        'expired' => $expiredUsers,
        'blocked' => $blockedUsers,
        'trial'   => $trialUsers,
        'paid'    => $paidUsers,
    ],
    'payments' => [
        'total_revenue'       => $totalRevenue,
        'pending_payments'    => $pendingPayments,
        'successful_payments' => $successfulPayments,
    ],
    'calls' => [
        'total'  => $totalCalls,
        'sent'   => $totalSent,
        'failed' => $totalFailed,
    ],
    'active_banners' => $activeBanners,
    'charts' => [
        'user_growth'  => $growthChart,
        'revenue'      => $revenueChart,
        'call_activity' => $callChart,
    ],
]);
