<?php
date_default_timezone_set('Africa/Blantyre');

// Database connection
$conn = new mysqli('localhost', 'smplus_hrdc', '0991123495@Tomaida', 'smplus_hrdc');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Only process POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['comment_submit'])) {

    // Sanitize and trim inputs
    $name = $conn->real_escape_string(trim($_POST['name']));
    $email = $conn->real_escape_string(trim($_POST['email']));
    $comment = $conn->real_escape_string(trim($_POST['comment']));
    $post_id = intval($_POST['post_id']); // hidden input in form

    // Check if all fields are filled
    if ($name && $email && $comment && $post_id) {

        // Insert comment into database
        $sql = "INSERT INTO hrdc_comments 
                (comment_post_ID, comment_author, comment_author_email, comment_date, comment_content, comment_approved) 
                VALUES 
                ($post_id, '$name', '$email', NOW(), '$comment', 1)"; // 1 = approved

        if ($conn->query($sql)) {
            // Success: redirect back with status=success
            header("Location: news.php?id=$post_id&status=success#comments");
            exit();
        } else {
            // Database error
            header("Location: news.php?id=$post_id&status=error#comments");
            exit();
        }

    } else {
        // Missing fields
        header("Location: news.php?id=$post_id&status=empty#comments");
        exit();
    }
}
?>
