<?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;

class SessionController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('treasury.view_sessions');
        $employee = App::getInstance()->currentEmployee();

        $sessions = SessionService::getAllSessionHistory((int) $employee->id);

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

    public function current(Request $request): Response
    {
        $this->authorize('treasury.open_session');
        $employee = App::getInstance()->currentEmployee();

        $session = SessionService::getAnyCurrentSession((int) $employee->id);

        if (!$session) {
            return $this->redirect('/treasury')->withWarning('لا توجد وردية مفتوحة حالياً');
        }

        $treasury = TreasuryService::find((int) $session['treasury_id']);

        $db = App::getInstance()->db();
        $payments = $db->select(
            "SELECT p.*, m.full_name_ar as member_name, r.receipt_number
             FROM payments p
             LEFT JOIN members m ON m.id = p.member_id
             LEFT JOIN receipts r ON r.payment_id = p.id
             WHERE p.session_id = ? AND p.is_voided = 0
             ORDER BY p.id DESC",
            [(int) $session['id']]
        );

        return $this->view('Treasury.Views.sessions.current', [
            'session'  => $session,
            'payments' => $payments,
            'treasury' => $treasury,
        ]);
    }

    public function open(Request $request): Response
    {
        $this->authorize('treasury.open_session');
        $employee = App::getInstance()->currentEmployee();
        $treasury = TreasuryService::getSubTreasury();

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

        $result = SessionService::openSession((int) $treasury['id'], (int) $employee->id);

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

        return $this->redirect('/treasury')->withSuccess('تم فتح الوردية — رقم: ' . $result['session_number']);
    }

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

        $result = SessionService::closeSession((int) $id);

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

        return $this->redirect('/treasury')->withSuccess(
            'تم إغلاق الوردية — الإجمالي: ' . money($result['closing_balance']) . ' (' . $result['total_receipts'] . ' إيصال)'
        );
    }
}
