<?php 
/**
 * @package    Proxim
 * @author     Davison Pro <davisonpro.coder@gmail.com | https://davisonpro.dev>
 * @copyright  2019 Proxim
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

namespace Proxim\Api;

use Db;
use Proxim\Route;
use Proxim\Configuration;
use Proxim\Currency;
use Proxim\Database\DbQuery;
use Proxim\Order\Order;
use Proxim\Presenter\Order\OrderPresenter;
use Proxim\Validate;
use Proxim\Util\ArrayUtils;

class LatestOrders extends Route {
    public function getOrders() {
        $app = $this->app;
        $smarty = $app->container->smarty;
		$params = $app->request->get();

		$limit = (int) ArrayUtils::get($params, 'limit', 15);
        $env = ArrayUtils::get($params, 'env');

        $sql = new DbQuery();
        $sql->select('o.order_id');
        $sql->from('order', 'o');
        $sql->where("o.status_id = " . Order::FINISHED);
        $sql->orderBy('o.order_id DESC');
        $sql->limit( $limit );

        $result =  Db::getInstance(PROX_USE_SQL_SLAVE)->executeS($sql);
        
        $latest_orders = array();

        $order_presenter = new OrderPresenter();

        foreach($result as $order) {
            $order = new Order( (int) $order['order_id'] );
            if(Validate::isLoadedObject($order)) {
                $order = $order_presenter->present($order);
                $latest_orders[] = array(
                    "orderId" => $order->id, 
                    "topicTitle" => $order->title, 
                    "discipline" => $order->topic_category, 
                    "academicLevel" => $order->academic_level_title, 
                    "paperType" => $order->paper_type_title, 
                    "pages" => $order->pages
                );
            }
        }

		return $app->response([
			"lco" => $latest_orders,
			"env" => array(
				"environment" => $env,
			)
		]);
    }
}   