<?php

namespace Modules\Operations\Controllers;

use App\Controllers\BaseController;
use Modules\Operations\Services\OperationsApprovalService;

class OperationsApprovalController extends BaseController
{
    protected OperationsApprovalService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->service = new OperationsApprovalService();
    }

    public function expenses()
    {
        $search = trim((string) $this->request->getGet('q'));

        return view('Modules\Operations\Views\approvals\queue', array_merge($this->baseViewData(), [
            'title'         => 'Expense Approval',
            'heroTitle'     => 'Expense Approval',
            'heroDesc'      => 'Review draft expenses waiting for approval.',
            'crumb'         => 'Expense Approval',
            'filterAction'  => 'operations/approvals/expenses',
            'items'         => $this->service->listExpenses($search ?: null),
            'filters'       => ['search' => $search],
            'emptyMessage'  => 'No draft expenses pending approval.',
            'amountLabel'   => 'Amount',
            'showAmount'    => true,
        ]));
    }

    public function approveExpense()
    {
        $id = (int) $this->request->getPost('id');
        $result = $this->service->approveExpense($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/operations/approvals/expenses')->with('error', $result['error']);
        }

        return redirect()->to('/operations/approvals/expenses')->with('success', 'Expense approved.');
    }

    public function workOrders()
    {
        $search = trim((string) $this->request->getGet('q'));

        return view('Modules\Operations\Views\approvals\queue', array_merge($this->baseViewData(), [
            'title'         => 'Work Approval',
            'heroTitle'     => 'Work Approval',
            'heroDesc'      => 'Approve or reject work orders submitted for review.',
            'crumb'         => 'Work Approval',
            'filterAction'  => 'operations/approvals/work-orders',
            'items'         => $this->service->listWorkOrders($search ?: null),
            'filters'       => ['search' => $search],
            'emptyMessage'  => 'No work orders pending approval.',
            'amountLabel'   => null,
            'showAmount'    => false,
        ]));
    }

    public function approveWorkOrder()
    {
        $id = (int) $this->request->getPost('id');
        $result = $this->service->approveWorkOrder($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/operations/approvals/work-orders')->with('error', $result['error']);
        }

        return redirect()->to('/operations/approvals/work-orders')->with('success', 'Work order approved.');
    }

    public function rejectWorkOrder()
    {
        $id = (int) $this->request->getPost('id');
        $reason = (string) $this->request->getPost('rejection_reason');
        $result = $this->service->rejectWorkOrder($id, $reason, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/operations/approvals/work-orders')->with('error', $result['error']);
        }

        return redirect()->to('/operations/approvals/work-orders')->with('success', 'Work order rejected.');
    }

    public function purchases()
    {
        $search = trim((string) $this->request->getGet('q'));

        return view('Modules\Operations\Views\approvals\queue', array_merge($this->baseViewData(), [
            'title'         => 'Purchase Approval',
            'heroTitle'     => 'Purchase Approval',
            'heroDesc'      => 'Review purchase requests, RFQs, quotations, and purchase orders.',
            'crumb'         => 'Purchase Approval',
            'filterAction'  => 'operations/approvals/purchases',
            'items'         => $this->service->listPurchases($search ?: null),
            'filters'       => ['search' => $search],
            'emptyMessage'  => 'No purchase documents pending approval.',
            'amountLabel'   => 'Total',
            'showAmount'    => true,
        ]));
    }

    public function approvePurchase()
    {
        $type = (string) $this->request->getPost('type');
        $id   = (int) $this->request->getPost('id');
        $result = $this->service->approvePurchase($type, $id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/operations/approvals/purchases')->with('error', $result['error'] ?? 'Approve failed.');
        }

        return redirect()->to('/operations/approvals/purchases')->with('success', 'Document approved.');
    }

    public function rejectPurchase()
    {
        $type   = (string) $this->request->getPost('type');
        $id     = (int) $this->request->getPost('id');
        $reason = (string) $this->request->getPost('rejection_reason');
        $result = $this->service->rejectPurchase($type, $id, $reason, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/operations/approvals/purchases')->with('error', $result['error'] ?? 'Reject failed.');
        }

        return redirect()->to('/operations/approvals/purchases')->with('success', 'Document rejected.');
    }

    public function leave()
    {
        $search = trim((string) $this->request->getGet('q'));

        return view('Modules\Operations\Views\approvals\queue', array_merge($this->baseViewData(), [
            'title'         => 'Leave Approval',
            'heroTitle'     => 'Leave Approval',
            'heroDesc'      => 'Approve or reject pending leave requests.',
            'crumb'         => 'Leave Approval',
            'filterAction'  => 'operations/approvals/leave',
            'items'         => $this->service->listLeave($search ?: null),
            'filters'       => ['search' => $search],
            'emptyMessage'  => 'No leave requests pending approval.',
            'amountLabel'   => 'Days',
            'showAmount'    => true,
        ]));
    }

    public function approveLeave()
    {
        $id = (int) $this->request->getPost('id');
        $result = $this->service->approveLeave($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/operations/approvals/leave')->with('error', $result['error']);
        }

        return redirect()->to('/operations/approvals/leave')->with('success', 'Leave request approved.');
    }

    public function rejectLeave()
    {
        $id = (int) $this->request->getPost('id');
        $reason = (string) $this->request->getPost('rejection_reason');
        $result = $this->service->rejectLeave($id, $reason, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/operations/approvals/leave')->with('error', $result['error']);
        }

        return redirect()->to('/operations/approvals/leave')->with('success', 'Leave request rejected.');
    }
}
