<?php

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Content-Type: application/json; charset=UTF-8");

include_once("../database.php");
$postData = file_get_contents("php://input");

if(isset($postData) && !empty($postData)){
    $request = json_decode($postData);
    $username = mysqli_real_escape_string($mysqli, trim($request->username));
    $title = mysqli_real_escape_string($mysqli, trim($request->title));
    $out = mysqli_real_escape_string($mysqli, trim($request->out));
    $ind = mysqli_real_escape_string($mysqli, trim($request->ind));
    $isSubmit = trim($request->isSubmit);
    if((int)$ind==0){
        $sql = "SELECT out1 FROM questions WHERE title='$title'";
        if($result = mysqli_query($mysqli,$sql)->fetch_all(MYSQLI_ASSOC)){
            $bool = 0;
            if($result[0]['out1'] === $out){
                $bool=1;
                if($isSubmit){
                    $sql1 = "UPDATE users SET rating = rating + 5 WHERE username='$username'";
                    mysqli_query($mysqli,$sql1);
                }
            }
            echo json_encode($bool);
        }
        else{
            http_response_code(404);
        }
    }
    else{
        $sql = "SELECT out2 FROM questions WHERE title='$title'";
        if($result = mysqli_query($mysqli,$sql)->fetch_all(MYSQLI_ASSOC)){
            $bool = 0;
            if($result[0]['out2'] === $out){
                $bool=1;
                if($isSubmit){
                    $sql1 = "UPDATE users SET rating = rating + 5 WHERE username='$username'";
                    mysqli_query($mysqli,$sql1);
                }
            }

            echo json_encode($bool);
        }
        else{
            http_response_code(404);
        }
    }

}

?>
