<?php

/**
 *
 * This Controller used to save, fetch or delete Shopify orders
 *
 * @category   Products
 * @package    WooCommerce API
 * @author     Original Author <debashrib@riaxe.com>
 * @copyright  2019-2020 Riaxe Systems
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    Release: @1.0
 */

namespace OrderStoreSpace\Controllers;

use ComponentStoreSpace\Controllers\StoreComponent;
use App\Modules\Products\Controllers\ProductsController;
use App\Modules\Orders\Models\Orders;

class StoreOrdersController extends StoreComponent {

    public function __construct() {
        parent::__construct();
    }

    /**
     * Get list of Order or a Single Order Details
     *
     * @author     sonali@imprintnext.com
     * @date       18 Feb 2022
     * @parameter  Slim default params
     * @response   Array of list/one order(s)
     */
    public function getOrders($request, $response, $args) {
        $storeResponse = [];
        $orders = [];
        // Get all requested Query params 
        $from = $request->getQueryParam('from') ? $request->getQueryParam('from') : date('Y-m-d', strtotime('2015-01-01'));
        $to = $request->getQueryParam('to') ? $request->getQueryParam('to') : date('Y-m-d');
        if($request->getQueryParam('action')){
        $from = date('Y-m-d', strtotime($request->getQueryParam('start_date')));
        $to = date('Y-m-d', strtotime($request->getQueryParam('end_date')));
        }
        $filters = [
            'is_customize' => $request->getQueryParam('is_customize'),
            'sku' => $request->getQueryParam('sku'),
            'search' => $request->getQueryParam('name'),
            'page' => $request->getQueryParam('page'),
            'order_id' => $request->getQueryParam('orderid'),
            'per_page' => $request->getQueryParam('per_page'),
            'fromDate' => $from,
            'customer_id' => $request->getQueryParam('customer_id'),
            'toDate' => $to,
            'order_status' => $request->getQueryParam('order_status'),
            'order' => (!empty($request->getQueryParam('order')) && $request->getQueryParam('order') != "") ? $request->getQueryParam('order') : 'desc',
            'orderby' => (!empty($request->getQueryParam('orderby')) && $request->getQueryParam('order_by') != "") ? $request->getQueryParam('orderby') : 'id',
        ];
        if (isset($args['id']) && $args['id'] != "" && $args['id'] > 0) {
            // fetching Single Order
            $orders = $this->orderDetails($args);
        } else {
            // fetching all Orders
            $orders = $this->allOrders($filters);
        }
        $totalRecord = $this->countOrders();
        if (isset($orders) && is_array($orders) && count($orders) > 0) {
            $storeResponse = [
                    'status' => 1,
                    'total_records' => $totalRecord,
                    'records' => (isset($args['id']) && $args['id'] != "" && $args['id'] > 0)?1:count($orders),
                    'order_details' => $orders
                ];
        } else {
           $storeResponse = [
                'status' => 0,
                'message' => 'No order available',
                'order_details' => []
            ];
        }
        return $storeResponse;
    }

    /**
     * Get list of Order Logs
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Responce object
     * @param $args     Slim's Argument parameters
     *
     * @author sonali@imprintnext.com
     * @date   17th Feb 2022
     * @return Order information in Json format
     */
    public function orderItemDetails($request, $response, $args)
    {
       //Get all order details by order id
        $orderDetailsObj = $this->orderInfo($args['id']);
        return json_clean_decode($orderDetailsObj, true);
    }

    /**
     * Get list of Order Logs
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Responce object
     * @param $args     Slim's Argument parameters
     *
     * @author sonali@imprintnext.com
     * @date   17th Feb 2020
     * @return Order List in Json format
     */
    public function getStoreLogs($request, $response, $args)
    {
        //Get order details by order id
        $orderDetailsObj = $this->getOrderLog($args['id']);
        return json_clean_decode($orderDetailsObj, true);
    }
    
    /**
     * GET : Default order statuses
     *
     * @author sonali@imprintnext.com
     * @date   25 Feb 2022
     * @return Array
     */
    public function getDefaultOrderStatuses() {
        return $this->orderStatus();        
    }

    /**
     * POST : Order placed
     *
     * @param orderId
     * @param orderData
     *
     * @author sonali@imprintnext.com
     * @date       11 feb 2022
     * @return Array
     */
    public function updateStoreOrderStatus($orderId, $orderData) {
        $response = "failed";
        $orderStatus = ['order_status' => $orderData['statusKey']];
        $ordersInit = new Orders();
        $ordersInit->where('order_id', $orderId)
                    ->update($orderStatus);
        $storeResponse =  $this->updateOrderStatuses($orderId, $orderData);
        if($storeResponse['status'] == 1) {
            $response = "success";
        }
        return $response;
    }

    /**
     * GET : Default order statuses
     *
     * @author sonali@imprintnext.com
     * @date       17 feb 2022
     * @return Array
     */
    public function storeOrder($decodeData){
        try {
            if (!empty($decodeData)) {
                return $this->createStoreOrder($decodeData);
            }
        } catch (\Exception $e) {
            // Store exception in logs
            create_log(
                'store',
                'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'post all the order details',
                        'controller' => 'storeordercontroller',
                    ],
                ]
            );
        }
    }

     /**
     * GET : updte to an archive order
     *
     * @author sonali@imprintnext.com
     * @date       17 feb 2022
     * @return Array
     */


    public function archiveOrderById($request, $response, $args)
    {
        $storeResponse = [];
        $orderIds = $request->getParsedBody();
        try {
            $orderData = [
                "statusKey" => 10,
                "store_id" => $orderIds['store_id'],
            ];
            $orderIDs = explode (",", str_replace(array( '[', ']' ), '', $orderIds['order_id']));
            foreach($orderIDs as $orderKey => $orderValue){
               $storeResponse = $this->updateOrderStatuses($orderIDs[$orderKey],$orderData);
            }
            // Calling to Custom API for getting Archive status
        } catch (\Exception $e) {
            // Store exception in logs
            create_log(
                'store', 'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'Archive Status',
                    ],
                ]
            );
        }
        return $storeResponse;
    }

    /**
     * GET: Order of single item details
     *
     * @param $order_id
     * @param $store_id
     *
     * @author divya@imprintnext.com
     * @date   22 March 2022
     * @return Array
     */
    public function getStoreOrderLineItemDetails($order_id, $orderItemId, $is_customer, $store_id) {
        return $this->getOrderLineItemData($order_id, $orderItemId, $is_customer);
    }

    public function getOrderShortDetails($orderIds, $storeId){
        return $this->getOrderShotInfo($orderIds, $storeId);
    }

    /**
     * Create Reorder
     *
     * @author     steve@imprintnext.com
     * @date       21 Apr 2023
     * @param  orderId
     * @param  order item no.
     * @response   checkout url
     */
    public function storeReorder($request, $response, $args)
    {
        $allPutValues = $request->getParsedBody();
        $orderId =  $allPutValues['orderid'];
        $orderItemIds =  $allPutValues['orderitemids'];
        return $this->createStoreReorder($orderId, $orderItemIds);
    }

     /**
     * GET: Order line item details with attributes
     *
     * @author     divya@imprintnext.com
     * @date       03 January 2024
     * @param  orderId
     * @response   order line item details
     */
    public function orderItemAttribute($orderId, $storeId) {
        return $this->getAttributeFromStore($orderId, $storeId);
    }
}
