<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Customer;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;

class CustomerController extends Controller
{
    /**
     * List customers (supports optional ?q=search)
     */
    public function index(Request $request)
    {
        $query = Customer::query();

        // If authenticated user belongs to a tenant, limit customers to that tenant
        $user = auth('api')->user();
        if ($user && isset($user->tenant_id) && $user->tenant_id) {
            $query->where('tenant_id', $user->tenant_id);
        }

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

        $customers = $query->orderBy('name')->limit(100)->get();

        return response()->json([
            'success' => true,
            'data' => $customers,
        ]);
    }

    /**
     * Create a new customer with user account
     * This creates both a Customer record and a User account for login
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:50',
            'email' => 'required|email|max:255|unique:users,email',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false, 
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $user = auth('api')->user();
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : ($request->input('tenant_id') ?? null);

            // Create User account with role 'passenger'
            $newUser = User::create([
                'name' => $request->input('name'),
                'email' => $request->input('email'),
                'phone' => $request->input('phone') ?? null,
                'password' => Hash::make($request->input('password')),
                'role' => 'passenger',
                'tenant_id' => $tenantId,
                'status' => 'active',
            ]);

            // Create Customer record linked to User
            $customerData = [
                'name' => $request->input('name'),
                'phone' => $request->input('phone') ?? null,
                'email' => $request->input('email'),
                'tenant_id' => $tenantId,
                'user_id' => $newUser->id,
            ];

            $customer = Customer::create($customerData);

            return response()->json([
                'success' => true,
                'message' => 'Customer created successfully',
                'data' => array_merge($customer->toArray(), [
                    'user_id' => $newUser->id,
                    'email' => $newUser->email
                ])
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error creating customer: ' . $e->getMessage(),
            ], 500);
        }
    }
}
