<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Referral;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ReferralController extends Controller
{
    public function index(Request $request)
    {
        $user  = auth()->user();
        $query = Referral::with('owner')->latest();

        // Hide developer referrals from UI display
        $query->where('raw', 'not like', 'DEVx%');

        if (!$user->isOwner()) {
            // Admins (or resellers if they ever call it) see only referrals they created
            $query->where('owner_id', $user->id);
        }

        $perPage = $request->get('per_page', 10);
        return response()->json(['success' => true, 'data' => $query->paginate($perPage)]);
    }

    public function store(Request $request)
    {
        $user = auth()->user();

        // Resellers cannot generate referrals
        if ($user->isReseller()) {
            return response()->json(['success' => false, 'message' => 'Forbidden: Resellers cannot generate referrals'], 403);
        }

        $allowedRoles = ['admin', 'reseller'];
        if ($user->isOwner()) {
            $allowedRoles[] = 'owner';
        }

        $request->validate([
            'saldo'           => 'required|numeric|min:1',
            'role_type'       => 'required|string|in:' . implode(',', $allowedRoles),
            'referral_limit'  => 'nullable|integer|min:1|max:9999',
        ]);

        // Admins can only generate reseller referrals
        if ($user->isAdmin() && !$user->isOwner() && $request->role_type !== 'reseller') {
            return response()->json(['success' => false, 'message' => 'Forbidden: Admins can only generate reseller referrals'], 403);
        }

        // Owner has UNLIMITED referrals — skip limit check entirely
        if (!$user->isOwner()) {
            $totalCount = Referral::where('owner_id', $user->id)->count();

            $limit = $user->referral_limit;
            if ($limit !== null && $totalCount >= $limit) {
                return response()->json(['success' => false, 'message' => 'Referral limit reached'], 429);
            }

            // Referral balance allocation is independent (no deduction from Admin panel balance)
        }

        $raw    = Str::random(6);
        $hashed = substr(md5($raw . config('app.key')), 0, 16);

        $referral = Referral::create([
            'hashed'          => $hashed,
            'raw'             => $raw,
            'owner_id'        => $user->id,
            'saldo'           => $request->saldo,
            'role_type'       => $request->role_type,
            'referral_limit'  => $request->role_type === 'admin' ? ($request->referral_limit ?? 10) : null,
        ]);

        AuditLog::record('CREATE_REFERRAL', "Referral {$raw} created for role {$request->role_type} with saldo {$request->saldo}");

        return response()->json(['success' => true, 'referral' => $referral]);
    }

    public function limit()
    {
        $user  = auth()->user();
        $used  = Referral::where('owner_id', $user->id)->count();

        // Owner is unlimited
        if ($user->isOwner()) {
            return response()->json(['success' => true, 'used' => $used, 'limit' => null, 'remaining' => null, 'unlimited' => true]);
        }

        $limit = $user->referral_limit;
        return response()->json(['success' => true, 'used' => $used, 'limit' => $limit, 'remaining' => max(0, $limit - $used), 'unlimited' => false]);
    }
}
