<?php
/**
 * Contact Form - Save messages to database
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/functions.php';

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name'] ?? '');
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $subject = sanitize($_POST['subject'] ?? '');
    $message = sanitize($_POST['message'] ?? '');

    if (strlen($name) < 2) $errors[] = 'Name must be at least 2 characters.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Please enter a valid email.';
    if (strlen($subject) < 2) $errors[] = 'Subject must be at least 2 characters.';
    if (strlen($message) < 10) $errors[] = 'Message must be at least 10 characters.';

    if (empty($errors)) {
        try {
            $pdo = getDbConnection();
            $stmt = $pdo->prepare('INSERT INTO contact_messages (name, email, subject, message) VALUES (?, ?, ?, ?)');
            $stmt->execute([$name, $email, $subject, $message]);
            $success = 'Thank you! Your message has been sent. We will get back to you soon.';
            $_POST = [];
        } catch (PDOException $e) {
            // If table is missing (e.g. old DB), create it and retry once
            if ($e->getCode() === '42S02' || strpos($e->getMessage(), 'contact_messages') !== false) {
                try {
                    $pdo->exec("CREATE TABLE IF NOT EXISTS contact_messages (
                        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                        name VARCHAR(100) NOT NULL,
                        email VARCHAR(255) NOT NULL,
                        subject VARCHAR(255) NOT NULL,
                        message TEXT NOT NULL,
                        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                        INDEX idx_created (created_at)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                    $stmt = $pdo->prepare('INSERT INTO contact_messages (name, email, subject, message) VALUES (?, ?, ?, ?)');
                    $stmt->execute([$name, $email, $subject, $message]);
                    $success = 'Thank you! Your message has been sent. We will get back to you soon.';
                    $_POST = [];
                } catch (PDOException $e2) {
                    $errors[] = 'Unable to send message. Please try again later.';
                }
            } else {
                $errors[] = 'Unable to send message. Please try again later.';
            }
        }
    }
}

$pageTitle = 'Contact Us';
require_once __DIR__ . '/includes/header.php';
?>

<div class="auth-card contact-card">
    <h1><i class="fas fa-envelope"></i> Contact Us</h1>
    <p class="subtitle">PHP User Registration — <a href="https://rskworld.in" target="_blank">rskworld.in</a></p>

    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <?php foreach ($errors as $e): ?>
                <div><?= htmlspecialchars($e) ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <form method="post" action="" class="auth-form">
        <div class="form-group">
            <label for="name">Your Name</label>
            <input type="text" id="name" name="name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" required minlength="2">
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" id="email" name="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label for="subject">Subject</label>
            <input type="text" id="subject" name="subject" value="<?= htmlspecialchars($_POST['subject'] ?? '') ?>" required minlength="2" placeholder="What is this about?">
        </div>
        <div class="form-group">
            <label for="message">Message</label>
            <textarea id="message" name="message" rows="5" required minlength="10" placeholder="Your message..."><?= htmlspecialchars($_POST['message'] ?? '') ?></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Send Message</button>
    </form>
    <p class="auth-footer">
        <a href="index.php">Back to Home</a> &nbsp;|&nbsp;
        <a href="mailto:help@rskworld.in">help@rskworld.in</a> | +91 93305 39277
    </p>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
