<?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'])) {
            $response = array();
            $vpos_options       = $utils->getOption("paytr-pos");

            $merchant_id = $vpos_options[0]["merchant_id"];
            $merchant_key = $vpos_options[0]["merchant_key"];
            $merchant_salt = $vpos_options[0]["merchant_salt"];

            $start_date = date('Y-m-d 00:00:00', strtotime($_POST['date_start']));
            $end_date = date('Y-m-d 23:59:59', strtotime($_POST['date_end']));

            $paytr_token = base64_encode(hash_hmac('sha256', $merchant_id . $start_date . $end_date . $merchant_salt, $merchant_key, true));

            $post_vals = array('merchant_id' => $merchant_id,
                'start_date' => $start_date,
                'end_date' => $end_date,
                'paytr_token' => $paytr_token,
                'dummy' => 0
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://www.paytr.com/rapor/islem-dokumu");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vals);
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 90);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 90);

            $result = @curl_exec($ch);

            if (curl_errno($ch)) {
                $response = array('status'=>false, 'message'=>"Hata! ".curl_error($ch));
                curl_close($ch);
            }

            curl_close($ch);

            $result = json_decode($result, 1);

            if ($result['status'] == 'success') {
                $response = array('status'=>true, 'result'=>$result['list']);
            } elseif ($result['status'] == 'failed') {
                $response = array('status'=>false, 'message'=>"ilgili tarih araliginda islem bulunamadi");
            }  else {
                $response = array('status'=>false, 'message'=>$result['err_no'] . " - " . $result['err_msg']);
            }
            
        }else{
            $response = array('status'=>false, 'message'=>"Hatalı CSRF Token!");
        }
    }else{
        $response = array('status'=>false, 'message'=>"Hatalı İstek!");
    }

    echo json_encode($response);