<?php

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

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

class CityController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = City::with(['country', 'state']);

            return DataTables::of($query)
                ->addIndexColumn()
                ->addColumn('country', fn ($row) => $row->country?->name)
                ->addColumn('state', fn ($row) => $row->state?->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::cities/partials/actions', compact('row'))->render();
                })
                ->rawColumns(['status', 'action'])
                ->make(true);
        }

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

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

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

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

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

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

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

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

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

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

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

    public function destroy(City $city)
    {
        // Check if city is being used by branches
        $branchCount = DB::table('branches')->where('city_id', $city->id)->count();

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

        // Check if city is being used by bank_branches
        $bankBranchCount = DB::table('bank_branches')->where('city_id', $city->id)->count();

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

        // Check if city is being used by employees
        $employeeCount = DB::table('employees')->where('city_id', $city->id)->count();

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

        $city->delete();

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

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

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

    /* ================= AJAX HELPERS ================= */

    public function statesByCountry(Country $country)
    {
        return State::where('country_id', $country->id)
            ->where('status', true)
            ->orderBy('name')
            ->get(['id', 'name']);
    }
}
