<?php

abstract class CustomerBaseController
{
    protected function requireCustomer(): void
    {
        if (!isset($_SESSION['user'])) {

            $_SESSION['redirect_after_login'] =
                $_SERVER['REQUEST_URI']
                ?? BASE_URL . '/?url=customer';

            header(
                'Location: '
                . BASE_URL
                . '/?url=login'
            );

            exit;
        }

        if (
            (
                $_SESSION['user']['role']
                ?? null
            ) !== 'customer'
        ) {

            http_response_code(403);

            require BASE_PATH
                . '/app/views/errors/403.php';

            exit;
        }
    }


    protected function requirePost(): void
    {
        if (
            $_SERVER['REQUEST_METHOD']
            !== 'POST'
        ) {

            http_response_code(405);

            exit('Method Not Allowed');
        }
    }


    protected function validateCsrf(): void
    {
        $token =
            $_POST['_token']
            ?? '';

        $sessionToken =
            $_SESSION['csrf_token']
            ?? '';

        if (
            $token === ''
            || $sessionToken === ''
            || !hash_equals(
                $sessionToken,
                $token
            )
        ) {

            http_response_code(403);

            exit('Yêu cầu không hợp lệ.');
        }
    }


    protected function flashSuccess(
        string $message
    ): void {

        $_SESSION['flash_success'] =
            $message;
    }


    protected function flashError(
        string $message
    ): void {

        $_SESSION['flash_error'] =
            $message;
    }


    protected function redirect(
        string $route
    ): never {

        header(
            'Location: '
            . BASE_URL
            . '/?url='
            . urlencode($route)
        );

        exit;
    }
}