<?php

namespace App\Http\Controllers;

use App\Models\Game;
use App\Models\ManualPaymentGateway;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class AccountController extends Controller
{
    public function dashboard(Request $request)
    {
        $user = $this->accountUser($request);

        return view('account.dashboard', [
            'user' => $user,
            'ordersThisMonth' => $user->orders()->whereMonth('created_at', now()->month)->whereYear('created_at', now()->year)->count(),
            'favoritesCount' => $user->favorites()->count(),
            'recentOrders' => $user->orders()->with('items')->latest()->limit(5)->get(),
            'recentNotifications' => $user->customerNotifications()->latest()->limit(5)->get(),
        ]);
    }

    public function orders(Request $request)
    {
        $status = $request->string('status')->toString();
        $orders = $request->user()->orders()
            ->with('items')
            ->when($status !== '', fn ($query) => $query->where(function ($nested) use ($status) {
                $nested->where('payment_status', $status)->orWhere('fulfillment_status', $status);
            }))
            ->latest()
            ->paginate(12)
            ->withQueryString();

        return view('account.orders', [
            'user' => $this->accountUser($request),
            'orders' => $orders,
            'status' => $status,
        ]);
    }

    public function tickets(Request $request)
    {
        return view('account.tickets', [
            'user' => $this->accountUser($request),
            'tickets' => $request->user()->supportTickets()->withCount('messages')->latest('last_activity_at')->paginate(10),
        ]);
    }

    public function wallet(Request $request)
    {
        $user = $this->accountUser($request);

        return view('account.wallet', [
            'user' => $user,
            'entries' => $user->wallet?->entries()->latest()->paginate(12),
            'submissions' => $user->manualPaymentSubmissions()->with('gateway')->latest()->limit(8)->get(),
            'gateways' => ManualPaymentGateway::where('is_active', true)->orderBy('sort_order')->get(),
        ]);
    }

    public function notifications(Request $request)
    {
        $filter = $request->string('filter')->toString();

        return view('account.notifications', [
            'user' => $this->accountUser($request),
            'filter' => $filter,
            'notifications' => $request->user()->customerNotifications()
                ->when($filter === 'unread', fn ($query) => $query->whereNull('read_at'))
                ->latest()
                ->paginate(12)
                ->withQueryString(),
        ]);
    }

    public function markNotificationsRead(Request $request): RedirectResponse
    {
        $request->user()->customerNotifications()->whereNull('read_at')->update(['read_at' => now()]);

        return back()->with('status', 'تم تعليم الإشعارات كمقروءة.');
    }

    public function favorites(Request $request)
    {
        return view('account.favorites', [
            'user' => $this->accountUser($request),
            'favorites' => $request->user()->favoriteGames()->with(['category', 'productVariants'])->latest('favorites.created_at')->paginate(12),
        ]);
    }

    public function toggleFavorite(Request $request, Game $game)
    {
        $exists = $request->user()->favorites()->where('game_id', $game->id)->exists();

        if ($exists) {
            $request->user()->favorites()->where('game_id', $game->id)->delete();
        } else {
            $request->user()->favorites()->create(['game_id' => $game->id]);
        }

        $payload = [
            'ok' => true,
            'favorited' => ! $exists,
            'count' => $request->user()->favorites()->count(),
        ];

        if ($request->expectsJson()) {
            return response()->json($payload);
        }

        return back()->with('status', $exists ? 'تم حذف المنتج من المفضلة.' : 'تمت إضافة المنتج للمفضلة.');
    }

    public function profile(Request $request)
    {
        return view('account.profile', [
            'user' => $this->accountUser($request),
        ]);
    }

    public function updateProfile(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'display_name' => ['nullable', 'string', 'max:120'],
            'phone' => ['nullable', 'string', 'max:40'],
            'locale' => ['nullable', 'in:ar,en'],
        ]);

        $request->user()->update($data);

        if (! empty($data['locale'])) {
            session(['store_locale' => $data['locale']]);
        }

        return back()->with('status', 'تم حفظ بيانات الملف الشخصي.');
    }

    public function updatePassword(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'current_password' => ['required', 'current_password'],
            'password' => ['required', 'confirmed', Password::min(8)],
        ]);

        $request->user()->update([
            'password' => Hash::make($data['password']),
        ]);

        return back()->with('status', 'تم تغيير كلمة المرور.');
    }

    private function accountUser(Request $request)
    {
        return $request->user()->load([
            'wallet.entries',
            'orders.items',
            'customerNotifications.order',
            'referrer',
            'referredUsers',
            'referralRewardsSent.referred',
            'referralRewardsReceived.referrer',
            'sentWalletTransfers.receiver',
            'receivedWalletTransfers.sender',
            'voucherRedemptions.voucher',
            'supportTickets.messages',
            'favorites.game',
            'manualPaymentSubmissions.gateway',
        ]);
    }
}
