<?php
declare(strict_types=1);

namespace App\Modules\Treasury\Controllers;

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

class SettlementController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('treasury.view_settlements');
        $treasury = TreasuryService::getSubTreasury();

        if (!$treasury) {
            return $this->redirect('/treasury')->withError('لم يتم تعريف الخزنة الفرعية');
        }

        $settlements = SettlementService::getSettlementHistory((int) $treasury['id']);

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

    public function create(Request $request): Response
    {
        $this->authorize('treasury.initiate_settlement');
        $treasury = TreasuryService::getSubTreasury();

        if (!$treasury) {
            return $this->redirect('/treasury')->withError('لم يتم تعريف الخزنة الفرعية');
        }

        $db = App::getInstance()->db();
        $closedSessions = $db->select(
            "SELECT ts.*, e.full_name_ar as cashier_name
             FROM treasury_sessions ts
             LEFT JOIN employees e ON e.id = ts.cashier_id
             WHERE ts.treasury_id = ? AND ts.status = 'closed'
             ORDER BY ts.closed_at DESC
             LIMIT 20",
            [(int) $treasury['id']]
        );

        return $this->view('Treasury.Views.settlements.create', [
            'sessions' => $closedSessions,
            'treasury' => $treasury,
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('treasury.initiate_settlement');

        $sessionId = (int) $request->post('session_id', 0);
        if ($sessionId <= 0) {
            return $this->redirect('/treasury/settlements/create')->withError('يجب اختيار وردية');
        }

        $result = SettlementService::initiateSettlement($sessionId);

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

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

    public function show(Request $request, string $id): Response
    {
        $this->authorize('treasury.view_settlements');

        $settlement = SettlementService::find((int) $id);
        if (!$settlement) {
            return $this->redirect('/treasury/settlements')->withError('التسوية غير موجودة');
        }

        return $this->view('Treasury.Views.settlements.show', [
            'settlement' => $settlement,
        ]);
    }
}
