<?php

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

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


class CustomerOrderController
    extends CustomerBaseController
{
    private Order $orderModel;


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

        $this->orderModel =
            new Order();
    }


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


        $status =
            trim(
                $_GET['status']
                ?? ''
            );


        $allowedStatuses = [
            '',
            'pending',
            'confirmed',
            'packing',
            'shipping',
            'completed',
            'cancelled'
        ];


        if (
            !in_array(
                $status,
                $allowedStatuses,
                true
            )
        ) {

            $status = '';
        }


        $page =
            max(
                1,
                (int)
                ($_GET['page'] ?? 1)
            );


        $perPage = 10;


        $totalOrders =
            $this->orderModel
                ->countForCustomer(
                    $customerId,
                    $status
                );


        $totalPages =
            max(
                1,
                (int)
                ceil(
                    $totalOrders
                    / $perPage
                )
            );


        $page =
            min(
                $page,
                $totalPages
            );


        $orders =
            $this->orderModel
                ->getForCustomer(
                    $customerId,
                    $status,
                    $perPage,
                    ($page - 1)
                    * $perPage
                );


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


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


        $orderId =
            (int)
            ($_GET['id'] ?? 0);


        $order =
            $this->orderModel
                ->findByIdForCustomer(
                    $orderId,
                    $customerId
                );


        if (!$order) {

            http_response_code(404);

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

            return;
        }


        $orderItems =
            $this->orderModel
                ->getItems(
                    $orderId
                );


        $statusLogs =
            $this->orderModel
                ->getStatusLogs(
                    $orderId
                );


        require BASE_PATH
            . '/app/views/customer/order-detail.php';
    }


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

        $this->validateCsrf();


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


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


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


        if ($reason === '') {

            $this->flashError(
                'Vui lòng nhập lý do hủy đơn.'
            );

            header(
                'Location: '
                . BASE_URL
                . '/?url=customer/order&id='
                . $orderId
            );

            exit;
        }


        try {

            $this->orderModel
                ->cancelByCustomer(
                    $orderId,
                    $customerId,
                    $reason
                );


            $this->flashSuccess(
                'Đơn hàng đã được hủy.'
            );

        } catch (RuntimeException $e) {

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


        header(
            'Location: '
            . BASE_URL
            . '/?url=customer/order&id='
            . $orderId
        );

        exit;
    }
}