<?php
require_once __DIR__ . '/config.php';

$pageTitle = "Thrillsense - Contact";
$metaDescription = "Contact ThrillSense for theme park news tips, press releases, media enquiries, corrections, advertising and partnership opportunities.";
$extra_head = '<link rel="stylesheet" href="/styles/contact.css">';

$successMessage = '';
$errorMessage = '';

$name = '';
$email = '';
$company = '';
$enquiryType = '';
$subject = '';
$message = '';
$consent = '';

$enquiryTypes = [
    'News tip',
    'Press release',
    'Media / PR enquiry',
    'Correction',
    'Advertising / partnership',
    'General enquiry'
];

function getClientIpAddress(): string
{
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }

    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ips[0]);
    }

    return $_SERVER['REMOTE_ADDR'] ?? '';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $company = trim($_POST['company'] ?? '');
    $enquiryType = trim($_POST['enquiry_type'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $consent = $_POST['consent'] ?? '';

    // Honeypot field - real users should not fill this in.
    $website = trim($_POST['website'] ?? '');

    // Basic timer - helps block bots that submit instantly.
    $formStartedAt = (int)($_POST['form_started_at'] ?? 0);
    $timeTaken = time() - $formStartedAt;

    $ipAddress = getClientIpAddress();

    $lowerSubject = strtolower($subject);
    $lowerMessage = strtolower($message);

    $linkCount = substr_count($lowerMessage, 'http://')
        + substr_count($lowerMessage, 'https://')
        + substr_count($lowerSubject, 'http://')
        + substr_count($lowerSubject, 'https://');

    $spamWords = [
        'casino',
        'viagra',
        'crypto',
        'cryptocurrency',
        'bitcoin',
        'loan',
        'payday',
        'seo backlinks',
        'backlinks',
        'guest post',
        'link insertion',
        'telegram',
        'whatsapp',
        'porn',
        'xxx'
    ];

    $containsSpamWord = false;

    foreach ($spamWords as $spamWord) {
        if (stripos($subject, $spamWord) !== false || stripos($message, $spamWord) !== false) {
            $containsSpamWord = true;
            break;
        }
    }

    $recentSubmissionCount = 0;

    if ($ipAddress !== '') {
        try {
            $rateStmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM contact_enquiries
                WHERE ip_address = :ip_address
                AND created_at >= DATE_SUB(NOW(), INTERVAL 15 MINUTE)
            ");

            $rateStmt->execute([
                ':ip_address' => $ipAddress
            ]);

            $recentSubmissionCount = (int)$rateStmt->fetchColumn();
        } catch (PDOException $e) {
            $recentSubmissionCount = 0;
        }
    }

    if ($website !== '') {
        $errorMessage = "Sorry, something went wrong. Please try again.";
    } elseif ($formStartedAt <= 0 || $timeTaken < 4) {
        $errorMessage = "Sorry, something went wrong. Please try again.";
    } elseif ($recentSubmissionCount >= 3) {
        $errorMessage = "You have submitted too many messages recently. Please try again later.";
    } elseif ($name === '' || $email === '' || $enquiryType === '' || $subject === '' || $message === '') {
        $errorMessage = "Please complete all required fields.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errorMessage = "Please enter a valid email address.";
    } elseif (!in_array($enquiryType, $enquiryTypes, true)) {
        $errorMessage = "Please select a valid enquiry type.";
    } elseif ($consent !== 'yes') {
        $errorMessage = "Please confirm that you are happy for ThrillSense to use your details to respond to this enquiry.";
    } elseif (mb_strlen($message) < 20) {
        $errorMessage = "Please enter a little more detail in your message.";
    } elseif (mb_strlen($message) > 5000) {
        $errorMessage = "Your message is too long. Please keep it under 5,000 characters.";
    } elseif ($linkCount > 2) {
        $errorMessage = "Sorry, your message could not be sent.";
    } elseif ($containsSpamWord) {
        $errorMessage = "Sorry, your message could not be sent.";
    } else {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO contact_enquiries 
                    (name, email, company, enquiry_type, subject, message, status, ip_address, created_at)
                VALUES 
                    (:name, :email, :company, :enquiry_type, :subject, :message, 'new', :ip_address, NOW())
            ");

            $stmt->execute([
                ':name' => $name,
                ':email' => $email,
                ':company' => $company !== '' ? $company : null,
                ':enquiry_type' => $enquiryType,
                ':subject' => $subject,
                ':message' => $message,
                ':ip_address' => $ipAddress !== '' ? $ipAddress : null
            ]);

            // Optional email notification. Database save is the important part.
            $to = "hello@thrillsense.com";
            $emailSubject = "New ThrillSense enquiry: " . $subject;

            $emailBody = "A new enquiry has been submitted via ThrillSense.\n\n";
            $emailBody .= "Name: " . $name . "\n";
            $emailBody .= "Email: " . $email . "\n";
            $emailBody .= "Company / Website: " . ($company !== '' ? $company : 'Not provided') . "\n";
            $emailBody .= "Enquiry Type: " . $enquiryType . "\n";
            $emailBody .= "Subject: " . $subject . "\n";
            $emailBody .= "IP Address: " . ($ipAddress !== '' ? $ipAddress : 'Not available') . "\n\n";
            $emailBody .= "Message:\n" . $message . "\n\n";
            $emailBody .= "You can view this enquiry in the ThrillSense admin panel.";

            $headers = [];
            $headers[] = "From: ThrillSense <hello@thrillsense.com>";
            $headers[] = "Reply-To: " . $name . " <" . $email . ">";
            $headers[] = "Content-Type: text/plain; charset=UTF-8";

            @mail($to, $emailSubject, $emailBody, implode("\r\n", $headers));

            $successMessage = "Thanks for getting in touch. Your message has been sent and we’ll respond where appropriate.";

            $name = '';
            $email = '';
            $company = '';
            $enquiryType = '';
            $subject = '';
            $message = '';
            $consent = '';

        } catch (PDOException $e) {
            $errorMessage = "Sorry, your message could not be sent right now. Please email us directly at hello@thrillsense.com.";
        }
    }
}

require_once __DIR__ . '/includes/header.php';
?>

<main class="news-page">

    <section class="hero-news">
        <div class="hero-text">
            <h1 class="title-alt">Contact</h1>
        </div>
    </section>

    <section class="container py-5">

        <div class="contact-intro text-center mb-5">
            <p>
                Have a theme park news tip, press release, media enquiry or question for ThrillSense?
                Use the form below to get in touch.
            </p>
        </div>

        <div class="row g-4">

            <div class="col-lg-8">
                <div class="contact-card">
                    <h2>Send us a message</h2>

                    <?php if ($successMessage !== ''): ?>
                        <div class="contact-message success">
                            <?php echo htmlspecialchars($successMessage, ENT_QUOTES, 'UTF-8'); ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($errorMessage !== ''): ?>
                        <div class="contact-message error">
                            <?php echo htmlspecialchars($errorMessage, ENT_QUOTES, 'UTF-8'); ?>
                        </div>
                    <?php endif; ?>

                    <form method="post" action="/contact" novalidate>

                        <div class="contact-hidden">
                            <label for="website">Website</label>
                            <input type="text" id="website" name="website" tabindex="-1" autocomplete="off">
                        </div>

                        <input type="hidden" name="form_started_at" value="<?php echo time(); ?>">

                        <div class="contact-form-group">
                            <label for="name">Name <span>*</span></label>
                            <input
                                type="text"
                                id="name"
                                name="name"
                                value="<?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); ?>"
                                required
                            >
                        </div>

                        <div class="contact-form-group">
                            <label for="email">Email address <span>*</span></label>
                            <input
                                type="email"
                                id="email"
                                name="email"
                                value="<?php echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); ?>"
                                required
                            >
                        </div>

                        <div class="contact-form-group">
                            <label for="company">Company / website</label>
                            <input
                                type="text"
                                id="company"
                                name="company"
                                value="<?php echo htmlspecialchars($company, ENT_QUOTES, 'UTF-8'); ?>"
                            >
                        </div>

                        <div class="contact-form-group">
                            <label for="enquiry_type">Enquiry type <span>*</span></label>
                            <select id="enquiry_type" name="enquiry_type" required>
                                <option value="">Please select</option>

                                <?php foreach ($enquiryTypes as $type): ?>
                                    <option
                                        value="<?php echo htmlspecialchars($type, ENT_QUOTES, 'UTF-8'); ?>"
                                        <?php echo $enquiryType === $type ? 'selected' : ''; ?>
                                    >
                                        <?php echo htmlspecialchars($type, ENT_QUOTES, 'UTF-8'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="contact-form-group">
                            <label for="subject">Subject <span>*</span></label>
                            <input
                                type="text"
                                id="subject"
                                name="subject"
                                value="<?php echo htmlspecialchars($subject, ENT_QUOTES, 'UTF-8'); ?>"
                                required
                            >
                        </div>

                        <div class="contact-form-group">
                            <label for="message">Message <span>*</span></label>
                            <textarea id="message" name="message" required><?php echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8'); ?></textarea>
                        </div>

                        <label class="contact-consent">
                            <input
                                type="checkbox"
                                name="consent"
                                value="yes"
                                <?php echo $consent === 'yes' ? 'checked' : ''; ?>
                                required
                            >
                            <span>
                                I understand ThrillSense will use the details provided to respond to this enquiry.
                            </span>
                        </label>

<div class="contact-button-row">
    <button type="submit" class="contact-button">Send message</button>
</div>

                    </form>
                </div>
            </div>

            <div class="col-lg-4">
                <aside class="contact-info-card">
                    <h2>What can you contact us about?</h2>

                    <p>
                        ThrillSense covers theme park news, features, guides and updates from across the UK and beyond.
                        We welcome relevant enquiries from readers, parks, PR teams, agencies and potential partners.
                    </p>

                    <ul class="contact-info-list">
                        <li>
                            <strong>News tips</strong>
                            Ride updates, planning applications, park changes or rumours worth looking into.
                        </li>

                        <li>
                            <strong>Press releases</strong>
                            Theme park announcements, attraction openings, events and media updates.
                        </li>

                        <li>
                            <strong>Corrections</strong>
                            If something needs correcting or clarifying, please let us know.
                        </li>

                        <li>
                            <strong>Partnerships</strong>
                            Advertising, affiliate, ticketing or content opportunities.
                        </li>

                        <li>
                            <strong>Prefer email?</strong>
                            Contact us at <a href="mailto:hello@thrillsense.com">hello@thrillsense.com</a>.
                        </li>
                    </ul>
                </aside>
            </div>

        </div>

    </section>

</main>

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