<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

include 'db/config.php';

function check_input($par) {
    $par = trim($par);
    $par = stripslashes($par);
    $par = htmlspecialchars($par);
    return $par;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Set the timezone to Africa/Lagos
    date_default_timezone_set("Africa/Lagos");

    // Sanitize and retrieve POST data
    $user_id = mysqli_real_escape_string($con, $_POST['user_id']);
    $auth = mysqli_real_escape_string($con, $_POST['auth']);
    $message = htmlspecialchars(trim($_POST['message']));
    $date_reg = date("d-M-Y h:i:s a"); // Current date and time in Lagos timezone

    $response = [];

    // Check if user exists in the `users` table
    $user_query = $con->prepare("SELECT firstname, lastname, email FROM users WHERE user_id = ? AND auth = ?");
    if (!$user_query) {
        $response['success'] = false;
        $response['message'] = 'Database error: ' . $con->error;
        echo json_encode($response);
        exit();
    }
    
    $user_query->bind_param("ss", $user_id, $auth);
    $user_query->execute();
    $result = $user_query->get_result();

    if ($result->num_rows > 0) {
        // User exists, fetch name and email
        $row = $result->fetch_assoc();
        $firstname = $row['firstname'];
        $lastname = $row['lastname'];
        $email = $row['email'];
        
        $name = $firstname." ".$lastname;

        // Insert into `feedback` table
        $insert_query = $con->prepare("INSERT INTO feedback (user_id, name, email, feedback, date_reg) VALUES (?, ?, ?, ?, ?)");
        if (!$insert_query) {
            $response['success'] = false;
            $response['message'] = 'Database error: ' . $con->error;
            echo json_encode($response);
            exit();
        }
        
        $insert_query->bind_param("sssss", $user_id, $name, $email, $message, $date_reg);
        if ($insert_query->execute()) {
            $response['success'] = true;
            $response['message'] = 'Feedback submitted successfully';
            $response['local_time'] = $date_reg; // Include the local time in the response
        } else {
            $response['success'] = false;
            $response['message'] = 'Failed to submit feedback: ' . $insert_query->error;
        }

        $insert_query->close();
    } else {
        // User not found
        $response['success'] = false;
        $response['message'] = 'User not found';
    }

    $user_query->close();
} else {
    $response['success'] = false;
    $response['message'] = 'Invalid request method';
}

// Return JSON response
header('Content-Type: application/json; charset=utf-8');
echo json_encode($response);

// Close the database connection
$con->close();
?>
