<?php

require_once BASE_PATH
    . '/app/controllers/owner/OwnerBaseController.php';

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


class OwnerOrderController
    extends OwnerBaseController
{
    private Order $orderModel;


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

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


    // ========================================================
    // LIST
    // ========================================================

    public function index(): void
    {
        $search =
            trim(
                $_GET['search']
                ?? ''
            );


        $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 = 15;


        $totalOrders =
            $this->orderModel
                ->countForOwner(
                    $search,
                    $status
                );


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


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


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


        require BASE_PATH
            . '/app/views/owner/orders/index.php';
    }


    // ========================================================
    // DETAIL
    // ========================================================

    public function detail(): void
    {
        $orderId =
            (int)
            ($_GET['id'] ?? 0);


        $order =
            $this->orderModel
                ->findForOwner(
                    $orderId
                );


        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/owner/orders/detail.php';
    }


    // ========================================================
    // STATUS
    // ========================================================

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

        $this->validateCsrf();


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


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


        $newStatus =
            trim(
                $_POST['status']
                ?? ''
            );


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


        $allowed = [

            'confirmed',
            'packing',
            'shipping',
            'completed',
            'cancelled'
        ];


        if (
            !in_array(
                $newStatus,
                $allowed,
                true
            )
        ) {

            $this->flashError(
                'Trạng thái không hợp lệ.'
            );

            $this->backToOrder(
                $orderId
            );
        }


        try {

            $this->orderModel
                ->updateStatusByOwner(
                    $orderId,
                    $ownerId,
                    $newStatus,
                    $note !== ''
                        ? $note
                        : null
                );


            $this->flashSuccess(
                'Đã cập nhật trạng thái đơn hàng.'
            );


        } catch (RuntimeException $e) {

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


        $this->backToOrder(
            $orderId
        );
    }


    // ========================================================
    // MARK PAID
    // ========================================================

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

        $this->validateCsrf();


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


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


        try {

            $this->orderModel
                ->markPaidByOwner(
                    $orderId,
                    $ownerId
                );


            $this->flashSuccess(
                'Đã xác nhận thanh toán.'
            );


        } catch (RuntimeException $e) {

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


        $this->backToOrder(
            $orderId
        );
    }


    private function backToOrder(
        int $orderId
    ): never {

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

        exit;
    }
}