<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class JurisdictionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = DB::table('jurisdictions');

        // Search
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('code', 'like', "%{$search}%")
                  ->orWhere('name', 'like', "%{$search}%")
                  ->orWhere('display_name', 'like', "%{$search}%");
            });
        }

        // Filter by type
        if ($request->has('type') && $request->type) {
            $query->where('type', $request->type);
        }

        // Filter by status
        if ($request->has('status') && $request->status !== '') {
            $query->where('active', $request->status === 'active');
        }

        $jurisdictions = $query->orderBy('type')->orderBy('name')->get();

        return response()->json([
            'data' => $jurisdictions
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'code' => 'required|string|max:10|unique:jurisdictions,code',
            'name' => 'required|string|max:255',
            'display_name' => 'required|string|max:255',
            'type' => 'required|in:federal,provincial,territorial',
            'active' => 'boolean'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        $id = DB::table('jurisdictions')->insertGetId([
            'code' => $request->code,
            'name' => $request->name,
            'display_name' => $request->display_name,
            'type' => $request->type,
            'active' => $request->active ?? true,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        $jurisdiction = DB::table('jurisdictions')->find($id);

        return response()->json([
            'success' => true,
            'data' => $jurisdiction
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $jurisdiction = DB::table('jurisdictions')->find($id);

        if (!$jurisdiction) {
            return response()->json([
                'success' => false,
                'message' => 'Jurisdiction not found'
            ], 404);
        }

        return response()->json([
            'data' => $jurisdiction
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $jurisdiction = DB::table('jurisdictions')->find($id);

        if (!$jurisdiction) {
            return response()->json([
                'success' => false,
                'message' => 'Jurisdiction not found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'code' => 'required|string|max:10|unique:jurisdictions,code,' . $id,
            'name' => 'required|string|max:255',
            'display_name' => 'required|string|max:255',
            'type' => 'required|in:federal,provincial,territorial',
            'active' => 'boolean'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        DB::table('jurisdictions')->where('id', $id)->update([
            'code' => $request->code,
            'name' => $request->name,
            'display_name' => $request->display_name,
            'type' => $request->type,
            'active' => $request->active ?? true,
            'updated_at' => now()
        ]);

        $jurisdiction = DB::table('jurisdictions')->find($id);

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $jurisdiction = DB::table('jurisdictions')->find($id);

        if (!$jurisdiction) {
            return response()->json([
                'success' => false,
                'message' => 'Jurisdiction not found'
            ], 404);
        }

        DB::table('jurisdictions')->where('id', $id)->delete();

        return response()->json([
            'success' => true,
            'message' => 'Jurisdiction deleted successfully'
        ]);
    }
}
