<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\Customer;
use App\Models\Membership;
use App\Models\MembershipPlan;
use App\Models\Order;
use App\Models\Referral;
use App\Models\RewardTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class AccountController extends Controller
{
    public function dashboard()
    {
        $customer = $this->customer();

        return view('account.dashboard', [
            'customer' => $customer,
            'upcoming' => Booking::where('customer_id', $customer->id)->whereIn('status', ['pending', 'confirmed'])->orderBy('check_in')->limit(3)->get(),
            'recentOrders' => Order::where('customer_id', $customer->id)->latest()->limit(3)->get(),
            'membership' => $customer->membership()->with('plan')->first(),
        ]);
    }

    public function bookings()
    {
        return view('account.bookings', [
            'bookings' => Booking::with(['room.roomType', 'roomType'])->where('customer_id', $this->customer()->id)->latest()->paginate(10),
        ]);
    }

    public function orders()
    {
        return view('account.orders', [
            'orders' => Order::with('items')->where('customer_id', $this->customer()->id)->latest()->paginate(10),
        ]);
    }

    public function membership()
    {
        $customer = $this->customer();

        return view('account.membership', [
            'customer' => $customer,
            'membership' => $customer->membership()->with('plan')->first(),
            'plans' => MembershipPlan::where('status', 'active')->orderBy('price')->get(),
        ]);
    }

    public function subscribe(MembershipPlan $plan)
    {
        $customer = $this->customer();

        if ($customer->membership()->exists()) {
            return back()->with('error', 'You already have an active membership.');
        }

        Membership::create([
            'code' => 'MEM-' . strtoupper(Str::random(6)),
            'customer_id' => $customer->id,
            'membership_plan_id' => $plan->id,
            'starts_at' => today(),
            'expires_at' => today()->addDays($plan->duration_days),
            'status' => 'active',
        ]);

        return back()->with('success', "Welcome to the {$plan->name} tier! Visit the front desk to complete payment and collect your card.");
    }

    public function rewards()
    {
        $customer = $this->customer();

        return view('account.rewards', [
            'customer' => $customer,
            'transactions' => RewardTransaction::where('customer_id', $customer->id)->latest()->paginate(15),
            'referrals' => Referral::with('referred')->where('referrer_customer_id', $customer->id)->latest()->get(),
        ]);
    }

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

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

        $data = $request->validate([
            'name' => 'required|string|max:120',
            'phone' => 'nullable|string|max:40',
            'address' => 'nullable|string|max:255',
            'password' => 'nullable|string|min:8|confirmed',
        ]);

        $user->update(array_filter([
            'name' => $data['name'],
            'phone' => $data['phone'] ?? null,
            'address' => $data['address'] ?? null,
            'password' => ! empty($data['password']) ? Hash::make($data['password']) : null,
        ]));

        $this->customer()->update(['name' => $data['name'], 'phone' => $data['phone'] ?? null, 'address' => $data['address'] ?? null]);

        return back()->with('success', 'Profile updated.');
    }

    private function customer(): Customer
    {
        $user = auth()->user();

        return Customer::firstOrCreate(
            ['user_id' => $user->id],
            ['name' => $user->name, 'email' => $user->email, 'phone' => $user->phone]
        );
    }
}
