<?php

namespace Modules\Assets\Controllers;

use App\Controllers\BaseController;
use App\Models\AssetTypeModel;
use App\Models\EmployeeAssetAssignmentModel;
use App\Models\EmployeeModel;
use Modules\Assets\Services\EmployeeAssetService;

class EmployeeAssetController extends BaseController
{
    protected EmployeeAssetAssignmentModel $assignments;
    protected EmployeeAssetService $service;
    protected EmployeeModel $employees;
    protected AssetTypeModel $types;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->assignments = new EmployeeAssetAssignmentModel();
        $this->service     = new EmployeeAssetService();
        $this->employees   = new EmployeeModel();
        $this->types       = new AssetTypeModel();
    }

    public function index()
    {
        $employeeId  = $this->request->getGet('employee_id') ? (int) $this->request->getGet('employee_id') : null;
        $assetTypeId = $this->request->getGet('asset_type_id') ? (int) $this->request->getGet('asset_type_id') : null;
        $status      = $this->request->getGet('status') ?: null;
        $search      = trim((string) $this->request->getGet('q'));

        $builder = $this->assignments
            ->select('employee_asset_assignments.*, e.full_name, e.employee_number, t.name as type_name, t.code as type_code, t.category')
            ->join('employees e', 'e.id = employee_asset_assignments.employee_id')
            ->join('asset_types t', 't.id = employee_asset_assignments.asset_type_id')
            ->where('e.deleted_at', null)
            ->scopeForList($employeeId, $assetTypeId, $status, $search ?: null);

        $assignments = $builder->orderBy('employee_asset_assignments.assigned_date', 'DESC')->findAll();

        return view('Modules\Assets\Views\assignments\index', array_merge($this->baseViewData(), [
            'title'       => 'Asset Assignments',
            'assignments' => $assignments,
            'employees'   => $this->employees->scopeForList(null, 'active')->orderBy('full_name', 'ASC')->findAll(),
            'types'       => $this->types->getActive(),
            'employeeId'  => $employeeId,
            'assetTypeId' => $assetTypeId,
            'filters'     => compact('search', 'status'),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'employee_id'    => 'required|integer',
            'asset_type_id'  => 'required|integer',
            'asset_name'     => 'required|min_length[1]|max_length[200]',
            'assigned_date'  => 'required|valid_date[Y-m-d]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        $redirect = $this->request->getPost('redirect_to') ?: '/assets/assignments';

        return redirect()->to($redirect)->with('success', 'Asset assigned to employee.');
    }

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

        return view('Modules\Assets\Views\assignments\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Asset Assignment',
            'assignment' => $assignment,
            'types'      => $this->types->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'asset_type_id' => 'required|integer',
            'asset_name'    => 'required|min_length[1]|max_length[200]',
            'assigned_date' => 'required|valid_date[Y-m-d]',
        ])) {
            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('/assets/assignments')->with('success', 'Asset assignment updated.');
    }

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

        return redirect()->back()->with('success', 'Asset marked as returned.');
    }

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

        return redirect()->to('/assets/assignments')->with('success', 'Asset assignment deleted.');
    }
}
