<?php
/**
 * Apply Referral Code During Registration
 * POST /v1/referral/apply
 * Body: { "referral_code": "MSQ-ABC123" }
 * 
 * Called during registration to link a new user to their referrer.
 */

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

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

$data = Security::sanitize(input());
$code = $data['referral_code'] ?? null;

if (!$code) {
    json_error('رمز الإحالة مطلوب', 422);
}

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

try {
    // 1. Validate the referral code
    $stmt = $db->prepare("SELECT * FROM referral_codes WHERE code = ? LIMIT 1");
    $stmt->execute([$code]);
    $referralCode = $stmt->fetch();

    if (!$referralCode) {
        json_error('رمز الإحالة غير صالح', 404);
    }

    // Prevent self-referral
    if ($referralCode['user_id'] === $userId) {
        json_error('لا يمكنك استخدام رمز الإحالة الخاص بك', 400);
    }

    // Check if user already used a referral
    $checkStmt = $db->prepare("SELECT id FROM referrals WHERE referred_id = ? LIMIT 1");
    $checkStmt->execute([$userId]);
    if ($checkStmt->fetch()) {
        json_error('لقد استخدمت رمز إحالة مسبقاً', 409);
    }

    // 2. Create the referral record
    $db->beginTransaction();

    $referralId = \App\Core\Database::generateUuid();
    $stmt = $db->prepare("
        INSERT INTO referrals (id, referrer_id, referred_id, referral_code_id, status, created_at)
        VALUES (?, ?, ?, ?, 'registered', NOW())
    ");
    $stmt->execute([$referralId, $referralCode['user_id'], $userId, $referralCode['id']]);

    // 3. Notify the referrer
    try {
        $notifStmt = $db->prepare("
            INSERT INTO notifications (id, tenant_id, user_id, type, title, body, data, created_at)
            VALUES (UUID(), ?, ?, 'referral', '🎉 إحالة جديدة!', 'شخص جديد انضم باستخدام رمز إحالتك', ?, NOW())
        ");
        $notifStmt->execute([
            $referralCode['tenant_id'],
            $referralCode['user_id'],
            json_encode(['referral_id' => $referralId, 'code' => $code])
        ]);
    } catch (\Exception $e) {
        // Don't fail the whole operation if notification fails
        error_log("[referral/apply] Notification failed: " . $e->getMessage());
    }

    $db->commit();

    json_success([
        'referral_id' => $referralId,
        'referrer_code' => $code,
        'status' => 'registered',
    ], 'تم تطبيق رمز الإحالة بنجاح! 🎉');

} catch (\Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    safe_error($e, 'referral/apply', 'حدث خطأ في تطبيق رمز الإحالة.');
}
