<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Rule;

class CustomerController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Customer::where('restaurant_id', $request->user()->restaurant_id);

        // Search
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        // Filter by customer type
        if ($request->has('type')) {
            switch ($request->type) {
                case 'vip':
                    $query->vip();
                    break;
                case 'loyal':
                    $query->loyal();
                    break;
                case 'regular':
                    $query->regular();
                    break;
                case 'new':
                    $query->new();
                    break;
            }
        }

        $customers = $query->orderBy('name')->paginate(2000);

        return response()->json([
            'customers' => $customers->items(),
            'pagination' => [
                'current_page' => $customers->currentPage(),
                'last_page' => $customers->lastPage(),
                'per_page' => $customers->perPage(),
                'total' => $customers->total(),
            ],
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => [
                'required',
                'string',
                'regex:/^\+254[0-9]{9}$/',
                Rule::unique('customers')->where('restaurant_id', $request->user()->restaurant_id),
            ],
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string|max:500',
            'preferences' => 'nullable|array',
        ]);

        $customer = Customer::create([
            'restaurant_id' => $request->user()->restaurant_id,
            'name' => $request->name,
            'phone' => $request->phone,
            'email' => $request->email,
            'address' => $request->address,
            'preferences' => $request->preferences,
        ]);

        return response()->json([
            'message' => 'Customer created successfully',
            'customer' => $customer,
        ], 201);
    }

    public function show(Customer $customer): JsonResponse
    {
        $customer->load(['orders' => function ($query) {
            $query->latest()->limit(10);
        }]);

        return response()->json([
            'customer' => $customer,
            'formatted_phone' => $customer->formatted_phone,
            'average_order_value' => $customer->average_order_value,
            'customer_type' => $customer->customer_type,
            'recent_orders' => $customer->orders,
        ]);
    }

    public function update(Request $request, Customer $customer): JsonResponse
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => [
                'required',
                'string',
                'regex:/^\+254[0-9]{9}$/',
                Rule::unique('customers')->where('restaurant_id', $request->user()->restaurant_id)->ignore($customer->id),
            ],
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string|max:500',
            'preferences' => 'nullable|array',
            'is_active' => 'boolean',
        ]);

        $customer->update([
            'name' => $request->name,
            'phone' => $request->phone,
            'email' => $request->email,
            'address' => $request->address,
            'preferences' => $request->preferences,
            'is_active' => $request->is_active ?? true,
        ]);

        return response()->json([
            'message' => 'Customer updated successfully',
            'customer' => $customer,
        ]);
    }

    public function findByPhone(Request $request, string $phone): JsonResponse
    {
        // Clean and format phone number
        $cleanPhone = preg_replace('/[^0-9]/', '', $phone);
        
        // Try different phone number formats
        $phoneVariants = [
            '+254' . substr($cleanPhone, -9), // +254XXXXXXXXX
            '0' . substr($cleanPhone, -9),    // 0XXXXXXXXX
            $cleanPhone,                      // As provided
        ];

        $customer = Customer::where('restaurant_id', $request->user()->restaurant_id)
            ->where(function ($query) use ($phoneVariants) {
                foreach ($phoneVariants as $variant) {
                    $query->orWhere('phone', 'like', '%' . $variant);
                }
            })
            ->first();

        if (!$customer) {
            return response()->json(['customer' => null]);
        }

        return response()->json([
            'customer' => [
                'id' => $customer->id,
                'name' => $customer->name,
                'phone' => $customer->phone,
                'formatted_phone' => $customer->formatted_phone,
                'email' => $customer->email,
                'address' => $customer->address,
                'total_orders' => $customer->total_orders,
                'total_spent' => $customer->total_spent,
                'average_order_value' => $customer->average_order_value,
                'customer_type' => $customer->customer_type,
                'last_order_at' => $customer->last_order_at,
                'preferences' => $customer->preferences,
            ],
        ]);
    }
}