<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start output buffering
ob_start();

// Include database configuration
require_once 'admin/includes/config.php';

// Initialize response array
$response = [
    'success' => false,
    'message' => 'An error occurred. Please try again.'
];

// Function to log errors
function logError($message) {
    $logFile = __DIR__ . '/error_log.txt';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Log the POST data for debugging
    logError('Form submitted with data: ' . print_r($_POST, true));
    // reCAPTCHA validation passed, process the form
            $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
            $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
            $phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING);
            $message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);
            
    // Basic validation
    if (empty($name) || empty($email) || empty($message)) {
        $response['message'] = 'Name, email, and message are required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response['message'] = 'Invalid email format';
    } else {
        // Prepare an insert statement with the correct table name and fields
        $sql = "INSERT INTO contact_submissions (name, email, phone, subject, message, status) 
                VALUES (?, ?, ?, 'Contact Form', ?, 'new')";
        
        if ($stmt = $conn->prepare($sql)) {
            logError('SQL prepared successfully');
            // Get additional information
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
            
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("ssss", $param_name, $param_email, $param_phone, $param_message);
            
            // Set parameters
            $param_name = $name;
            $param_email = $email;
            $param_phone = $phone;
            $param_message = $message;
                    
            // Attempt to execute the prepared statement
            if ($stmt->execute()) {
                logError('Query executed successfully');
                $response = [
                    'success' => true,
                    'name' => $name,
                    'message' => 'Your message has been sent successfully! We will get back to you soon.'
                ];
                        
                // Send email notification (uncomment and configure as needed)
                /*
                $to = "admin@ecogramlifestyle.com";
                $subject = "New Contact Form Submission";
                $email_message = "New contact form submission:\n\n";
                $email_message .= "Name: $name\n";
                $email_message .= "Email: $email\n";
                $email_message .= "Phone: " . ($phone ?: 'Not provided') . "\n";
                $email_message .= "Message:\n$message\n\n";
                $email_message .= "Submitted on: " . date('Y-m-d H:i:s') . "\n";
                $headers = "From: $email\r\n";
                $headers .= "Reply-To: $email\r\n";
                $headers .= "X-Mailer: PHP/" . phpversion();
                
                @mail($to, $subject, $email_message, $headers);
                */
            } else {
                $errorMsg = 'Database execution error: ' . $stmt->error;
                logError($errorMsg);
                $response['message'] = 'Oops! Something went wrong. Please try again later.';
                $response['error'] = $errorMsg;
            }
            
            // Close statement
            $stmt->close();
        } else {
            $errorMsg = 'Database preparation error: ' . $conn->error;
            logError($errorMsg);
            $response['message'] = 'Database error. Please try again later.';
            $response['error'] = $errorMsg;
        }
    }
} else {
    $response['message'] = 'Invalid request method';
}

// Close connection
if (isset($conn)) {
    $conn->close();
}

// Get any output that might have been generated
$output = ob_get_clean();

// Log any unexpected output
if (!empty($output)) {
    logError('Unexpected output: ' . $output);
}

// Return JSON response
header('Content-Type: application/json');
// Add debug info if in development
if (isset($_GET['debug'])) {
    $response['debug'] = [
        'post_data' => $_POST,
        'sql' => $sql ?? null,
        'params' => [
            'name' => $param_name ?? null,
            'email' => $param_email ?? null,
            'phone' => $param_phone ?? null,
            'ip' => $param_ip ?? null,
            'user_agent' => $param_user_agent ?? null
        ]
    ];
}
echo json_encode($response);
?>
