<?php
session_start();
require_once "db.php"; // Ensure db.php correctly sets up $conn as PDO

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

    // Sanitize inputs
    $name    = trim($_POST['name'] ?? '');
    $email   = trim($_POST['email'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');

    // Basic validation
    $errors = [];
    if (empty($name))    $errors[] = "Name is required.";
    if (empty($email))   $errors[] = "Email is required.";
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format.";
    if (empty($subject)) $errors[] = "Subject is required.";
    if (empty($message)) $errors[] = "Message cannot be empty.";

    // If errors exist, redirect back with error messages
    if (!empty($errors)) {
        $_SESSION['contact_error'] = implode(" ", $errors);
        header("Location: contactus.php");
        exit();
    }

    try {
        // Insert message into contact_messages table
        $stmt = $conn->prepare("
            INSERT INTO contact_messages (name, email, subject, message, status) 
            VALUES (:name, :email, :subject, :message, 'unread')
        ");
        $stmt->execute([
            ':name'    => $name,
            ':email'   => $email,
            ':subject' => $subject,
            ':message' => $message
        ]);

        $_SESSION['contact_success'] = "Your message has been sent successfully!";
    } catch (PDOException $e) {
        error_log("Contact form DB error: " . $e->getMessage());
        $_SESSION['contact_error'] = "Failed to send message. Please try again later.";
    }

    header("Location: contactus.php");
    exit();
} else {
    header("Location: contactus.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Us - Taji Yetu</title>
<link rel="icon" href="images/taji-yetu.png" type="image/png">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
<style>
body, html {
    margin:0; padding:0; height:100%;
    font-family:Arial, sans-serif;
    background:#000;
    color:#fff;
    overflow-x:hidden;
}
.contact-container {
    max-width:700px;
    margin:100px auto;
    background:#111;
    border-radius:12px;
    padding:30px;
    box-shadow:0 8px 25px rgba(255,255,255,0.1);
    position:relative;
    z-index:1;
    animation:fadeIn 0.6s ease-in-out;
}
@keyframes fadeIn {
    0% {opacity:0; transform:translateY(20px);}
    100% {opacity:1; transform:translateY(0);}
}
h2 {
    text-align:center;
    margin-bottom:20px;
    color:#fff;
}
input, textarea {
    width:100%;
    padding:12px;
    margin-top:10px;
    border-radius:8px;
    border:none;
    background:#222;
    color:#fff;
    resize:none;
}
button {
    background:#000;
    color:#fff;
    border:2px solid #fff;
    border-radius:6px;
    padding:10px 16px;
    cursor:pointer;
    transition:0.2s;
}
button:hover {
    background:#fff;
    color:#000;
}
.alert {
    margin-top:10px;
    border-radius:8px;
}
.bg-overlay {
    position:fixed;
    top:0; left:0;
    width:100%; height:100%;
    z-index:0;
    pointer-events:none;
}
</style>
</head>
<body>
<div class="bg-overlay"><canvas id="bgCanvas"></canvas></div>

<div class="contact-container">
    <h2>Contact Us</h2>
    <?php if (!empty($_SESSION['contact_error'])): ?>
        <div class="alert alert-danger"><?= $_SESSION['contact_error']; unset($_SESSION['contact_error']); ?></div>
    <?php endif; ?>
    <?php if (!empty($_SESSION['contact_success'])): ?>
        <div class="alert alert-success"><?= $_SESSION['contact_success']; unset($_SESSION['contact_success']); ?></div>
    <?php endif; ?>

    <form action="contactus_action.php" method="POST">
        <label>Name</label>
        <input type="text" name="name" required>
        <label>Email</label>
        <input type="email" name="email" required>
        <label>Subject</label>
        <input type="text" name="subject" required>
        <label>Message</label>
        <textarea name="message" rows="5" required></textarea>
        <div style="text-align:center; margin-top:15px;">
            <button type="submit">Send Message</button>
        </div>
    </form>
</div>

<script>
// Background particle animation
const canvas = document.getElementById('bgCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particles = [];
for(let i=0;i<80;i++){
    particles.push({x:Math.random()*canvas.width,y:Math.random()*canvas.height,r:Math.random()*2+1});
}
function animateParticles(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    particles.forEach(p=>{
        ctx.beginPath();
        ctx.arc(p.x,p.y,p.r,0,Math.PI*2);
        ctx.fillStyle='white';
        ctx.fill();
        p.y -= 0.3;
        if(p.y<0) p.y=canvas.height;
    });
    requestAnimationFrame(animateParticles);
}
animateParticles();
window.addEventListener('resize',()=>{
    canvas.width=window.innerWidth;
    canvas.height=window.innerHeight;
});
</script>
</body>
</html>
