<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Services\PaymentService;
use App\Services\SettingsService;

class PaymentController extends Controller
{
    private PaymentService $payments;
    private SettingsService $settings;

    public function __construct()
    {
        $this->payments = new PaymentService();
        $this->settings = new SettingsService();
    }

    public function checkout(Request $request): void
    {
        require_role('student');

        if (!verify_csrf((string) $request->post('_csrf_token', ''))) {
            flash('error', 'Sessao expirada. Tente novamente.');
            app()->response()->back();
        }

        $result = $this->payments->startCheckout(
            (int) $request->post('course_id'),
            current_user(),
            (string) $request->post('coupon_code', ''),
            (string) $request->post('affiliate_code', '')
        );

        if (!$result['ok']) {
            flash('error', $result['error']);
            app()->response()->back();
        }

        app()->response()->redirect('/payments/show?id=' . $result['payment']['id']);
    }

    public function show(Request $request): string
    {
        require_role('student');
        $payment = $this->payments->payment((int) $request->input('id'));

        if (!$payment || (int) $payment['student_id'] !== (int) current_user()['id']) {
            flash('error', 'Pagamento nao encontrado.');
            app()->response()->redirect('/payments');
        }

        return $this->view('payments/show', [
            'title' => 'Pagamento manual',
            'payment' => $payment,
            'paymentMethods' => array_values(array_filter($this->settings->paymentMethods(), fn (array $method): bool => $method['enabled'])),
            'paymentInstructions' => $this->settings->get('payment_manual_instructions', 'Depois de pagar, envie o comprovativo nesta pagina usando a referencia do pedido.'),
        ]);
    }

    public function uploadProof(Request $request): void
    {
        require_role('student');

        if (!verify_csrf((string) $request->post('_csrf_token', ''))) {
            flash('error', 'Sessao expirada. Tente novamente.');
            app()->response()->back();
        }

        $result = $this->payments->submitProof(
            (int) $request->post('payment_id'),
            $_FILES['proof'] ?? [],
            (string) $request->post('student_note', ''),
            current_user()
        );

        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Comprovativo enviado. Aguarde aprovacao.' : $result['error']);
        app()->response()->back();
    }

    public function history(): string
    {
        require_role('student');

        return $this->view('payments/history', [
            'title' => 'Meus pagamentos',
            'payments' => $this->payments->studentPayments((int) current_user()['id']),
        ]);
    }
}
