<?php

namespace App\Http\Controllers\Api\Admin;

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

class LocationController extends Controller
{
    public function index()
    {
        $locations = Location::orderBy('name', 'asc')->get();
        return response()->json($locations);
    }

    public function store(Request $request)
    {
        $request->validate([
            'country' => 'required|string|max:100',
            'state' => 'required|string|max:100',
            'district' => 'required|string|max:100',
            'name' => 'required|string|max:100|unique:locations,name',
            'slug' => 'required|string|max:100|unique:locations,slug',
            'status' => 'boolean',
            'meta_title' => 'nullable|string|max:255',
            'meta_desc' => 'nullable|string'
        ]);

        $location = Location::create($request->all());

        return response()->json([
            'message' => 'Location created successfully',
            'location' => $location
        ], 201);
    }

    public function update(Request $request, $id)
    {
        $location = Location::findOrFail($id);

        $request->validate([
            'country' => 'required|string|max:100',
            'state' => 'required|string|max:100',
            'district' => 'required|string|max:100',
            'name' => 'required|string|max:100|unique:locations,name,' . $location->id,
            'slug' => 'required|string|max:100|unique:locations,slug,' . $location->id,
            'status' => 'boolean',
            'meta_title' => 'nullable|string|max:255',
            'meta_desc' => 'nullable|string'
        ]);

        $location->update($request->all());

        return response()->json([
            'message' => 'Location updated successfully',
            'location' => $location
        ]);
    }

    public function destroy($id)
    {
        $location = Location::findOrFail($id);
        $location->delete();

        return response()->json(['message' => 'Location deleted successfully']);
    }
}
