<?php

namespace App\Http\Controllers\CRM;

use App\Models\CRM\City;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CityController extends Controller
{
    public function show(City $city)
    {
        return [
            'value'           => $city->id,
            'label'           => (!empty($city->zip) ? "({$city->zip}) " : '')
                . "{$city->name}, {$city->municipality}"
                . ", {$city->country->name}",
            'dropdown_label'  => (!empty($city->zip) ? "({$city->zip}) " : '')
                . "{$city->name}, {$city->municipality}"
                . ", {$city->country->name}",
        ];
    }

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

        $cities = City::query()
            ->where(function ($query) use ($term) {
                $query->where('name', 'like', "%{$term}%")
                    ->orWhere('municipality', 'like', "%{$term}%")
                    ->orWhere('zip', 'like', "%{$term}%");
            })
            ->orderByRaw("
                (
                    -- ZIP Score: 100 points if zip is non-empty and matches the term; 50 if it exists.
                    CASE 
                        WHEN (zip IS NOT NULL AND zip <> '' AND zip LIKE ?) THEN 100
                        WHEN (zip IS NOT NULL AND zip <> '') THEN 50
                        ELSE 0
                    END
                    +
                    -- Name Score: 10 points if the name matches the term.
                    CASE 
                        WHEN name LIKE ? THEN 10
                        ELSE 0
                    END
                    +
                    -- Municipality Score: 5 points if the municipality matches the term.
                    CASE 
                        WHEN municipality LIKE ? THEN 5
                        ELSE 0
                    END
                ) DESC
                ", ["%{$term}%", "%{$term}%", "%{$term}%"])
            // Additional ordering: records with non-empty zip are sorted by their numeric value (lower first)
            ->orderByRaw("CASE WHEN (zip IS NOT NULL AND zip <> '') THEN CAST(zip AS UNSIGNED) ELSE 999999 END ASC")
            ->orderBy('name') // fallback ordering for consistency
            ->limit(20)
            ->get();

        // Return two labels:
        return $cities->map(function ($c) {
            return [
                'value'           => $c->id,
                'label'           => (!empty($c->zip) ? "({$c->zip}) " : '')
                    . "{$c->name}, {$c->municipality}"
                    . ", {$c->country->name}",
                'dropdown_label'  => (!empty($c->zip) ? "({$c->zip}) " : '')
                    . "{$c->name}, {$c->municipality}"
                    . ", {$c->country->name}",
            ];
        });
    }
}
