<?php

declare(strict_types=1);

namespace App\Controllers;

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

class AdminPaymentController extends Controller
{
    private PaymentService $payments;

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

    public function index(Request $request): string
    {
        require_role('admin');

        $filters = [
            'status' => (string) $request->input('status', ''),
            'search' => (string) $request->input('search', ''),
        ];

        return $this->view('admin/payments/index', [
            'title' => 'Pagamentos',
            'payments' => $this->payments->adminPayments($filters),
            'filters' => $filters,
        ]);
    }

    public function approve(Request $request): void
    {
        $this->guard($request);
        $result = $this->payments->approve((int) $request->post('payment_id'), (int) current_user()['id'], (string) $request->post('admin_note', ''));
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Pagamento aprovado e acesso liberado.' : $result['error']);
        app()->response()->back();
    }

    public function reject(Request $request): void
    {
        $this->guard($request);
        $result = $this->payments->reject((int) $request->post('payment_id'), (int) current_user()['id'], (string) $request->post('admin_note', ''));
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Pagamento rejeitado.' : $result['error']);
        app()->response()->back();
    }

    public function proof(Request $request): void
    {
        require_role('admin');
        $proof = $this->payments->proof((int) $request->input('id'));

        if (!$proof) {
            http_response_code(404);
            exit('Comprovativo nao encontrado.');
        }

        $path = $this->payments->proofPath($proof);

        if (!is_file($path)) {
            http_response_code(404);
            exit('Ficheiro nao encontrado.');
        }

        header('Content-Type: ' . $proof['file_type']);
        header('Content-Disposition: inline; filename="comprovativo"');
        header('Content-Length: ' . filesize($path));
        readfile($path);
        exit;
    }

    private function guard(Request $request): void
    {
        require_role('admin');

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