<?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 'config.php';

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

$response = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = mysqli_real_escape_string($con, $_POST['user_id']);
    $auth = mysqli_real_escape_string($con, $_POST['auth']);
    $message = check_input($_POST['message']);

    date_default_timezone_set("Africa/Lagos");
    $date_reg = date("d-M-Y h:i:s a"); 

    try {
        // Verify if user exists in the database
        $user_query = $con->prepare("SELECT firstname, lastname, email FROM users WHERE user_id = ? AND auth = ?");
        $user_query->bind_param("ss", $user_id, $auth);
        $user_query->execute();
        $user_result = $user_query->get_result();

        if ($user_result->num_rows > 0) {
            $user = $user_result->fetch_assoc();
            $firstname = $user['firstname'];
            $lastname = $user['lastname'];
            $email = $user['email'];
        
            $name = $firstname." ".$lastname;

            // Insert inquiry into the database
            $stmt = $con->prepare("INSERT INTO inquiry (user_id, name, email, message, date_reg) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("sssss", $user_id, $name, $email, $message, $date_reg);

            if ($stmt->execute()) {
                $response['status'] = true;
                $response['success'] = "Enquiry submitted successfully!";
            } else {
                $response['status'] = false;
                $response['success'] = "Database error: " . $stmt->error;
            }
            $stmt->close();
        } else {
            $response['status'] = false;
            $response['success'] = "User not found or invalid credentials.";
        }
        $user_query->close();
    } catch (Exception $e) {
        $response['status'] = false;
        $response['success'] = "Error: " . $e->getMessage();
    }
} else {
    $response['status'] = false;
    $response['success'] = "Invalid request method.";
}

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

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