<?php
    header('Access-Control-Allow-Origin: '.$config->get('site_url'));
    header('Content-Type: application/json');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');
    
    $response;
    if($_SERVER["REQUEST_METHOD"] == "POST") {
        if(isset($_POST['csrf_token']) && $csrf_generator->validate($_POST['csrf_token'])) {
            $results = array();
            for($i = 14; $i >= 0; $i--) {
                $date       = date("Y-m-d", strtotime("-$i day"));
                $stmt  	= $db->query("SELECT COUNT(id) AS 'total' FROM ".$db->prefix."orders WHERE CAST(date_added AS DATE) = '{$date}'");
                if($stmt->num_rows > 0){
                    $total      = $stmt->row["total"];
                    $results['labels'][] = $date;
                    $results['data'][] = (int)$total;
                }else{
                    $results['labels'][] = $date;
                    $results['data'][] = 0;
                }
            }
            $response = array('status'=>true, 'result'=>$results);
        } else {
            $response = array('status'=>false, 'message'=>'Hatalı CSRF token. Lütfen daha sonra tekrar deneyiniz.');
        }
    } else {
        $response = array('status'=>false, 'message'=>'Hatalı istek. Lütfen daha sonra tekrar deneyiniz.');
    }

    echo json_encode($response);