<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CoverageArea;

class CoverageAreaController extends Controller
{

    public function index()
    {
        $coverageAreas = CoverageArea::orderBy('id', 'desc')->get();
        $coverageAreas = $coverageAreas->map(function ($area) {
            return [
                'id' => $area->id,
                'area' => $area->area,
                'cities' => json_decode($area->city, true),
            ];
        });
        return sendSuccessResponse($coverageAreas);
    }
    public function coverage()
    {
        $coverageAreas = CoverageArea::paginate(10);
        return view('Backend.CoverageArea.coverage', compact('coverageAreas'));
    }

    public function store(Request $request)
    {
        try {
            $request->validate([
                'area' => 'required|string|min:2|max:100',
                'cities' => 'required|array',
            ]);
            foreach ($request->cities as $city) {
                CoverageArea::create([
                    'area' => $request->area,
                    'city' => $city,
                ]);
            }
            toastr()->success('Coverage area added successfully');
            return redirect()->route('admin.coverage');
        } catch (\Exception $e) {
            toastr()->error('Failed to add coverage area');
            return redirect()->route('admin.coverage');
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $request->validate([
                'area' => 'required|string|min:2|max:100',
                'cities' => 'required|array',
            ]);
            $coverageArea = CoverageArea::find($id);

            foreach ($request->cities as $city) {
                $coverageArea->update([
                    'area' => $request->area,
                    'city' => $city,
                ]);
            }

            toastr()->success('Coverage area updated successfully');
            return redirect()->route('admin.coverage');
        } catch (\Exception $e) {
            dd($e);
            toastr()->error('Failed to update coverage area');
            return redirect()->route('admin.coverage');
        }
    }

    public function destroy($id)
    {
        try {
            $coverageArea = CoverageArea::find($id);
            $coverageArea->delete();
            toastr()->success('Coverage area deleted successfully');
            return redirect()->route('admin.coverage');
        } catch (\Exception $e) {
            toastr()->error('Failed to delete coverage area');
            return redirect()->route('admin.coverage');
        }
    }
}
