<?php
/**
 * Admin statistics
 */
require_once 'config.php';

$input = json_decode(file_get_contents('php://input'), true) ?: [];
$userId = miniapp_require_admin();
try { if (function_exists('gemaccStarsAutoCancelExpired')) gemaccStarsAutoCancelExpired($pdo, 50); } catch (Throwable $e) { error_log('[stars_auto_cancel_admin_stats] '.$e->getMessage()); }

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $input['action'] ?? '';
    
    if ($action === 'reset_sales') {
        // Save last reset date
        $stmt = $pdo->prepare("INSERT INTO settings (key_name, value) VALUES ('last_sales_reset', ?) ON DUPLICATE KEY UPDATE value = ?");
        $resetDate = jdate('Y/m/d H:i');
        $stmt->execute([$resetDate, $resetDate]);
        
        // Save current stats before reset
        $stmt = $pdo->prepare("INSERT INTO settings (key_name, value) VALUES ('sales_reset_offset', ?) ON DUPLICATE KEY UPDATE value = ?");
        
        // Get current total delivered orders
        $stmt2 = $pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'DELIVERED'");
        $currentCount = (int)$stmt2->fetchColumn();
        $stmt->execute([$currentCount, $currentCount]);
        
        // Save revenue and cost offsets so net profit after reset is calculated from the same window.
        $stmt = $pdo->prepare("INSERT INTO settings (key_name, value) VALUES ('revenue_reset_offset', ?) ON DUPLICATE KEY UPDATE value = ?");
        $stmt2 = $pdo->query("SELECT COALESCE(SUM(price), 0) FROM orders WHERE status = 'DELIVERED'");
        $currentRevenue = (int)$stmt2->fetchColumn();
        $stmt->execute([$currentRevenue, $currentRevenue]);

        try { if (!function_exists('gemacc_column_exists') || !gemacc_column_exists($pdo, 'plans', 'purchase_price')) $pdo->exec("ALTER TABLE plans ADD COLUMN purchase_price INT NOT NULL DEFAULT 0 AFTER price"); } catch (Throwable $e) {}
        try { if (!function_exists('gemacc_column_exists') || !gemacc_column_exists($pdo, 'orders', 'purchase_price')) $pdo->exec("ALTER TABLE orders ADD COLUMN purchase_price INT NOT NULL DEFAULT 0 AFTER price"); } catch (Throwable $e) {}
        $stmt = $pdo->prepare("INSERT INTO settings (key_name, value) VALUES ('cost_reset_offset', ?) ON DUPLICATE KEY UPDATE value = ?");
        $stmt2 = $pdo->query("SELECT COALESCE(SUM(COALESCE(NULLIF(o.purchase_price,0), NULLIF(p.purchase_price,0), CASE WHEN o.service_type='windscribe' AND COALESCE(o.months,1)>=12 THEN o.requested_seats*333333 WHEN o.service_type='windscribe' THEN o.requested_seats*150000 WHEN o.service_type='expressvpn' AND COALESCE(o.months,1)>=12 THEN o.requested_seats*250000 WHEN o.service_type='expressvpn' THEN o.requested_seats*50000 WHEN o.service_type='v2ray' THEN 0 ELSE o.requested_seats*180000 END, 0)), 0) FROM orders o LEFT JOIN plans p ON p.id = o.plan_id WHERE o.status = 'DELIVERED'");
        $currentCost = (int)$stmt2->fetchColumn();
        $stmt->execute([$currentCost, $currentCost]);
        
        gemaccAdminActionNotify('آمار فروش ریست شد', ['تعداد فروش قبل از ریست'=>$currentCount, 'درآمد قبل از ریست'=>money($currentRevenue), 'هزینه قبل از ریست'=>money($currentCost), 'تاریخ ریست'=>$resetDate], $userId);
        echo json_encode(['ok' => true, 'message' => 'آمار فروش ریست شد'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    echo json_encode(['ok' => false, 'error' => 'Invalid action'], JSON_UNESCAPED_UNICODE);
    exit;
}

// Get reset offsets
$stmt = $pdo->query("SELECT key_name, value FROM settings WHERE key_name IN ('sales_reset_offset', 'revenue_reset_offset', 'cost_reset_offset', 'last_sales_reset')");
$offsets = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $offsets[$row['key_name']] = $row['value'];
}
$salesOffset = (int)($offsets['sales_reset_offset'] ?? 0);
$revenueOffset = (int)($offsets['revenue_reset_offset'] ?? 0);
$costOffset = (int)($offsets['cost_reset_offset'] ?? 0);
$lastReset = $offsets['last_sales_reset'] ?? null;

// Total users
$stmt = $pdo->query("SELECT COUNT(*) FROM users");
$totalUsers = (int)$stmt->fetchColumn();

// Sales stats
try { if (!function_exists('gemacc_column_exists') || !gemacc_column_exists($pdo, 'plans', 'purchase_price')) $pdo->exec("ALTER TABLE plans ADD COLUMN purchase_price INT NOT NULL DEFAULT 0 AFTER price"); } catch (Throwable $e) {}
try { if (!function_exists('gemacc_column_exists') || !gemacc_column_exists($pdo, 'orders', 'purchase_price')) $pdo->exec("ALTER TABLE orders ADD COLUMN purchase_price INT NOT NULL DEFAULT 0 AFTER price"); } catch (Throwable $e) {}
$stmt = $pdo->query("
    SELECT 
        COUNT(*) as total_orders,
        SUM(CASE WHEN o.status = 'DELIVERED' THEN 1 ELSE 0 END) as delivered_count,
        SUM(CASE WHEN o.status = 'PENDING' THEN 1 ELSE 0 END) as pending_count,
        SUM(CASE WHEN o.status = 'DELIVERED' THEN o.price ELSE 0 END) as total_revenue,
        SUM(CASE WHEN o.status = 'DELIVERED' THEN COALESCE(NULLIF(o.purchase_price,0), NULLIF(p.purchase_price,0), CASE WHEN o.service_type='windscribe' AND COALESCE(o.months,1)>=12 THEN o.requested_seats*333333 WHEN o.service_type='windscribe' THEN o.requested_seats*150000 WHEN o.service_type='expressvpn' AND COALESCE(o.months,1)>=12 THEN o.requested_seats*250000 WHEN o.service_type='expressvpn' THEN o.requested_seats*50000 WHEN o.service_type='v2ray' THEN 0 ELSE o.requested_seats*180000 END, 0) ELSE 0 END) as total_cost,
        SUM(CASE WHEN o.status = 'DELIVERED' AND DATE(o.delivered_at) = CURDATE() THEN 1 ELSE 0 END) as today_count,
        SUM(CASE WHEN o.status = 'DELIVERED' AND DATE(o.delivered_at) = CURDATE() THEN o.price ELSE 0 END) as today_revenue,
        SUM(CASE WHEN o.status = 'DELIVERED' AND DATE(o.delivered_at) = CURDATE() THEN COALESCE(NULLIF(o.purchase_price,0), NULLIF(p.purchase_price,0), CASE WHEN o.service_type='windscribe' AND COALESCE(o.months,1)>=12 THEN o.requested_seats*333333 WHEN o.service_type='windscribe' THEN o.requested_seats*150000 WHEN o.service_type='expressvpn' AND COALESCE(o.months,1)>=12 THEN o.requested_seats*250000 WHEN o.service_type='expressvpn' THEN o.requested_seats*50000 WHEN o.service_type='v2ray' THEN 0 ELSE o.requested_seats*180000 END, 0) ELSE 0 END) as today_cost
    FROM orders o
    LEFT JOIN plans p ON p.id = o.plan_id
");
$sales = $stmt->fetch() ?: [];

// Apply offsets for campaign tracking
$adjustedSalesCount = max(0, (int)($sales['delivered_count'] ?? 0) - $salesOffset);
$grossRevenue = (int)($sales['total_revenue'] ?? 0);
$totalCost = (int)($sales['total_cost'] ?? 0);
$netRevenue = max(0, $grossRevenue - $totalCost);
$todayGross = (int)($sales['today_revenue'] ?? 0);
$todayCost = (int)($sales['today_cost'] ?? 0);
$todayNet = max(0, $todayGross - $todayCost);
$adjustedRevenue = max(0, $grossRevenue - $revenueOffset);
$adjustedCost = max(0, $totalCost - $costOffset);
$adjustedNetRevenue = max(0, $adjustedRevenue - $adjustedCost);

// Credentials stats
$stmt = $pdo->query("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN is_active = 1 AND (sellable_until IS NULL OR sellable_until >= NOW()) THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN duration = '1M' THEN 1 ELSE 0 END) as monthly,
        SUM(CASE WHEN duration = '1Y' THEN 1 ELSE 0 END) as yearly,
        SUM(used_seats) as used_seats,
        SUM(max_seats - used_seats) as remaining_seats
    FROM credentials
");
$creds = $stmt->fetch() ?: [];

// Pending counts
$stmt = $pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'PENDING' AND NOT (UPPER(COALESCE(payment_method,''))='STARS' AND LOWER(COALESCE(payment_status,''))<>'paid')");
$pendingOrders = (int)$stmt->fetchColumn();

$stmt = $pdo->query("SELECT COUNT(*) FROM wallet_transactions WHERE type = 'DEPOSIT' AND status = 'PENDING'");
$pendingDeposits = (int)$stmt->fetchColumn();

$stmt = $pdo->query("SELECT COUNT(*) FROM waiting_queue");
$queueCount = (int)$stmt->fetchColumn();

echo json_encode([
    'ok'   => true,
    'data' => [
        'total_users'        => $totalUsers,
        'total_orders'       => (int)($sales['total_orders'] ?? 0),
        'total_sales_count'  => $adjustedSalesCount,
        'total_sales_amount' => $adjustedRevenue,
        'gross_income'       => $adjustedRevenue,
        'total_purchase_cost'=> $adjustedCost,
        'net_income'         => $adjustedNetRevenue,
        'today_sales_count'  => (int)($sales['today_count'] ?? 0),
        'today_sales_amount' => $todayGross,
        'today_gross_income' => $todayGross,
        'today_purchase_cost'=> $todayCost,
        'today_net_income'   => $todayNet,
        'pending_orders'     => $pendingOrders,
        'pending_deposits'   => $pendingDeposits,
        'queue_count'        => $queueCount,
        'last_sales_reset'   => $lastReset,
        'credentials'        => [
            'total'           => (int)($creds['total'] ?? 0),
            'active'          => (int)($creds['active'] ?? 0),
            'monthly'         => (int)($creds['monthly'] ?? 0),
            'yearly'          => (int)($creds['yearly'] ?? 0),
            'used_seats'      => (int)($creds['used_seats'] ?? 0),
            'remaining_seats' => (int)($creds['remaining_seats'] ?? 0),
        ],
    ],
], JSON_UNESCAPED_UNICODE);
