<?php

require_once BASE_PATH
    . '/app/controllers/customer/CustomerBaseController.php';

require_once BASE_PATH
    . '/app/models/ProductReview.php';


class CustomerReviewController
    extends CustomerBaseController
{
    private ProductReview $reviewModel;


    public function __construct()
    {
        $this->requireCustomer();

        $this->reviewModel =
            new ProductReview();
    }


    public function index(): void
    {
        $customerId =
            (int)
            $_SESSION['user']['id'];


        $reviewableItems =
            $this->reviewModel
                ->getReviewableItems(
                    $customerId
                );


        $reviews =
            $this->reviewModel
                ->getForCustomer(
                    $customerId
                );


        require BASE_PATH
            . '/app/views/customer/reviews.php';
    }


    public function store(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $customerId =
            (int)
            $_SESSION['user']['id'];


        $orderItemId =
            (int)
            ($_POST['order_item_id']
                ?? 0);


        $rating =
            (int)
            ($_POST['rating']
                ?? 0);


        $comment =
            trim(
                $_POST['comment']
                ?? ''
            );


        try {

            $this->reviewModel
                ->createForCustomer(
                    $customerId,
                    $orderItemId,
                    $rating,
                    $comment !== ''
                        ? $comment
                        : null
                );


            $this->flashSuccess(
                'Cảm ơn bạn đã đánh giá sản phẩm.'
            );


        } catch (RuntimeException $e) {

            $this->flashError(
                $e->getMessage()
            );
        }


        $this->redirect(
            'customer/reviews'
        );
    }
}