<?php

namespace Modules\Departments\Controllers;

use App\Controllers\BaseController;
use App\Models\BranchModel;
use App\Models\DepartmentModel;
use App\Models\EmployeeModel;
use Modules\Auth\Models\UserModel;
use Modules\Departments\Services\DepartmentService;

class DepartmentController extends BaseController
{
    protected DepartmentModel $departments;
    protected DepartmentService $service;
    protected BranchModel $branches;
    protected UserModel $users;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->departments = new DepartmentModel();
        $this->service     = new DepartmentService();
        $this->branches    = new BranchModel();
        $this->users       = new UserModel();
    }

    public function index()
    {
        $search   = trim((string) $this->request->getGet('q'));
        $status   = $this->request->getGet('status') ?: null;
        $branchId = $this->request->getGet('branch_id') ?: null;

        $departments = $this->departments
            ->scopeForList($search ?: null, $status, $branchId ? (int) $branchId : null)
            ->orderBy('name', 'ASC')
            ->findAll();

        $employeeModel = new EmployeeModel();
        $empCounts     = [];
        foreach ($departments as $d) {
            $empCounts[$d['id']] = $employeeModel->countByDepartment((int) $d['id']);
        }

        return view('Modules\Departments\Views\index', array_merge($this->baseViewData(), [
            'title'       => 'Departments',
            'departments' => $departments,
            'branches'    => $this->branches->orderBy('name', 'ASC')->findAll(),
            'empCounts'   => $empCounts,
            'filters'     => compact('search', 'status', 'branchId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Departments\Views\create', array_merge($this->baseViewData(), [
            'title'       => 'Add Department',
            'branches'    => $this->branches->orderBy('name', 'ASC')->findAll(),
            'managers'    => $this->users->where('status', 'active')->orderBy('first_name', 'ASC')->findAll(),
        ]));
    }

    public function store()
    {
        if (! $this->validate(['name' => 'required|min_length[2]|max_length[150]'])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/departments')->with('success', 'Department created.');
    }

    public function editForm(int $id)
    {
        $dept = $this->departments->find($id);
        if (! $dept) {
            return redirect()->to('/departments')->with('error', 'Department not found.');
        }

        return view('Modules\Departments\Views\edit', array_merge($this->baseViewData(), [
            'title'       => 'Edit Department',
            'department'  => $dept,
            'branches'    => $this->branches->orderBy('name', 'ASC')->findAll(),
            'managers'    => $this->users->where('status', 'active')->orderBy('first_name', 'ASC')->findAll(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate(['name' => 'required|min_length[2]|max_length[150]'])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->update($id, $this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/departments')->with('success', 'Department updated.');
    }

    public function activate(int $id)
    {
        $this->service->activate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Department activated.');
    }

    public function deactivate(int $id)
    {
        $this->service->deactivate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Department deactivated.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/departments')->with('error', $result['error']);
        }

        return redirect()->to('/departments')->with('success', 'Department deleted.');
    }
}
