<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Governorate;
use App\Models\City;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ClientController extends Controller
{
    public function index()
    {
        $clients = Client::with(['governorate', 'city'])
            ->latest()
            ->paginate(10);
        
        return view('clients.index', compact('clients'));
    }

    public function create()
    {
        $governorates = Governorate::orderBy('name')->get();
        $cities = City::where('governorate_id', $governorates->first()->id ?? null)->get();
        
        return view('clients.create', compact('governorates', 'cities'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'contact_person' => 'nullable|string|max:255',
            'phone' => 'required|string|max:20',
            'email' => 'nullable|email',
            'governorate_id' => 'required|exists:governorates,id',
            'city_id' => 'required|exists:cities,id',
            'area' => 'required|string|max:255',
            'address' => 'nullable|string',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
        ]);

        try {
            DB::beginTransaction();
            
            $client = Client::create([
                'name' => $request->name,
                'contact_person' => $request->contact_person,
                'phone' => $request->phone,
                'email' => $request->email,
                'governorate_id' => $request->governorate_id,
                'city_id' => $request->city_id,
                'area' => $request->area,
                'latitude' => $request->latitude,
                'longitude' => $request->longitude,
                'address' => $request->address,
                'status' => 'active',
            ]);
            
            DB::commit();
            
            return redirect()->route('clients.index')
                ->with('success', 'Client created successfully.');
                
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Failed to create client: ' . $e->getMessage());
        }
    }

    public function show(Client $client)
    {
        $client->load(['governorate', 'city', 'visits' => function($query) {
            $query->latest()->limit(5);
        }]);
        
        return view('clients.show', compact('client'));
    }

    public function edit(Client $client)
    {
        $governorates = Governorate::orderBy('name')->get();
        $cities = City::where('governorate_id', $client->governorate_id)->get();
        
        return view('clients.edit', compact('client', 'governorates', 'cities'));
    }

    public function update(Request $request, Client $client)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'contact_person' => 'nullable|string|max:255',
            'phone' => 'required|string|max:20',
            'email' => 'nullable|email',
            'governorate_id' => 'required|exists:governorates,id',
            'city_id' => 'required|exists:cities,id',
            'area' => 'required|string|max:255',
            'address' => 'nullable|string',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
            'status' => 'required|in:active,inactive',
        ]);

        try {
            DB::beginTransaction();
            
            $client->update([
                'name' => $request->name,
                'contact_person' => $request->contact_person,
                'phone' => $request->phone,
                'email' => $request->email,
                'governorate_id' => $request->governorate_id,
                'city_id' => $request->city_id,
                'area' => $request->area,
                'latitude' => $request->latitude,
                'longitude' => $request->longitude,
                'address' => $request->address,
                'status' => $request->status,
            ]);
            
            DB::commit();
            
            return redirect()->route('clients.index')
                ->with('success', 'Client updated successfully.');
                
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Failed to update client: ' . $e->getMessage());
        }
    }

    public function destroy(Client $client)
    {
        // Check if client has visits
        if ($client->visits()->count() > 0) {
            return redirect()->route('clients.index')
                ->with('error', 'Cannot delete client that has visits. Please delete visits first.');
        }

        $client->delete();

        return redirect()->route('clients.index')
            ->with('success', 'Client deleted successfully.');
    }

    public function getCities(Request $request)
    {
        $cities = City::where('governorate_id', $request->governorate_id)
            ->orderBy('name')
            ->get();
            
        return response()->json($cities);
    }

    public function searchLocation(Request $request)
    {
        // This would integrate with a geocoding service
        // For now, we'll return dummy data
        return response()->json([
            'latitude' => 30.0444,
            'longitude' => 31.2357,
            'address' => 'Cairo, Egypt'
        ]);
    }
}