<?php

namespace App\Modules\PLATFORM\Settings\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\PLATFORM\Settings\Models\State;
use App\Modules\PLATFORM\Settings\Models\Country;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;

class StateController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = State::with('country');

            return DataTables::of($query)
                ->addIndexColumn()
                ->addColumn('country', function ($row) {
                    return $row->country?->name;
                })
                ->editColumn('status', function ($row) {
                    return $row->status
                        ? '<span class="badge bg-success">Active</span>'
                        : '<span class="badge bg-danger">Inactive</span>';
                })
                ->addColumn('action', function ($row) {
                    return view('settings::states/partials/actions', compact('row'))->render();
                })
                ->rawColumns(['status', 'action'])
                ->make(true);
        }

        return view('settings::states/index');
    }

    public function create()
    {
        $countries = Country::where('status', true)->orderBy('name')->get();

        return view('settings::states/create', compact('countries'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'country_id' => 'required|exists:countries,id',
            'name'       => 'required|string|max:150',
            'code'       => 'nullable|string|max:10',
        ], [
            'country_id.required' => 'Please select a country.',
            'country_id.exists' => 'The selected country is invalid.',
            'name.required' => 'State name is required.',
            'name.max' => 'State name must not exceed 150 characters.',
            'code.max' => 'Code must not exceed 10 characters.',
        ]);

        State::create([
            'country_id' => $request->country_id,
            'name'       => $request->name,
            'code'       => $request->code,
            'status'     => $request->boolean('status'),
        ]);

        return response()->json([
            'status'  => true,
            'message' => 'State created successfully',
        ]);
    }

    public function edit(State $state)
    {
        $countries = Country::where('status', true)->orderBy('name')->get();

        return view('settings::states/edit', compact('state', 'countries'));
    }

    public function update(Request $request, State $state)
    {
        $request->validate([
            'country_id' => 'required|exists:countries,id',
            'name'       => 'required|string|max:150',
            'code'       => 'nullable|string|max:10',
        ], [
            'country_id.required' => 'Please select a country.',
            'country_id.exists' => 'The selected country is invalid.',
            'name.required' => 'State name is required.',
            'name.max' => 'State name must not exceed 150 characters.',
            'code.max' => 'Code must not exceed 10 characters.',
        ]);

        $state->update([
            'country_id' => $request->country_id,
            'name'       => $request->name,
            'code'       => $request->code,
            'status'     => $request->boolean('status'),
        ]);

        return response()->json([
            'status'  => true,
            'message' => 'State updated successfully',
        ]);
    }

    public function destroy(State $state)
    {
        // Check if state is being used by cities
        $cityCount = DB::table('cities')->where('state_id', $state->id)->count();

        if ($cityCount > 0) {
            return response()->json([
                'status' => false,
                'message' => 'Cannot delete this state. It is currently being used by ' . $cityCount . ' city(ies). Please remove or reassign all cities before deleting this state.',
            ], 422);
        }

        $state->delete();

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

    public function status(State $state)
    {
        $state->update([
            'status' => ! $state->status,
        ]);

        return response()->json([
            'status'  => true,
            'message' => 'Status updated successfully',
        ]);
    }
}
