<?php

namespace App\Controllers;

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

class Countries extends AdminBaseController
{
    public $title = 'Countries';
    public $menu = 'locations';
    public $submenu = 'countries';

    public function index()
    {
        $this->permissionCheck('locations_manage');
        $countries = (new RewarderCountryModel())->orderBy('name', 'asc')->findAll();
        return view('admin/locations/countries/list', compact('countries'));
    }

    public function add()
    {
        $this->permissionCheck('locations_manage');
        return view('admin/locations/countries/add');
    }

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

        (new RewarderCountryModel())->create([
            'name' => trim((string) post('name')),
            'code' => trim((string) post('code')) ?: null,
            '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('countries')->with('notifySuccess', 'Country created successfully');
    }

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

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

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

        return redirect()->to('countries')->with('notifySuccess', 'Country updated successfully');
    }

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

        $hasChildren = (new RewarderStateModel())->where('country_id', (int) $id)->countAllResults();
        if ($hasChildren) {
            return redirect()->to('countries')->with('notifyError', 'Cannot delete country that has states');
        }

        (new RewarderCountryModel())->delete((int) $id);
        return redirect()->to('countries')->with('notifySuccess', 'Country deleted successfully');
    }
}

