<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;

class AccountController extends Controller
{
    public function index(): Response|RedirectResponse
    {
        $user = auth()->user();

        if (in_array($user->status, ['pending', 'rejected'])) {
            return redirect()->route('portal.pending');
        }

        $bookings = [];
        if ($user->status === 'approved') {
            $userBookings = Booking::where('user_id', $user->id)
                ->orderByDesc('created_at')
                ->get();

            $bookingIds = $userBookings->pluck('id');

            $paidAmounts = DB::table('payment_transactions')
                ->whereIn('booking_id', $bookingIds)
                ->selectRaw("booking_id, SUM(CASE WHEN type != 'refund' THEN amount ELSE -amount END) as paid")
                ->groupBy('booking_id')
                ->pluck('paid', 'booking_id');

            $bookings = $userBookings->map(fn($b) => [
                'id'                    => $b->id,
                'reference'             => $b->reference,
                'facility_type'         => $b->facility_type,
                'facility_name'         => $b->facility_name,
                'date_start'            => $b->date_start?->format('Y-m-d'),
                'date_end'              => $b->date_end?->format('Y-m-d'),
                'time_start'            => $b->time_start,
                'time_end'              => $b->time_end,
                'persons_count'         => $b->persons_count,
                'name'                  => $b->name,
                'total_amount'          => $b->total_amount,
                'paid_amount'           => (float) ($paidAmounts[$b->id] ?? 0),
                'status'                => $b->status,
                'payment_status'        => $b->payment_status,
                'payment_method'        => $b->payment_method,
                'instapay_sender_phone' => $b->instapay_sender_phone,
                'created_at'            => $b->created_at->format('Y-m-d'),
            ])->all();
        }

        $instapayLink = DB::table('settings')->where('key', 'instapay_link')->value('value') ?? '';
        $clubLogoUrl  = asset('images/logo.png');

        return Inertia::render('Account/Index', [
            'user'         => [
                'name'           => $user->name,
                'email'          => $user->email,
                'phone'          => $user->phone ?? '',
                'church'         => $user->church ?? '',
                'status'         => $user->status,
                'rejection_note' => $user->rejection_note ?? null,
            ],
            'bookings'     => $bookings,
            'instapayLink' => $instapayLink,
            'clubLogoUrl'  => $clubLogoUrl,
            'newEntryRef'  => session('newEntryRef'),
        ]);
    }

    public function pending(): Response|RedirectResponse
    {
        $user = auth()->user();

        if ($user->status === 'approved') {
            return redirect()->route('account.index');
        }

        return Inertia::render('Portal/Pending', [
            'status'         => $user->status,
            'rejection_note' => $user->rejection_note ?? null,
        ]);
    }

    public function updateProfile(Request $request): RedirectResponse
    {
        $request->validate([
            'name'   => 'required|string|max:255',
            'phone'  => ['required', 'digits:11'],
            'church' => 'required|string|max:255',
        ], [
            'name.required'   => 'الاسم مطلوب.',
            'phone.required'  => 'رقم الموبايل مطلوب.',
            'phone.digits'    => 'رقم الموبايل يجب أن يكون 11 رقماً بالضبط.',
            'church.required' => 'اسم الكنيسة مطلوب.',
        ]);

        auth()->user()->update($request->only(['name', 'phone', 'church']));

        return redirect()->route('account.index')
            ->with('success', 'تم تحديث الملف الشخصي بنجاح.')
            ->with('active_tab', 'profile');
    }

    public function updatePassword(Request $request): RedirectResponse
    {
        $request->validate([
            'current_password' => ['required', 'current_password'],
            'password'         => ['required', 'confirmed', Rules\Password::defaults()],
        ], [
            'current_password.required'      => 'كلمة المرور الحالية مطلوبة.',
            'current_password.current_password' => 'كلمة المرور الحالية غير صحيحة.',
            'password.required'              => 'كلمة المرور الجديدة مطلوبة.',
            'password.confirmed'             => 'كلمة المرور الجديدة وتأكيدها غير متطابقتين.',
        ]);

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

        return redirect()->route('account.index')
            ->with('success', 'تم تغيير كلمة المرور بنجاح.')
            ->with('active_tab', 'profile');
    }
}
