<?php

namespace Modules\Operations\Controllers;

use App\Controllers\BaseController;
use App\Models\EmployeeModel;
use App\Models\InventoryAssetModel;
use App\Models\OpsEquipmentAllocationModel;
use App\Models\OpsMaterialUsageModel;
use App\Models\OpsStaffAllocationModel;
use App\Models\ProductModel;
use App\Models\WorkOrderModel;
use Modules\Operations\Services\OperationsResourcesService;

class OperationsResourcesController extends BaseController
{
    protected OpsStaffAllocationModel $staff;
    protected OpsEquipmentAllocationModel $equipment;
    protected OpsMaterialUsageModel $materials;
    protected OperationsResourcesService $service;
    protected EmployeeModel $employees;
    protected InventoryAssetModel $assets;
    protected ProductModel $products;
    protected WorkOrderModel $workOrders;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->staff      = new OpsStaffAllocationModel();
        $this->equipment  = new OpsEquipmentAllocationModel();
        $this->materials  = new OpsMaterialUsageModel();
        $this->service    = new OperationsResourcesService();
        $this->employees  = new EmployeeModel();
        $this->assets     = new InventoryAssetModel();
        $this->products   = new ProductModel();
        $this->workOrders = new WorkOrderModel();
    }

    // -------------------------------------------------------------------------
    // Staff allocation
    // -------------------------------------------------------------------------

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

        $entries = $this->staff
            ->scopeForList($search ?: null, $status)
            ->orderBy('ops_staff_allocations.id', 'DESC')
            ->paginate(25);

        return view('Modules\Operations\Views\resources\staff_allocation\index', array_merge($this->baseViewData(), [
            'title'   => 'Staff Allocation',
            'entries' => $entries,
            'pager'   => $this->staff->pager,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createStaffForm()
    {
        return view('Modules\Operations\Views\resources\staff_allocation\create', array_merge($this->baseViewData(), [
            'title'  => 'Allocate Staff',
            'row'    => [],
            'lookups'=> $this->resourceLookups(),
        ]));
    }

    public function storeStaff()
    {
        if (! $this->validate([
            'employee_id'      => 'required|is_natural_no_zero',
            'work_order_id'    => 'permit_empty|is_natural_no_zero',
            'service_visit_id' => 'permit_empty|is_natural_no_zero',
            'role'             => 'permit_empty|max_length[100]',
            'status'           => 'permit_empty|in_list[planned,active]',
            'from_date'        => 'permit_empty|valid_date',
            'to_date'          => 'permit_empty|valid_date',
            'notes'            => 'permit_empty|max_length[500]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/operations/resources/staff-allocation/' . $result['id'])
            ->with('success', 'Staff allocation created.');
    }

    public function showStaff(int $id)
    {
        $row = $this->staff->scopeForList()->where('ops_staff_allocations.id', $id)->first();
        if (! $row) {
            return redirect()->to('/operations/resources/staff-allocation')->with('error', 'Staff allocation not found.');
        }

        return view('Modules\Operations\Views\resources\staff_allocation\show', array_merge($this->baseViewData(), [
            'title' => $row['number'],
            'row'   => $row,
        ]));
    }

    public function editStaffForm(int $id)
    {
        $row = $this->staff->find($id);
        if (! $row) {
            return redirect()->to('/operations/resources/staff-allocation')->with('error', 'Staff allocation not found.');
        }

        if (! in_array($row['status'], OpsStaffAllocationModel::EDITABLE_STATUSES, true)) {
            return redirect()->to('/operations/resources/staff-allocation/' . $id)
                ->with('error', 'Only planned allocations can be edited.');
        }

        return view('Modules\Operations\Views\resources\staff_allocation\edit', array_merge($this->baseViewData(), [
            'title'  => 'Edit Staff Allocation',
            'row'    => $row,
            'lookups'=> $this->resourceLookups(),
        ]));
    }

    public function updateStaff(int $id)
    {
        if (! $this->validate([
            'employee_id'      => 'required|is_natural_no_zero',
            'work_order_id'    => 'permit_empty|is_natural_no_zero',
            'service_visit_id' => 'permit_empty|is_natural_no_zero',
            'role'             => 'permit_empty|max_length[100]',
            'from_date'        => 'permit_empty|valid_date',
            'to_date'          => 'permit_empty|valid_date',
            'notes'            => 'permit_empty|max_length[500]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/operations/resources/staff-allocation/' . $id)->with('success', 'Staff allocation updated.');
    }

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

        return redirect()->to('/operations/resources/staff-allocation/' . $id)->with('success', 'Staff allocation activated.');
    }

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

        return redirect()->to('/operations/resources/staff-allocation/' . $id)->with('success', 'Staff allocation released.');
    }

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

        return redirect()->to('/operations/resources/staff-allocation')->with('success', 'Staff allocation deleted.');
    }

    // -------------------------------------------------------------------------
    // Equipment allocation
    // -------------------------------------------------------------------------

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

        $entries = $this->equipment
            ->scopeForList($search ?: null, $status)
            ->orderBy('ops_equipment_allocations.id', 'DESC')
            ->paginate(25);

        return view('Modules\Operations\Views\resources\equipment_allocation\index', array_merge($this->baseViewData(), [
            'title'   => 'Equipment Allocation',
            'entries' => $entries,
            'pager'   => $this->equipment->pager,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createEquipmentForm()
    {
        return view('Modules\Operations\Views\resources\equipment_allocation\create', array_merge($this->baseViewData(), [
            'title'  => 'Allocate Equipment',
            'row'    => [],
            'lookups'=> $this->resourceLookups(),
        ]));
    }

    public function storeEquipment()
    {
        if (! $this->validate([
            'inventory_asset_id' => 'required|is_natural_no_zero',
            'work_order_id'      => 'permit_empty|is_natural_no_zero',
            'service_visit_id'   => 'permit_empty|is_natural_no_zero',
            'notes'              => 'permit_empty|max_length[500]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/operations/resources/equipment-allocation/' . $result['id'])
            ->with('success', 'Equipment allocation created.');
    }

    public function showEquipment(int $id)
    {
        $row = $this->equipment->scopeForList()->where('ops_equipment_allocations.id', $id)->first();
        if (! $row) {
            return redirect()->to('/operations/resources/equipment-allocation')->with('error', 'Equipment allocation not found.');
        }

        return view('Modules\Operations\Views\resources\equipment_allocation\show', array_merge($this->baseViewData(), [
            'title' => $row['number'],
            'row'   => $row,
        ]));
    }

    public function editEquipmentForm(int $id)
    {
        $row = $this->equipment->find($id);
        if (! $row) {
            return redirect()->to('/operations/resources/equipment-allocation')->with('error', 'Equipment allocation not found.');
        }

        if (! in_array($row['status'], OpsEquipmentAllocationModel::EDITABLE_STATUSES, true)) {
            return redirect()->to('/operations/resources/equipment-allocation/' . $id)
                ->with('error', 'Only assigned allocations can be edited.');
        }

        return view('Modules\Operations\Views\resources\equipment_allocation\edit', array_merge($this->baseViewData(), [
            'title'  => 'Edit Equipment Allocation',
            'row'    => $row,
            'lookups'=> $this->resourceLookups(),
        ]));
    }

    public function updateEquipment(int $id)
    {
        if (! $this->validate([
            'inventory_asset_id' => 'required|is_natural_no_zero',
            'work_order_id'      => 'permit_empty|is_natural_no_zero',
            'service_visit_id'   => 'permit_empty|is_natural_no_zero',
            'notes'              => 'permit_empty|max_length[500]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/operations/resources/equipment-allocation/' . $id)->with('success', 'Equipment allocation updated.');
    }

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

        return redirect()->to('/operations/resources/equipment-allocation/' . $id)->with('success', 'Equipment returned.');
    }

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

        return redirect()->to('/operations/resources/equipment-allocation/' . $id)->with('success', 'Equipment marked as lost.');
    }

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

        return redirect()->to('/operations/resources/equipment-allocation')->with('success', 'Equipment allocation deleted.');
    }

    // -------------------------------------------------------------------------
    // Material usage
    // -------------------------------------------------------------------------

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

        $entries = $this->materials
            ->scopeForList($search ?: null, $status)
            ->orderBy('ops_material_usage.id', 'DESC')
            ->paginate(25);

        return view('Modules\Operations\Views\resources\material_usage\index', array_merge($this->baseViewData(), [
            'title'   => 'Material Usage',
            'entries' => $entries,
            'pager'   => $this->materials->pager,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createMaterialForm()
    {
        return view('Modules\Operations\Views\resources\material_usage\create', array_merge($this->baseViewData(), [
            'title'  => 'Record Material Usage',
            'row'    => [],
            'lookups'=> $this->resourceLookups(),
        ]));
    }

    public function storeMaterial()
    {
        if (! $this->validate([
            'product_id'           => 'required|is_natural_no_zero',
            'quantity'             => 'required|decimal',
            'unit_label'           => 'permit_empty|max_length[30]',
            'used_at'              => 'permit_empty|valid_date',
            'used_by_employee_id'  => 'permit_empty|is_natural_no_zero',
            'work_order_id'        => 'permit_empty|is_natural_no_zero',
            'service_visit_id'     => 'permit_empty|is_natural_no_zero',
            'notes'                => 'permit_empty|max_length[500]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/operations/resources/material-usage/' . $result['id'])
            ->with('success', 'Material usage recorded.');
    }

    public function showMaterial(int $id)
    {
        $row = $this->materials->scopeForList()->where('ops_material_usage.id', $id)->first();
        if (! $row) {
            return redirect()->to('/operations/resources/material-usage')->with('error', 'Material usage not found.');
        }

        return view('Modules\Operations\Views\resources\material_usage\show', array_merge($this->baseViewData(), [
            'title' => $row['number'],
            'row'   => $row,
        ]));
    }

    public function editMaterialForm(int $id)
    {
        $row = $this->materials->find($id);
        if (! $row) {
            return redirect()->to('/operations/resources/material-usage')->with('error', 'Material usage not found.');
        }

        if (! in_array($row['status'], OpsMaterialUsageModel::EDITABLE_STATUSES, true)) {
            return redirect()->to('/operations/resources/material-usage/' . $id)
                ->with('error', 'Only recorded usage can be edited.');
        }

        return view('Modules\Operations\Views\resources\material_usage\edit', array_merge($this->baseViewData(), [
            'title'  => 'Edit Material Usage',
            'row'    => $row,
            'lookups'=> $this->resourceLookups(),
        ]));
    }

    public function updateMaterial(int $id)
    {
        if (! $this->validate([
            'product_id'           => 'required|is_natural_no_zero',
            'quantity'             => 'required|decimal',
            'unit_label'           => 'permit_empty|max_length[30]',
            'used_at'              => 'permit_empty|valid_date',
            'used_by_employee_id'  => 'permit_empty|is_natural_no_zero',
            'work_order_id'        => 'permit_empty|is_natural_no_zero',
            'service_visit_id'     => 'permit_empty|is_natural_no_zero',
            'notes'                => 'permit_empty|max_length[500]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/operations/resources/material-usage/' . $id)->with('success', 'Material usage updated.');
    }

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

        return redirect()->to('/operations/resources/material-usage/' . $id)->with('success', 'Material usage voided.');
    }

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

        return redirect()->to('/operations/resources/material-usage')->with('success', 'Material usage deleted.');
    }

    /**
     * @return array{employees: list<array>, assets: list<array>, products: list<array>, workOrders: list<array>, serviceVisits: list<array>}
     */
    protected function resourceLookups(): array
    {
        $assets = [];
        try {
            $assets = $this->assets->scopeForList(null, 'active')->orderBy('name', 'ASC')->findAll();
        } catch (\Throwable $e) {
            $assets = [];
        }

        return [
            'employees'     => $this->employees->scopeForList(null, 'active')->orderBy('full_name', 'ASC')->findAll(),
            'assets'        => $assets,
            'products'      => $this->products->getActive(),
            'workOrders'    => $this->workOrders->getAssignable(),
            'serviceVisits' => $this->service->openServiceVisits(),
        ];
    }
}
