<?php

/**
 * Class CfFileChanges
 */
class CfFileChanges
{
    /**
     * @var string
     */
    private $userName;
    /**
     * @var array
     */
    private $labels = [
        'DIFF' => 'Change in content (with file diff)',
        'C' => 'Change in content (based on file hash)',
        'S' => 'Change in file stats'
    ];

    /**
     * CfFileChanges constructor.
     *
     * @param $userName
     */
    public function __construct($userName)
    {
        $this->userName = $userName;
    }

    /**
     * @param $from
     * @param $to
     *
     * @return array
     * @throws Exception
     */
    public function getStatistics($from, $to)
    {
        $quotedFrom = DatabaseHelper::quote($from);
        $quotedTo = DatabaseHelper::quote($to);

        $sql = "SELECT COUNT(*) as changes_count, changetype,  to_char(changetimestamp , 'dd Mon yyyy' ) as day
                FROM  filechangeslog
                WHERE changetimestamp BETWEEN $quotedFrom AND $quotedTo
                GROUP BY changetype, day
                ORDER BY day";

        $apiResult = json_decode(
            cfapi_query_post($this->userName, $sql, '', false, -1, -1, [], []),
            JSON_OBJECT_AS_ARRAY
        );

        $rows = Utils::getQueryApiResultRows($apiResult);
        $dates = $this->initDates($from, $to);

        $data = ['DIFF' => $dates, 'C' => $dates, 'S' => $dates];
        foreach ($rows as $row) {

            $changeCount = $row[0];
            $changeType = $row[1];
            $date = $row[2];

            if (isset($data[$changeType])) {
                $data[$changeType][$date] = (int) $changeCount;
            }
        }

        return [
            'data' => $data,
            'labels' => $this->labels,
            'dates' => array_keys($dates)
        ];
    }

    /**
     * @param $from
     * @param $to
     *
     * @return array
     * @throws Exception
     */
    private function initDates($from, $to)
    {
        $period = new DatePeriod(
            new DateTime($from),
            new DateInterval('P1D'),
            new DateTime($to)
        );

        $periods = [];
        foreach ($period as $date) {
            $periods[$date->format('d M Y')] = 0;
        }

        return $periods;
    }

    public function getFiles(string $query = '', int $limit = 10)
    {
        $quotedQuery = DatabaseHelper::quote("%$query%");
        $sql = "SELECT distinct filename
                FROM  filechangeslog 
                WHERE filename LIKE $quotedQuery";

        $apiResult = json_decode(
            cfapi_query_post($this->userName, $sql, '', false, -1, (int) $limit, [], []),
            JSON_OBJECT_AS_ARRAY
        );

        $rows = Utils::getQueryApiResultRows($apiResult);
        $files = [];

        foreach ($rows as $row) {
            $files[] = $row[0];
        }

        return $files;
    }

}
