<?php

namespace App\Http\Controllers\Epelcon;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\Customer;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    public function index(Request $request)
    {
        $customers = Customer::withCount(['bookings', 'orders'])
            ->with('membership.plan')
            ->when($request->filled('q'), fn ($q) => $q->where(fn ($w) => $w->where('name', 'like', '%' . $request->q . '%')
                ->orWhere('phone', 'like', '%' . $request->q . '%')
                ->orWhere('email', 'like', '%' . $request->q . '%')))
            ->when($request->input('filter') === 'vip', fn ($q) => $q->where('vip', true))
            ->when($request->input('filter') === 'members', fn ($q) => $q->whereHas('membership'))
            ->latest()
            ->paginate(20)->withQueryString();

        $summary = [
            'total' => Customer::count(),
            'vip' => Customer::where('vip', true)->count(),
            'members' => Customer::whereHas('membership')->count(),
            'new_month' => Customer::whereBetween('created_at', [now()->startOfMonth(), now()])->count(),
        ];

        return view('epelcon.customers.index', compact('customers', 'summary'));
    }

    public function store(Request $request)
    {
        $data = $this->validateCustomer($request);

        $customer = Customer::create($data);
        ActivityLog::record('created customer', 'crm', $customer->name);

        return back()->with('success', "Customer “{$customer->name}” added.");
    }

    public function show(Customer $customer)
    {
        $customer->load([
            'bookings' => fn ($q) => $q->with('room.roomType')->latest()->limit(10),
            'orders' => fn ($q) => $q->latest()->limit(10),
            'membership.plan',
            'rewardTransactions' => fn ($q) => $q->latest()->limit(10),
            'referralsMade.referred',
            'user',
        ]);

        $lifetime = [
            'bookings_value' => (float) $customer->bookings()->sum('paid_amount'),
            'orders_value' => (float) $customer->orders()->sum('paid_amount'),
        ];

        return view('epelcon.customers.show', compact('customer', 'lifetime'));
    }

    public function update(Request $request, Customer $customer)
    {
        $customer->update($this->validateCustomer($request));

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

    private function validateCustomer(Request $request): array
    {
        return $request->validate([
            'name' => 'required|string|max:120',
            'email' => 'nullable|email|max:120',
            'phone' => 'nullable|string|max:40',
            'address' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:80',
            'country' => 'nullable|string|max:80',
            'id_type' => 'nullable|string|max:40',
            'id_number' => 'nullable|string|max:60',
            'dob' => 'nullable|date',
            'gender' => 'nullable|in:male,female,other',
            'vip' => 'nullable|boolean',
            'notes' => 'nullable|string',
        ]) + ['vip' => $request->boolean('vip')];
    }
}
