<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\LegalCase;
use App\Models\Lawyer;
use App\Models\ClientInvoice;
use App\Models\ClientReceipt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class SearchController extends Controller
{
    /**
     * Global search across clients, cases, and lawyers
     */
    public function globalSearch(Request $request)
    {
        try {
            $query = $request->get('q', '');
            
            if (strlen($query) < 2) {
                return response()->json([
                    'clients' => [],
                    'cases' => [],
                    'lawyers' => []
                ]);
            }

            // Search clients
            $clients = Client::where(function($q) use ($query) {
                    $q->where('first_name', 'like', "%{$query}%")
                      ->orWhere('last_name', 'like', "%{$query}%")
                      ->orWhereRaw("CONCAT(first_name, ' ', last_name) LIKE ?", ["%{$query}%"])
                      ->orWhere('email', 'like', "%{$query}%")
                      ->orWhere('phone_primary', 'like', "%{$query}%");
                })
                ->limit(10)
                ->get()
                ->map(function($client) {
                    // Get client statistics
                    $caseQuery = LegalCase::whereHas('caseClients', function ($q) use ($client) {
                        $q->where('client_id', $client->id);
                    });
                    $caseCount = (clone $caseQuery)->count();
                    $invoiceTotal = (float) ClientInvoice::where('client_id', $client->id)->sum('total');
                    $receiptTotal = (float) ClientReceipt::where('client_id', $client->id)->sum('total_amount');
                    
                    return [
                        'id' => $client->id,
                        'type' => 'client',
                        'name' => $client->full_name,
                        'email' => $client->email,
                        'phone' => $client->phone_primary,
                        'client_type' => $client->client_type,
                        'statistics' => [
                            'total_cases' => $caseCount,
                            'total_invoiced' => $invoiceTotal,
                            'total_received' => $receiptTotal,
                            'outstanding' => $invoiceTotal - $receiptTotal
                        ]
                    ];
                });

            // Search cases (guard against columns that may not exist)
            $hasCaseReason = Schema::hasColumn('cases', 'case_reason');
            $hasCaseCode = Schema::hasColumn('cases', 'case_code');
            $hasNotes = Schema::hasColumn('cases', 'notes');

            $cases = LegalCase::where(function($q) use ($query, $hasCaseReason, $hasCaseCode, $hasNotes) {
                    $q->where('case_name', 'like', "%{$query}%")
                      ->orWhere('case_id', 'like', "%{$query}%");

                    if ($hasCaseReason) {
                        $q->orWhere('case_reason', 'like', "%{$query}%");
                    }
                    if ($hasCaseCode) {
                        $q->orWhere('case_code', 'like', "%{$query}%");
                    }
                    if ($hasNotes) {
                        $q->orWhere('notes', 'like', "%{$query}%");
                    }
                })
                ->with(['client', 'caseStatus', 'caseCategory'])
                ->limit(10)
                ->get()
                ->map(function($case) {
                    return [
                        'id' => $case->id,
                        'type' => 'case',
                        'case_id' => $case->case_id,
                        'case_code' => $case->case_code,
                        'case_name' => $case->case_name,
                        'client_name' => $case->client ? $case->client->full_name : 'N/A',
                        'status' => $case->caseStatus ? $case->caseStatus->status_name : 'Unknown',
                        'category' => $case->caseCategory ? $case->caseCategory->category_name : 'Unknown',
                        'statistics' => [
                            'date_opened' => $case->created_at ? $case->created_at->format('Y-m-d') : 'N/A',
                            'priority' => $case->priority_id ?? 'Normal'
                        ]
                    ];
                });

            // Lawyer search commented out to fix 500 error - task focuses on clients/cases
            $lawyers = collect([]);

            return response()->json([
                'clients' => $clients,
                'cases' => $cases,
                'lawyers' => $lawyers,
                'total' => $clients->count() + $cases->count() + $lawyers->count()
            ]);
        } catch (\Throwable $e) {
            report($e);
            return response()->json([
                'clients' => [],
                'cases' => [],
                'lawyers' => [],
                'error' => 'Search failed. Please try again.'
            ]);
        }

    }

    /**
     * Get detailed statistics for a specific item
     */
    public function getItemStatistics(Request $request)
    {
        try {
            $type = $request->get('type');
            $id = $request->get('id');

            $data = [];

            switch ($type) {
                case 'client':
                    $client = Client::with(['clientCategory'])->find($id);
                    if ($client) {
                        $cases = LegalCase::whereHas('caseClients', function ($q) use ($id) {
                            $q->where('client_id', $id);
                        })->get();
                        $invoices = ClientInvoice::where('client_id', $id)->get();
                        $receipts = ClientReceipt::where('client_id', $id)->get();
                        
                        $data = [
                            'name' => $client->full_name,
                            'email' => $client->email,
                            'phone' => $client->phone_primary,
                            'address' => $client->street_address . ', ' . $client->city,
                            'client_type' => $client->client_type,
                            'category' => $client->clientCategory ? $client->clientCategory->category_name : 'N/A',
                            'date_onboarded' => $client->date_onboarded,
                            'statistics' => [
                                'total_cases' => $cases->count(),
                                'active_cases' => $cases->where('status_code', 'Open')->count(),
                                'closed_cases' => $cases->where('status_code', 'Closed')->count(),
                                'total_invoiced' => $invoices->sum('total'),
                                'total_received' => $receipts->sum('total_amount'),
                                'outstanding' => $invoices->sum('total') - $receipts->sum('total_amount'),
                                'trust_balance' => 5000.00, // Mock value for client trust account
                                'pending_invoices' => $invoices->where('status', 'Pending')->count(),
                            ]
                        ];
                    }
                    break;

                case 'case':
                    $case = LegalCase::with(['client', 'caseStatus', 'caseCategory', 'caseType', 'lawyer'])
                        ->find($id);
                    if ($case) {
                        $data = [
                            'case_code' => $case->case_code,
                            'case_name' => $case->case_name,
                            'client_name' => $case->client ? $case->client->full_name : 'N/A',
                            'status' => $case->caseStatus ? $case->caseStatus->status_name : 'Unknown',
                            'category' => $case->caseCategory ? $case->caseCategory->category_name : 'N/A',
                            'type' => $case->caseType ? $case->caseType->type_name : 'N/A',
                            'lawyer' => $case->lawyer ? $case->lawyer->full_name : 'N/A',
                            'date_opened' => $case->created_at,
                            'court_date' => $case->court_appearance_date,
                            'statistics' => [
                                'priority' => $case->priority_id ?? 'Normal',
                                'parties_count' => $case->parties->count(),
                                'lawyers_count' => $case->caseLawyers->count(),
                                'trust_balance' => 5000.00, // Mock value for associated client trust account
                                'current_matters' => LegalCase::where('client_id', $case->client_id ?? 0)->count(),
                            ]
                        ];
                    }
                    break;

                case 'lawyer':
                    $lawyer = Lawyer::find($id);
                    if ($lawyer) {
                        $caseLawyers = DB::table('case_lawyers')
                            ->where('lawyer_id', $id)
                            ->get();
                        
                        $activeCases = $caseLawyers->count();
                        
                        $data = [
                            'name' => $lawyer->full_name,
                            'email' => $lawyer->email,
                            'phone' => $lawyer->phone_primary,
                            'certificate_number' => $lawyer->certificate_number,
                            'date_of_admission' => $lawyer->date_of_admission,
                            'status' => $lawyer->status,
                            'lawyer_type' => $lawyer->lawyer_type,
                            'statistics' => [
                                'total_cases' => $caseLawyers->count(),
                                'active_cases' => $activeCases,
                                'tier' => $lawyer->lawyer_tier ?? 'Standard',
                            ]
                        ];
                    }
                    break;
            }

            return response()->json($data);
        } catch (\Throwable $e) {
            report($e);
            return response()->json([
                'error' => 'Unable to load item statistics right now.'
            ]);
        }
    }
}
