<?php
require_once __DIR__ . '/../../connect.php';

$inviterCode = filterRequest("inviter_code");

// Use JWT token variables provided by connect.php
if (!$inviterCode || !$user_id || !in_array($role, ['driver', 'passenger'])) {
    jsonError("Invalid parameters or unauthorized token");
}

// Ensure the code exists and get the inviter details
$stmtCheck = $con->prepare("SELECT user_id, user_type FROM user_referral_codes WHERE referral_code = ?");
$stmtCheck->execute([$inviterCode]);

if ($stmtCheck->rowCount() == 0) {
    jsonError("Invalid referral code");
}
$inviterData = $stmtCheck->fetch(PDO::FETCH_ASSOC);

// Check if user was already invited
$stmtExisting = $con->prepare("SELECT id FROM unified_referrals WHERE invited_user_id = ? AND invited_user_type = ?");
$stmtExisting->execute([$user_id, $role]);

if ($stmtExisting->rowCount() > 0) {
    jsonError("User already registered with a referral code");
}

// Insert new referral
$insertStmt = $con->prepare("INSERT INTO unified_referrals (inviter_code, invited_user_id, invited_user_type, status, trip_count, is_reward_claimed) VALUES (?, ?, ?, 'registered', 0, 0)");

try {
    $insertStmt->execute([$inviterCode, $user_id, $role]);
    printSuccess(["message" => "Referral linked successfully"]);
} catch (PDOException $e) {
    jsonError("Database error: " . $e->getMessage());
}
?>
