<?php
header('Access-Control-Allow-Origin: *');
header(
    'Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS'
);
header(
    'Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization'
);
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
    header("HTTP/1.1 200 OK");
    die();
}

require '../../../../config/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'));

    if (
        !empty($data->firstName) &&
        !empty($data->lastName) &&
        !empty($data->messageCategory) &&
        !empty($data->email) &&
        !empty($data->phone)
    ) {

        $fName = mysqli_real_escape_string($con, $data->firstName);
        $lName = mysqli_real_escape_string($con, $data->lastName);
        $messageCategory = mysqli_real_escape_string($con, $data->messageCategory);
        $email = mysqli_real_escape_string($con, $data->email);
        $phone = mysqli_real_escape_string($con, $data->phone);
        $message = mysqli_real_escape_string($con, $data->message);
        $ratings = $data->ratings;
        $status = 0;
        $dateTime = date("Y-m-d H:i:s");

        $query = "INSERT INTO Messages (`messageId`,`messageCategory`,`fname`,`lname`,`email`,`phone`,`message`,`ratings`,`status`,`dateCreated`) VALUES (null,$messageCategory,'$fName','$lName','$email','$phone','$message',$ratings,'$status','$dateTime');";

        if (mysqli_query($con, $query)) {
            if (mysqli_affected_rows($con) == 1) {
                echo json_encode([
                    'status' => 1,
                    'message' => 'Data inserted successfully.'
                ]);
                http_response_code(200);
            } else {
                echo json_encode([
                    'status' => 0,
                    'message' => 'Could not insert data.'
                ]);
                http_response_code(400);
            }
        }
    } else {
        echo json_encode([
            'status' => 0,
            'message' => 'Required fields are missing.'
        ]);
        http_response_code(400);
    }
} else {
    http_response_code(500);
    echo json_encode([
        'status' => -1
    ]);
    die();
}
