<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class SearchController extends Controller
{
    /**
     * Search for contacts/clients by phone number for 3CX integration
     * Route: GET /search?number=07999563176
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchByNumber(Request $request)
    {
        $number = $request->get('number');
        
        Log::info('[3CX Search] Phone number search request', [
            'number' => $number,
            'user_agent' => $request->userAgent(),
            'ip' => $request->ip()
        ]);

        if (empty($number)) {
            return response()->json([
                'success' => false,
                'message' => 'Phone number parameter is required',
                'data' => []
            ], 400);
        }

        // Clean the number - remove spaces, dashes, etc.
        $cleanNumber = preg_replace('/[^0-9+]/', '', $number);
        
        Log::info('[3CX Search] Cleaned number for search', [
            'original' => $number,
            'cleaned' => $cleanNumber
        ]);

        $results = [];

        try {
            // Search in clients table for phone numbers
            $clients = DB::table('clients')
                ->select('id', 'name', 'phone', 'mobile', 'email', 'company')
                ->where(function($query) use ($cleanNumber) {
                    $query->where('phone', 'like', '%' . $cleanNumber . '%')
                          ->orWhere('mobile', 'like', '%' . $cleanNumber . '%');
                })
                ->limit(10) // Limit results for performance
                ->get();

            foreach ($clients as $client) {
                $results[] = [
                    'id' => $client->id,
                    'name' => $client->name,
                    'company' => $client->company,
                    'phone' => $client->phone ?: $client->mobile,
                    'email' => $client->email,
                    'type' => 'client'
                ];
            }

            Log::info('[3CX Search] Search completed', [
                'number' => $cleanNumber,
                'results_count' => count($results)
            ]);

            // Return results in format expected by 3CX
            if (!empty($results)) {
                // Return first match for 3CX caller ID
                $firstResult = $results[0];
                return response()->json([
                    'success' => true,
                    'id' => $firstResult['id'],
                    'name' => $firstResult['name'],
                    'company' => $firstResult['company'],
                    'phone' => $firstResult['phone'],
                    'email' => $firstResult['email'],
                    'type' => $firstResult['type'],
                    'all_matches' => $results // Include all matches for debugging
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'No matching contacts found',
                    'data' => []
                ], 404);
            }

        } catch (\Exception $e) {
            Log::error('[3CX Search] Search failed', [
                'number' => $cleanNumber,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Search failed: ' . $e->getMessage(),
                'data' => []
            ], 500);
        }
    }
}