<?php
/**
 * Referral System — Generate & Track Referral Codes
 * GET /v1/referral/my-code — Get or generate user's referral code
 */

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

$decoded = AuthMiddleware::check();
$db = Database::getInstance();

$userId = $decoded['user_id'];
$tenantId = $decoded['tenant_id'] ?? null;

try {
    // Check if user already has a referral code
    $stmt = $db->prepare("SELECT * FROM referral_codes WHERE user_id = ? LIMIT 1");
    $stmt->execute([$userId]);
    $existing = $stmt->fetch();

    $rewardRules = [
        'per_registration' => '1 شهر مجاني على الباقة الحالية',
        'per_subscription' => '2 شهر مجاني + رفع الحد 50 فاتورة',
    ];

    if ($existing) {
        // Get referral stats (safe — returns zeros if no referrals yet)
        $statsStmt = $db->prepare("
            SELECT 
                COUNT(*) as total_referrals,
                SUM(CASE WHEN status = 'registered' THEN 1 ELSE 0 END) as registered,
                SUM(CASE WHEN status = 'subscribed' THEN 1 ELSE 0 END) as subscribed,
                SUM(CASE WHEN reward_claimed = 1 THEN 1 ELSE 0 END) as rewards_claimed
            FROM referrals WHERE referrer_id = ?
        ");
        $statsStmt->execute([$userId]);
        $stats = $statsStmt->fetch();

        // Recent referrals
        $recent = [];
        try {
            $recentStmt = $db->prepare("
                SELECT r.*, u.name as referred_name 
                FROM referrals r
                LEFT JOIN users u ON r.referred_id = u.id
                WHERE r.referrer_id = ?
                ORDER BY r.created_at DESC LIMIT 10
            ");
            $recentStmt->execute([$userId]);
            $recent = $recentStmt->fetchAll();

            // Decrypt names
            foreach ($recent as &$ref) {
                if (!empty($ref['referred_name'])) {
                    $dec = \App\Core\Encryption::decrypt($ref['referred_name']);
                    $ref['referred_name'] = ($dec !== false && $dec !== null) ? $dec : $ref['referred_name'];
                }
            }
        } catch (\Exception $e) {
            // If referrals table query fails, just return empty
            error_log("Referral recent query: " . $e->getMessage());
        }

        json_success([
            'code' => $existing['code'],
            'link' => 'https://musadaq.intaleqapp.com/ref/' . $existing['code'],
            'created_at' => $existing['created_at'],
            'stats' => [
                'total' => (int)($stats['total_referrals'] ?? 0),
                'registered' => (int)($stats['registered'] ?? 0),
                'subscribed' => (int)($stats['subscribed'] ?? 0),
                'rewards_claimed' => (int)($stats['rewards_claimed'] ?? 0),
            ],
            'recent' => $recent,
            'reward_rules' => $rewardRules,
        ], 'رمز الإحالة الخاص بك');
    } else {
        // Generate new referral code
        $code = 'MSQ-' . strtoupper(substr(md5($userId . time()), 0, 6));
        
        $insertStmt = $db->prepare("INSERT INTO referral_codes (id, user_id, tenant_id, code, created_at) VALUES (UUID(), ?, ?, ?, NOW())");
        $insertStmt->execute([$userId, $tenantId ?? '', $code]);

        json_success([
            'code' => $code,
            'link' => 'https://musadaq.intaleqapp.com/ref/' . $code,
            'created_at' => date('Y-m-d H:i:s'),
            'stats' => ['total' => 0, 'registered' => 0, 'subscribed' => 0, 'rewards_claimed' => 0],
            'recent' => [],
            'reward_rules' => $rewardRules,
        ], 'تم إنشاء رمز الإحالة');
    }
} catch (\Exception $e) {
    error_log("Referral error: " . $e->getMessage() . " | Trace: " . $e->getTraceAsString());
    safe_error($e, 'referral/my_code', 'حدث خطأ في نظام الإحالة.');
}
