<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\PeerMobileLostPhone;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LostPhoneApiController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $requestedPeCode = trim((string) $request->query('pe_code', ''));
        if ($requestedPeCode !== '') {
            $normalizedRequestedPeCode = $this->normalizePeCode($requestedPeCode);

            $directMatch = PeerMobileLostPhone::query()
                ->where('status', PeerMobileLostPhone::STATUS_ACTIVE)
                ->where('pe_code', $requestedPeCode)
                ->exists();

            $normalizedMatch = false;
            if (!$directMatch && $normalizedRequestedPeCode !== '') {
                $activePeCodes = PeerMobileLostPhone::query()
                    ->where('status', PeerMobileLostPhone::STATUS_ACTIVE)
                    ->pluck('pe_code');

                $normalizedMatch = $activePeCodes->contains(function ($value) use ($normalizedRequestedPeCode) {
                    return $this->normalizePeCode((string) $value) === $normalizedRequestedPeCode;
                });
            }

            return $this->jsonResponse([
                'pe_code' => $requestedPeCode,
                'wipe' => $directMatch || $normalizedMatch,
            ]);
        }

        $peCodes = PeerMobileLostPhone::query()
            ->where('status', PeerMobileLostPhone::STATUS_ACTIVE)
            ->orderBy('pe_code')
            ->pluck('pe_code')
            ->map(function ($value) {
                return trim((string) $value);
            })
            ->filter(function (string $value) {
                return $value !== '';
            })
            ->values();

        return $this->jsonResponse([
            'lost_phone_pe_codes' => $peCodes,
            'count' => $peCodes->count(),
        ]);
    }

    private function normalizePeCode(string $rawPeCode): string
    {
        $trimmed = trim($rawPeCode);
        if ($trimmed === '') {
            return '';
        }

        if (preg_match('/^\d+$/', $trimmed) === 1) {
            $normalized = ltrim($trimmed, '0');
            return $normalized === '' ? '0' : $normalized;
        }

        return strtolower($trimmed);
    }

    private function jsonResponse(array $payload): JsonResponse
    {
        return response()
            ->json($payload)
            ->withHeaders([
                'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
                'Pragma' => 'no-cache',
                'Access-Control-Allow-Origin' => '*',
            ]);
    }
}
