<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class LawyerController extends Controller
{
    public function lawyers()
    {
        $lawyerGroups = \App\Models\LawyerGroup::all();
        $lawyers = \App\Models\Lawyer::all();
        return view('modules.edit.add-lawyer', compact('lawyerGroups', 'lawyers'));
    }

    public function addLawyer()
    {
        $lawyerGroups = \App\Models\LawyerGroup::all();
        $lawyers = \App\Models\Lawyer::all();
        $lawyerTiers = \App\Models\LawyerTier::all();
        $lawyerTypes = \App\Models\LawyerType::all();
        return view('modules.edit.add-lawyer', compact('lawyerGroups', 'lawyers', 'lawyerTiers', 'lawyerTypes'));
    }

    public function storeLawyer(Request $request)
    {
        $lawyerTypeNames = \App\Models\LawyerType::pluck('lawyer_type_name')->toArray();

        $validated = $request->validate([
            'lawyer_id' => 'required|string|max:50|unique:lawyers',
            'first_name' => 'required|string|max:100',
            'last_name' => 'required|string|max:100',
            'email' => 'nullable|email|max:255',
            'phone_primary' => 'nullable|string|max:20',
            'phone_secondary' => 'nullable|string|max:20',
            'lawyer_group' => 'nullable|string|max:50',
            'bar_number' => 'nullable|string|max:50',
            'date_of_admission' => 'nullable|date',
            'status' => 'required|in:Active,Inactive,Suspended',
            'lawyer_type' => 'nullable|in:' . implode(',', $lawyerTypeNames),
            'tariff' => 'nullable|string|max:50',
            'tier' => 'nullable|integer',
            'notes' => 'nullable|string',
        ]);

        // Map form field names to model field names
        $validated['certificate_number'] = $validated['bar_number'];
        $validated['lawyer_tier'] = $validated['tier'];
        unset($validated['bar_number'], $validated['tier']);

        \App\Models\Lawyer::create($validated);

        return redirect()->route('modules.edit.lawyer-management')->with('success', 'Lawyer added successfully.');
    }

    public function editLawyer($id)
    {
        $lawyer = \App\Models\Lawyer::findOrFail($id);
        $lawyerGroups = \App\Models\LawyerGroup::all();
        $lawyerTypes = \App\Models\LawyerType::all();
        $lawyerTiers = \App\Models\LawyerTier::all();
        return view('modules.edit.edit-lawyer', compact('lawyer', 'lawyerGroups', 'lawyerTypes', 'lawyerTiers'));
    }

    public function updateLawyer(Request $request, $id)
    {
        $lawyer = \App\Models\Lawyer::findOrFail($id);

        $lawyerTypeNames = \App\Models\LawyerType::pluck('lawyer_type_name')->toArray();

        $validated = $request->validate([
            'first_name' => 'required|string|max:100',
            'last_name' => 'required|string|max:100',
            'email' => 'nullable|email|max:255',
            'phone_primary' => 'nullable|string|max:20',
            'phone_secondary' => 'nullable|string|max:20',
            'lawyer_group' => 'nullable|string|max:50',
            'bar_number' => 'nullable|string|max:50',
            'date_of_admission' => 'nullable|date',
            'status' => 'required|in:Active,Inactive,Suspended',
            'lawyer_type' => 'nullable|in:' . implode(',', $lawyerTypeNames),
            'tariff' => 'nullable|string|max:50',
            'tier' => 'nullable|integer',
            'notes' => 'nullable|string',
        ]);

        // Map form field names to model field names
        $validated['certificate_number'] = $validated['bar_number'];
        $validated['lawyer_tier'] = $validated['tier'];
        unset($validated['bar_number'], $validated['tier']);

        $lawyer->update($validated);

        return redirect()->route('modules.edit.lawyer-management')->with('success', 'Lawyer updated successfully.');
    }

    public function destroyLawyer($id)
    {
        $lawyer = \App\Models\Lawyer::findOrFail($id);
        $lawyer->delete();

        return redirect()->route('modules.edit.lawyer-management')->with('success', 'Lawyer deleted successfully.');
    }

    public function showLawyer($id)
    {
        $lawyer = \App\Models\Lawyer::findOrFail($id);
        return view('modules.processing.lawyer-show', compact('lawyer'));
    }

    // Alias methods for route compatibility
    public function index()
    {
        return view('modules.edit.lawyer');
    }

    public function create()
    {
        return $this->addLawyer();
    }

    public function store(Request $request)
    {
        return $this->storeLawyer($request);
    }

    public function show($id)
    {
        return $this->showLawyer($id);
    }

    public function edit($id)
    {
        return $this->editLawyer($id);
    }

    public function update(Request $request, $id)
    {
        return $this->updateLawyer($request, $id);
    }

    public function destroy($id)
    {
        return $this->destroyLawyer($id);
    }

    public function management()
    {
        $lawyerGroups = \App\Models\LawyerGroup::all();
        $lawyers = \App\Models\Lawyer::all();
        return view('modules.edit.lawyer-management', compact('lawyerGroups', 'lawyers'));
    }

    public function search(Request $request)
    {
        $query = $request->get('q', '');
        $query = trim($query);

        if (strlen($query) < 2) {
            return response()->json([]);
        }

        $lawyers = \App\Models\Lawyer::query();

        // Split query by space to handle first and last name search
        $parts = explode(' ', $query, 2);

        if (count($parts) === 1) {
            // Single word: search in both first_name and last_name
            $searchTerm = $parts[0];
            $lawyers->where(function ($q) use ($searchTerm) {
                $q->where('first_name', 'LIKE', '%' . $searchTerm . '%')
                  ->orWhere('last_name', 'LIKE', '%' . $searchTerm . '%');
            });
        } else {
            // Two words: first word searches first_name, second word searches last_name
            $firstName = $parts[0];
            $lastName = $parts[1];

            $lawyers->where(function ($q) use ($firstName, $lastName) {
                $q->where('first_name', 'LIKE', '%' . $firstName . '%')
                  ->where('last_name', 'LIKE', '%' . $lastName . '%');
            });
        }

        $results = $lawyers->limit(10)->get(['lawyer_id', 'first_name', 'last_name']);

        // Format results with full_name
        $formattedResults = $results->map(function ($lawyer) {
            return [
                'lawyer_id' => $lawyer->lawyer_id,
                'full_name' => $lawyer->first_name . ' ' . $lawyer->last_name,
            ];
        });

        return response()->json($formattedResults);
    }
}
