<?php

namespace App\Controllers;

use App\Models\RewarderCountryModel;
use App\Models\RewarderStateModel;
use App\Models\RewarderCityModel;

class States extends AdminBaseController
{
    public $title = 'States';
    public $menu = 'locations';
    public $submenu = 'states';

    public function index()
    {
        $this->permissionCheck('locations_manage');
        $states = (new RewarderStateModel())
            ->select('rewarder_states.*, rewarder_countries.name AS country_name')
            ->join('rewarder_countries', 'rewarder_countries.id = rewarder_states.country_id', 'left')
            ->orderBy('rewarder_countries.name', 'asc')
            ->orderBy('rewarder_states.name', 'asc')
            ->findAll();
        return view('admin/locations/states/list', compact('states'));
    }

    public function add()
    {
        $this->permissionCheck('locations_manage');
        $countries = (new RewarderCountryModel())->activeList();
        return view('admin/locations/states/add', compact('countries'));
    }

    public function save()
    {
        $this->permissionCheck('locations_manage');
        postAllowed();

        (new RewarderStateModel())->create([
            'country_id' => (int) post('country_id'),
            'name' => trim((string) post('name')),
            'status' => (int) post('status'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        return redirect()->to('states')->with('notifySuccess', 'State created successfully');
    }

    public function edit($id)
    {
        $this->permissionCheck('locations_manage');
        $state = (new RewarderStateModel())->getById($id);
        $countries = (new RewarderCountryModel())->activeList();
        return view('admin/locations/states/edit', compact('state', 'countries'));
    }

    public function update($id)
    {
        $this->permissionCheck('locations_manage');
        postAllowed();

        (new RewarderStateModel())->update($id, [
            'country_id' => (int) post('country_id'),
            'name' => trim((string) post('name')),
            'status' => (int) post('status'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        return redirect()->to('states')->with('notifySuccess', 'State updated successfully');
    }

    public function delete($id)
    {
        $this->permissionCheck('locations_manage');

        $hasChildren = (new RewarderCityModel())->where('state_id', (int) $id)->countAllResults();
        if ($hasChildren) {
            return redirect()->to('states')->with('notifyError', 'Cannot delete state that has cities');
        }

        (new RewarderStateModel())->delete((int) $id);
        return redirect()->to('states')->with('notifySuccess', 'State deleted successfully');
    }
}

