<?php
declare(strict_types=1);

namespace Autogedal\StockLog\Block\Adminhtml;

use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;

class History extends Template
{
    protected $_template = 'Autogedal_StockLog::history.phtml';

    private ResourceConnection $resource;
    private TimezoneInterface $timezone;

    public function __construct(
        Context $context,
        ResourceConnection $resource,
        TimezoneInterface $timezone,
        array $data = []
    ) {
        $this->resource  = $resource;
        $this->timezone  = $timezone;
        parent::__construct($context, $data);
    }

    public function formatLogDate(string $utcDate): string
    {
        try {
            return $this->timezone->formatDateTime(
                new \DateTime($utcDate, new \DateTimeZone('UTC')),
                \IntlDateFormatter::SHORT,
                \IntlDateFormatter::SHORT
            );
        } catch (\Throwable $e) {
            return $utcDate;
        }
    }

    public function getProductId(): int
    {
        return (int)$this->getRequest()->getParam('product_id', 0);
    }

    public function getSku(): string
    {
        $rows = $this->getHistoryData();
        return !empty($rows) ? (string)($rows[0]['sku'] ?? '') : '';
    }

    public function getHistoryData(): array
    {
        $productId = $this->getProductId();
        if ($productId === 0) {
            return [];
        }
        $connection = $this->resource->getConnection();
        return $connection->fetchAll(
            $connection->select()
                ->from($this->resource->getTableName('autogedal_stock_log'))
                ->where('product_id = ?', $productId)
                ->order('created_at DESC')
                ->limit(500)
        );
    }

    public function getChartJson(): string
    {
        $rows   = array_reverse($this->getHistoryData());
        $labels = [];
        $qtys   = [];
        $colors = [];

        foreach ($rows as $row) {
            $labels[] = $row['created_at'];
            $qtys[]   = (float)$row['qty_after'];
            $colors[] = (int)$row['is_in_stock_after'] === 0 ? 'rgba(220,53,69,0.8)' : 'rgba(40,167,69,0.8)';
        }

        return (string)json_encode(['labels' => $labels, 'qtys' => $qtys, 'colors' => $colors]);
    }

    public function getBackUrl(): string
    {
        return $this->getUrl('autogedal_stocklog/index/index');
    }
}
