<?php


namespace Shop\Controllers;

use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\Exceptions\PageNotFound;
use Diamond\Helpers\Date;
use Shop\Repositories\CustomerOrder\CustomerOrderCriteria;
use Symfony\Component\HttpFoundation\JsonResponse;
use Core\BaseController;
use Shop\Repositories\CustomerOrder\CustomerOrderRepository;
use Shop\Repositories\ProviderOrder\ProviderOrderRepository;

class OrderController extends BaseController implements RequestAwareInterface
{
    use RequestAwareTrait;

    protected $customerOrderRepository;
    protected $providerOrderRepository;

    /**
     * OrderController constructor.
     * @param CustomerOrderRepository $customerOrderRepository
     * @param ProviderOrderRepository $providerOrderRepository
     */
    public function __construct(CustomerOrderRepository $customerOrderRepository,
                                ProviderOrderRepository $providerOrderRepository)
    {
        $this->providerOrderRepository = $providerOrderRepository;
        $this->customerOrderRepository = $customerOrderRepository;
    }

    /**
     * @return JsonResponse
     * @throws \TypeError
     */
    public function aggregateSumDay(): JsonResponse
    {

        $limit = (int)$this->request->query->get("interval");

        $orders = $this->customerOrderRepository->findByCriteria(
            CustomerOrderCriteria::create()->setLimit(100)->setSortById('DESC')
        );

        $dates = Date::getDefaultDates($limit, 24);

        foreach ($orders as $order) {
            //если идет число не в часах

            $i = (new \DateTime($order->getDateTime()->format('Y-m-d')))->getTimestamp();

            if(!isset($dates[$i])){
                continue;
            }

            $sum = $dates[$i][1]??0;

            $sum+= $order->getSum();

            $dates[$i] = array(
                $i * 1000,
                $sum,
                date(\Diamond\Helpers\Date::formatDisplay(), $i)
            );
        }

        $lastIndex = strtotime((new \DateTime())->format('Y-m-d'));
        unset($dates[$lastIndex]);

        ksort($dates);

        //[[1625605200000,0,"07.07.2021 00:00"],
        return new JsonResponse(array_values($dates));
    }


    public function stateImage(array $params): void
    {
        $id = (int)$params['id'];
        /**
         * @var \Shop\Models\Order\Order $order
         */
        if (!$order = $this->customerOrderRepository->findById($id)) {
            $order = $this->providerOrderRepository->findById($id);
        }


        if (!isset($order)) {
            throw new PageNotFound('not found by id ' . $id);
        }

        $states = [];
        $all = $order->getOrderItems()->count();

        foreach ($order->getOrderItems() as $item) {
            $states[$item->getStateId()]['items'][] = $item->getId();
            $states[$item->getStateId()]['color'] = $item->getState()->getColor();
            $states[$item->getStateId()]['percent'] = round(count($states[$item->getStateId()]['items']) / $all * 100);
        }

        $data = [];
        foreach ($states as $state) {
            $data[$state['color']] = $state['percent'];
        }
        $image = $this->generate($data, 18, 18);


        header('Content-type: image/gif');
        imagegif($image);
        imagedestroy($image);
    }

    public function generate($result = array('808080' => 33, '800080' => 33, '000000' => 33), int $width, int $height)
    {
        $sum = 0;

        /*Calculate sum of all elements*/
        foreach ($result as $row) {
            $sum += $row;
        }

        $image = imagecreatetruecolor($width, $height);
        imagefilledrectangle($image, 0, 0, $width, $height, imagecolorallocate($image, 255, 255, 255));

        $old_grad = 0;
        foreach ($result as $key => $row) {
            /*split array*/
            list($r, $g, $b) = $this->_html2rgb($key);

            /*Calculate sectors in degrees*/
            $grad = $old_grad + round(($row * 360) / $sum);

            /*LibGD rounds degrees.*/
            if (round($old_grad) === round($grad))
                continue;
            $color = imagecolorallocate($image, $r, $g, $b);
            imagefilledarc($image, $width / 2, $height / 2, $width, $height, $old_grad, $grad, $color, IMG_ARC_PIE);
            $old_grad = $grad;
        }

        return $image;
    }

    /*
     * @param $color
     *   WebColor
     *
     * @return array
     *   Color in RGB notation
     */
    private function _html2rgb($color)
    {
        if (!$color) {
            return false;
        }
        if ($color[0] == '#')
            $color = substr($color, 1);
        if (strlen($color) == 6)
            list($r, $g, $b) = str_split($color, 2);
        else
            return false;

        $r = hexdec($r);
        $g = hexdec($g);
        $b = hexdec($b);
        return array($r, $g, $b);
    }

}