<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../services/facto/FactoDashboardService.php';

require_login();

header('Content-Type: application/json; charset=utf-8');

$to = isset($_GET['to']) ? $_GET['to'] : date('Y-m-d');
$from = isset($_GET['from']) ? $_GET['from'] : date('Y-m-d', strtotime('-30 days'));
$group = isset($_GET['group']) ? $_GET['group'] : 'day';

if (!in_array($group, array('day', 'week', 'month'))) {
    $group = 'day';
}

$maxFrom = date('Y-m-d', strtotime($to . ' -12 months'));

if (strtotime($from) < strtotime($maxFrom)) {
    $from = $maxFrom;
}

try {
    $service = new FactoDashboardService();

    echo json_encode(
        $service->getSalesQuotesChart($from, $to, $group)
    );
} catch (Exception $e) {
    http_response_code(500);

    echo json_encode(array(
        'error' => true,
        'message' => $e->getMessage()
    ));
}