<?php

namespace App\Http\Controllers\Api\Mobile\Rider;

use App\Http\Controllers\Controller;
use App\Models\LocalDeliveryZone;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    public function zones()
    {
        $zones = LocalDeliveryZone::where('is_enabled', true)
            ->select('id', 'name', 'lat', 'lng', 'radius', 'delivery_charge')
            ->get();

        return response()->json(['status' => 'success', 'data' => $zones]);
    }

    public function submitVerification(Request $request)
    {
        $rider = $request->user();

        $request->merge([
            'zone_ids' => $this->normalizeZoneIds($request),
        ]);

        $validated = $request->validate([
            'zone_ids' => 'required|array|min:1',
            'zone_ids.*' => 'integer|exists:local_delivery_zones,id',
            'nid_front' => 'required|image|mimes:jpeg,png,jpg,webp|max:4096',
            'nid_back' => 'required|image|mimes:jpeg,png,jpg,webp|max:4096',
        ]);

        if ($rider->nid_front && Storage::disk('public')->exists(str_replace('storage/', '', $rider->nid_front))) {
            Storage::disk('public')->delete(str_replace('storage/', '', $rider->nid_front));
        }
        if ($rider->nid_back && Storage::disk('public')->exists(str_replace('storage/', '', $rider->nid_back))) {
            Storage::disk('public')->delete(str_replace('storage/', '', $rider->nid_back));
        }

        $frontPath = $request->file('nid_front')->store('riders/nid', 'public');
        $backPath = $request->file('nid_back')->store('riders/nid', 'public');

        $rider->update([
            'nid_front' => 'storage/' . $frontPath,
            'nid_back' => 'storage/' . $backPath,
            'zone_ids' => array_values(array_unique($validated['zone_ids'])),
            'approval_status' => 'awaiting_admin',
        ]);

        return response()->json([
            'status' => 'success',
            'message' => 'Verification submitted. Admin will review your request.',
            'data' => [
                'approval_status' => $rider->approval_status,
            ],
        ]);
    }

    public function updatePhoto(Request $request)
    {
        $rider = $request->user();

        $request->validate([
            'photo' => 'required|image|mimes:jpeg,png,jpg,webp|max:4096',
        ]);

        if ($rider->photo && Storage::disk('public')->exists(str_replace('storage/', '', $rider->photo))) {
            Storage::disk('public')->delete(str_replace('storage/', '', $rider->photo));
        }

        $path = $request->file('photo')->store('riders/photos', 'public');
        $rider->update(['photo' => 'storage/' . $path]);

        return response()->json([
            'status' => 'success',
            'message' => 'Profile photo updated',
            'data' => [
                'photo' => url($rider->photo),
            ],
        ]);
    }

    public function updateLocation(Request $request)
    {
        $validated = $request->validate([
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
        ]);

        $request->user()->update([
            'current_lat' => $validated['lat'],
            'current_lng' => $validated['lng'],
        ]);

        return response()->json(['status' => 'success', 'message' => 'Location updated']);
    }

    /**
     * Normalize zone_ids from multipart, JSON, or indexed form fields.
     *
     * @return array<int, int>
     */
    protected function normalizeZoneIds(Request $request): array
    {
        $raw = $request->input('zone_ids');

        if (is_array($raw)) {
            return array_values(array_filter(array_map('intval', $raw)));
        }

        if (is_string($raw) && $raw !== '') {
            $decoded = json_decode($raw, true);
            if (is_array($decoded)) {
                return array_values(array_filter(array_map('intval', $decoded)));
            }
            return array_values(array_filter(array_map('intval', explode(',', $raw))));
        }

        // zone_ids[0], zone_ids[1], ...
        $indexed = [];
        foreach ($request->all() as $key => $value) {
            if (preg_match('/^zone_ids\[(\d+)\]$/', (string) $key, $m)) {
                $indexed[(int) $m[1]] = (int) $value;
            }
        }
        if ($indexed !== []) {
            ksort($indexed);
            return array_values(array_filter($indexed));
        }

        return [];
    }
}
