<?php
declare(strict_types=1);

namespace App\Modules\Cashier\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Treasury\Services\SettlementService;

class SettlementReceiveController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('cashier.receive_settlement');

        $settlements = SettlementService::getPendingSettlements();

        return $this->view('Cashier.Views.settlements.index', [
            'settlements' => $settlements,
        ]);
    }

    public function receive(Request $request, string $id): Response
    {
        $this->authorize('cashier.receive_settlement');
        $employee = App::getInstance()->currentEmployee();

        $result = SettlementService::receiveSettlement((int) $id, (int) $employee->id);

        if (!$result['success']) {
            return $this->redirect('/cashier/settlements')->withError($result['error']);
        }

        return $this->redirect('/cashier/settlements')->withSuccess(
            'تم استلام التسوية — المبلغ: ' . money($result['amount'])
        );
    }

    public function reject(Request $request, string $id): Response
    {
        $this->authorize('cashier.receive_settlement');
        $employee = App::getInstance()->currentEmployee();

        $reason = trim((string) $request->post('reason', ''));
        if ($reason === '') {
            return $this->redirect('/cashier/settlements')->withError('يجب إدخال سبب الرفض');
        }

        $result = SettlementService::rejectSettlement((int) $id, (int) $employee->id, $reason);

        if (!$result['success']) {
            return $this->redirect('/cashier/settlements')->withError($result['error']);
        }

        return $this->redirect('/cashier/settlements')->withSuccess('تم رفض التسوية');
    }
}
