<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Services\CourseService;
use App\Services\PromotionService;

class PromotionController extends Controller
{
    private PromotionService $promotions;
    private CourseService $courses;

    public function __construct()
    {
        $this->promotions = new PromotionService();
        $this->courses = new CourseService();
    }

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

        return $this->view('admin/promotions/index', [
            'title' => 'Promocoes e vendas',
            'coupons' => $this->promotions->coupons(),
            'campaigns' => $this->promotions->campaigns(),
            'affiliates' => $this->promotions->affiliates(),
            'affiliateCommissions' => $this->promotions->affiliateCommissions(),
            'courses' => $this->courses->adminCourses(['status' => 'published']),
        ]);
    }

    public function storeCoupon(Request $request): void
    {
        require_role('admin');
        $this->guardCsrf($request);

        $result = $this->promotions->createCoupon($request->all(), (int) current_user()['id']);
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Cupao criado.' : $result['error']);
        app()->response()->back();
    }

    public function storeCampaign(Request $request): void
    {
        require_role('admin');
        $this->guardCsrf($request);

        $result = $this->promotions->createCampaign($request->all(), (int) current_user()['id']);
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Promocao criada.' : $result['error']);
        app()->response()->back();
    }

    public function storeAffiliate(Request $request): void
    {
        require_role('admin');
        $this->guardCsrf($request);

        $result = $this->promotions->createAffiliate($request->all(), (int) current_user()['id']);
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Afiliado criado.' : $result['error']);
        app()->response()->back();
    }

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