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

function generateUnifiedCode($con) {
    while (true) {
        $letters = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ"), 0, 2);
        $numbers = substr(str_shuffle("23456789"), 0, 4);
        $code = $letters . $numbers;

        $stmt = $con->prepare("SELECT COUNT(*) FROM user_referral_codes WHERE referral_code = ?");
        $stmt->execute([$code]);

        if ($stmt->fetchColumn() == 0) {
            return $code;
        }
    }
}

// Ensure the JWT values exist
if (!$user_id || !in_array($role, ['driver', 'passenger'])) {
    jsonError("Invalid or missing user information in token");
}

$stmt = $con->prepare("SELECT referral_code FROM user_referral_codes WHERE user_id = ? AND user_type = ?");
$stmt->execute([$user_id, $role]);

if ($stmt->rowCount() > 0) {
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    printSuccess(["referral_code" => $row['referral_code']]);
} else {
    $newCode = generateUnifiedCode($con);
    $insertStmt = $con->prepare("INSERT INTO user_referral_codes (user_id, user_type, referral_code) VALUES (?, ?, ?)");
    
    try {
        $insertStmt->execute([$user_id, $role, $newCode]);
        printSuccess(["referral_code" => $newCode]);
    } catch (PDOException $e) {
        jsonError("Database error: " . $e->getMessage());
    }
}
?>
