<?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();
            $status_sale = "1,3,4,5,6,7,8,11";
            $status_cancelled = "9,10,12";

            for($i = 12; $i >= 0; $i--) {
                $date_start = date('Y-m-01', strtotime("-$i month"));
                $date_end  = date('Y-m-t', strtotime("-$i month"));
                $month = date('F Y', strtotime($date_start));
                $stmt = $db->query("SELECT COUNT(id) AS 'total' FROM ".$db->prefix."orders WHERE status IN ({$status_sale}) AND CAST(date_added AS DATE) BETWEEN :date_start AND :date_end", array(':date_start'=>$date_start, ':date_end'=>$date_end));
                if($stmt->num_rows > 0){
                    $total      = $stmt->row["total"];
                    $results['sale']['labels'][] = $month;
                    $results['sale']['data'][] = $total;
                }else{
                    $results['sale']['labels'][] = $month;
                    $results['sale']['data'][] = 0;
                }
            }

            for($i = 12; $i >= 0; $i--) {
                $date_start = date('Y-m-01', strtotime("-$i month"));
                $date_end  = date('Y-m-t', strtotime("-$i month"));
                $month = date('F Y', strtotime($date_start));
                $stmt = $db->query("SELECT COUNT(id) AS 'total' FROM ".$db->prefix."orders WHERE status IN ({$status_cancelled}) AND CAST(date_added AS DATE) BETWEEN :date_start AND :date_end", array(':date_start'=>$date_start, ':date_end'=>$date_end));
                if($stmt->num_rows > 0){
                    $total      = $stmt->row["total"];
                    $results['cancelled']['labels'][] = $month;
                    $results['cancelled']['data'][] = $total;
                }else{
                    $results['cancelled']['labels'][] = $month;
                    $results['cancelled']['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);