<?php
header('Access-Control-Allow-Origin: *');
header("Content-type: application/json; charset=utf-8");

if (isset($_SERVER['HTTP_ORIGIN'])) {
  // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
  // you want to allow, and if so:
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Credentials: true');
  header('Access-Control-Max-Age: 1000');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
    // may also be using PUT, PATCH, HEAD etc
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
  }

  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
    header("Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization");
  }
  exit(0);
}

include '../../utils/database.php';
include '../../utils/helper.php';

error_reporting(0);

//showErrors();

$conn = new mysqli($servername, $username, $password, $dbname_process);
mysqli_set_charset($conn, "utf8");
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$type = $_GET['type'];

$allQuestions = array();

$query = "SELECT * FROM questionsV2 WHERE `type`='$type' ORDER BY `id`";
$result = $conn->query($query);
if ($result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
    $res["question"] = $row["text"];
    $res["description"] = $row["description"];
    $res["type"] = $row["type"];
    $qid = $row["qid"];
    $answers = array();

    $resultAns = $conn->query("SELECT * FROM answersV2 WHERE `qid`='$qid'");
    if ($resultAns->num_rows > 0) {
      while ($rowAns = $resultAns->fetch_assoc()) {
        array_push($answers , $rowAns["aid"]);
      }
    }

    $res["answers"] = $answers;

    array_push($allQuestions, $res);
  }
}

$response['success'] = 'true';
$response['message'] = '200';
$response['data'] = $allQuestions;
$json_response = json_encode($response);
echo $json_response;
die();

// else {
//     $response['success'] = 'false';
//     $response['message'] = 'مشکل در ذخیره سازی اطلاعات';
//     $json_response = json_encode($response);
//     echo $json_response;
//     die();
// }
