<?php

namespace Hura8\Components\Order\AdminController;


use Hura8\Components\Order\Controller\OrderStatus;
use Hura8\Components\Order\Model\OrderModel;
use Hura8\Events\EventName;
use Hura8\Events\RealEvents\OrderEvent;
use Hura8\System\Controller\aAdminEntityBaseController;

class AOrderController extends aAdminEntityBaseController
{

    /* @var  OrderModel $objOrderModel */
    protected $objOrderModel;

    /* @var  AOrderStatusController $objAOrderStatusController */
    protected $objAOrderStatusController;

    public function __construct()
    {
        $this->objAOrderStatusController = new AOrderStatusController();
        $this->objOrderModel = new OrderModel();
        parent::__construct($this->objOrderModel);
    }

    public function updateOrderFulfillmentStatus($order_id, $new_status, $comment, $payment_data = []) {

        if(!array_key_exists($new_status, OrderStatus::FULFILLMENT_STATUS)) {
            return [
                "status" => 'error',
                'message' => '',
            ];
        }

        $this->objAOrderStatusController->createHistory($order_id, 'fulfillment', $new_status, $comment, $payment_data );

        //cap nhat don hang
        $this->objOrderModel->update( $order_id, [
            'fulfillment_status' => $new_status
        ]);

        $this->updateDerivedOrderStatus($order_id);

        return [
            "status" => 'success',
            'message' => 'Cập nhật thành công',
        ];
    }

    public function updateOrderPaymentStatus($order_id, $new_status, $comment, $payment_data = []) {

        if(!array_key_exists($new_status, OrderStatus::PAYMENT_STATUS)) {
            return [
                "status" => 'error',
                'message' => '',
            ];
        }

        $this->objAOrderStatusController->createHistory($order_id, 'payment', $new_status, $comment, $payment_data );

        //cap nhat don hang
        $this->objOrderModel->update( $order_id, [
            'payment_status' => $new_status
        ]);

        $this->updateDerivedOrderStatus($order_id);

        return [
            "status" => 'success',
            'message' => 'Cập nhật thành công',
        ];
    }

    protected function updateDerivedOrderStatus($order_id) {

        $current_info = $this->getInfo($order_id);

        // order must be success
        if(
            $current_info['payment_status'] == OrderStatus::PAYMENT_STATUS['paid']['id'] &&
            $current_info['fulfillment_status'] == OrderStatus::FULFILLMENT_STATUS['fulfilled']['id']
        ) {

            return $this->objOrderModel->update($order_id, [
                'order_status' => OrderStatus::ORDER_STATUS['success']['id']
            ]);

        }


        // update processing
        return $this->objOrderModel->update($order_id, [
            'order_status' => OrderStatus::ORDER_STATUS['processing']['id']
        ]);

    }

    public function updateOrderStatus($order_id, $status, $comment) {

        $current_info = $this->getInfo($order_id);

        // cannot update if order has: success or cancel
        if(in_array($current_info['order_status'], [
            OrderStatus::ORDER_STATUS['success']['id'],
            OrderStatus::ORDER_STATUS['canceled']['id'],
        ])) {
            return [
                "status" => 'error',
                'message' => '',
            ];
        }

        if(!array_key_exists($status, OrderStatus::ORDER_STATUS)) {
            return [
                "status" => 'error',
                'message' => '',
            ];
        }

        $this->objAOrderStatusController->createHistory($order_id, 'order', $status, $comment );

        $this->objOrderModel->update($order_id, [
            'order_status' => $status
        ]);

        // dispatch
        $objOrderEvent = new OrderEvent();
        $objOrderEvent->setUpdateOrderInfo([
            'orderId'       => $order_id,
            'order_status'  => $status,
            'old_status'    => $current_info['order_status']
        ]);
        get_dispatcher()->dispatch(EventName::ORDER['updated_status'], $objOrderEvent);

        return [
            "status" => 'success',
            'message' => 'Cập nhật thành công',
        ];
    }


    protected function formatItemInList(array $order_info ) {

        $rs = $order_info;

        $rs["order_date"] = date("d-m-Y", $rs['order_time']);
        $rs["order_hour"] = date("h:i a", $rs['order_time']);

        if($rs['order_discount']) $rs['order_discount'] = \json_decode($rs['order_discount'], true);

        $rs["payment_status_name"]      = (array_key_exists($rs["payment_status"], OrderStatus::PAYMENT_STATUS)) ? OrderStatus::PAYMENT_STATUS[$rs["payment_status"]]['title'] : '';

        $rs["fulfillment_status_name"]  = (array_key_exists($rs["fulfillment_status"], OrderStatus::FULFILLMENT_STATUS)) ?  OrderStatus::FULFILLMENT_STATUS[$rs["fulfillment_status"]]['title'] : '';

        $rs["order_status_name"]        = (array_key_exists($rs["order_status"], OrderStatus::ORDER_STATUS)) ?  OrderStatus::ORDER_STATUS[$rs["order_status"]]['title'] : '';

        return $rs;
    }

    protected function getListFilterCondition($list_id) {

        if($list_id == 'mine') {
            return [
                'assign_to' => ADMIN_ID,
            ];
        }

        if($list_id == 'new') {
            return [
                'status' => 'new',
            ];
        }

        if($list_id == 'unpaid') {
            return [
                'payment' => 'unpaid',
            ];
        }

        if($list_id == 'partially-paid') {
            return [
                'payment' => 'partially-paid',
            ];
        }

        if($list_id == 'unfulfilled') {
            return [
                'fullfillment' => 'unfulfilled',
            ];
        }

        if($list_id == 'partially-fulfilled') {
            return [
                'fullfillment' => 'partially-fulfilled',
            ];
        }

        return null;
    }

    public function getStatusHistory($orderId){

        return $this->objAOrderStatusController->getStatusHistory($orderId);

    }

    public function getItemsForOrderList(array $list_ids, $fields = "*") {

        return $this->objOrderModel->getItemsForOrderList($list_ids, $fields);

    }

    public static function createId($order_id){
        $key_length = strlen($order_id);

        $order_keys = [];
        for($i=0; $i < 9 - $key_length; $i++){
            $order_keys[] = "0";
        }
        $order_keys[] = $order_id;

        $order_eles = str_split(join("", $order_keys), 3);

        return join("-", $order_eles);
    }


    protected function deleteFileBeforeDeleteItem($item_id): bool
    {
        return true;
    }

}
