<?php
ob_start();
session_start();
include_once 'config.php';
include_once 'auth.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'vendor/autoload.php';

// Flash message functions
function display_flash_message() {
    if (isset($_SESSION['flash_message'])) {
        $type = $_SESSION['flash_message']['type'] === 'success' ? 'success' : 'danger';
        $message = htmlspecialchars($_SESSION['flash_message']['message']);
        echo "<div class='alert alert-$type alert-dismissible fade show' role='alert'>
                $message
                <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
              </div>";
        unset($_SESSION['flash_message']);
    }
}

function set_flash_message($type, $message) {
    $_SESSION['flash_message'] = ['type' => $type, 'message' => $message];
}

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        set_flash_message('danger', 'Invalid security token. Please try again.');
    } else {
        $name    = trim($_POST['name'] ?? '');
        $email   = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
        $subject = trim($_POST['subject'] ?? '');
        $message = trim($_POST['message'] ?? '');

        if (!$name || !$email || !$subject || !$message) {
            set_flash_message('danger', 'Please fill in all fields correctly.');
        } elseif (strlen($message) < 10) {
            set_flash_message('danger', 'Message is too short.');
        } else {
            $mail = new PHPMailer(true);

            try {
                // SMTP Configuration
                $mail->isSMTP();
                $mail->Host       = 'smtp.gmail.com';
                $mail->SMTPAuth   = true;
                $mail->Username   = $_ENV['EMAIL_USERNAME'] ?? 'mautimasea14@gmail.com'; // Set in .env or server
                $mail->Password   = $_ENV['EMAIL_PASSWORD'] ?? 'ykqf cpzz bizx wcix'; // Use App Password!
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port       = 587;

                // Common settings
                $admin_email = 'mautimasea14@gmail.com';
                $site_name   = 'Doyle Enterprise';

                // ——— Email to Admin (You) ———
                $mail->setFrom($admin_email, $site_name . ' Contact Form');
                $mail->addAddress($admin_email);
                $mail->addReplyTo($email, $name);

                $mail->isHTML(true);
                $mail->Subject = "New Contact: $subject";
                $mail->Body    = "
                    <h2>New Message from Contact Form</h2>
                    <table cellpadding='8' style='font-family: Arial, sans-serif;'>
                        <tr><td><strong>Name:</strong></td><td>" . htmlspecialchars($name) . "</td></tr>
                        <tr><td><strong>Email:</strong></td><td><a href='mailto:$email'>$email</a></td></tr>
                        <tr><td><strong>Subject:</strong></td><td>" . htmlspecialchars($subject) . "</td></tr>
                        <tr><td><strong>Message:</strong></td><td>" . nl2br(htmlspecialchars($message)) . "</td></tr>
                        <tr><td><strong>Received:</strong></td><td>" . date('d M Y \a\t H:i') . " EAT</td></tr>
                        <tr><td><strong>IP Address:</strong></td><td>{$_SERVER['REMOTE_ADDR']}</td></tr>
                    </table>
                    <hr><small>Sent via Doyle Enterprise website</small>
                ";
                $mail->AltBody = strip_tags($mail->Body);
                $mail->send();

                // ——— Auto-Reply to User ———
                $mail->clearAddresses();
                $mail->clearReplyTos();
                $mail->setFrom($admin_email, $site_name);
                $mail->addAddress($email, $name);
                $mail->addReplyTo($admin_email, $site_name);

                $mail->Subject = "Thank You for Contacting Doyle Enterprise";
                $mail->Body    = "
                    <div style='font-family: Arial, sans-serif; max-width: 600px; margin: auto; padding: 20px; border: 1px solid #eee;'>
                        <h2 style='color: #2c3e50;'>Hi $name,</h2>
                        <p>Thank you for reaching out to <strong>Doyle Enterprise</strong>!</p>
                        <p>We have received your message and will get back to you within <strong>24 hours</strong>.</p>
                        
                        <hr>
                        <h4>Your Message:</h4>
                        <blockquote style='background:#f9f9f9; padding:15px; border-left:4px solid #3498db;'>
                            <strong>Subject:</strong> " . htmlspecialchars($subject) . "<br><br>
                            " . nl2br(htmlspecialchars($message)) . "
                        </blockquote>
                        
                        <p>Best regards,<br><strong>Doyle Enterprise Team</strong><br>
                        Nairobi, Kenya | +254 746 071 550 | <a href='mailto:mautimasea14@gmail.com'>mautimasea14@gmail.com</a></p>
                        
                        <hr>
                        <small style='color:#7f8c8d;'>This is an automated response. Please do not reply directly to this email.</small>
                    </div>
                ";
                $mail->AltBody = "Hi $name,\n\nThank you for contacting Doyle Enterprise! We've received your message and will respond within 24 hours.\n\nBest regards,\nDoyle Enterprise Team";
                $mail->send();

                set_flash_message('success', 'Thank you! Your message has been sent successfully. Check your email for confirmation.');

            } catch (Exception $e) {
                error_log("PHPMailer Error: " . $e->getMessage());
                set_flash_message('danger', 'Sorry, something went wrong. Please try again or contact us via WhatsApp.');
            }
        }
    }
    header("Location: contact.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 - Doyle Enterprise</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f5f7fa; }
        .contact-info { padding: 60px 0; }
        .contact-form {
            background: white;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        .btn-primary { background-color: #2c3e50; border: none; }
        .btn-primary:hover { background-color: #1a2530; }
    </style>
</head>
<body>
    <?php include_once 'header.php'; ?>

    <section class="bg-primary text-white py-5">
        <div class="container text-center">
            <h1>Contact Us</h1>
            <p class="lead">We’re here to help. Reach out anytime!</p>
        </div>
    </section>

    <section class="contact-info bg-light">
        <div class="container">
            <div class="row g-5 align-items-center">
                <div class="col-lg-5">
                    <h3 class="mb-4">Get in Touch</h3>
                    <ul class="list-unstyled">
                        <li class="mb-3"><i class="fas fa-envelope text-primary me-3"></i> <a href="mailto:mautimasea14@gmail.com">mautimasea14@gmail.com</a></li>
                        <li class="mb-3"><i class="fas fa-phone text-success me-3"></i> <a href="tel:+254746071550">0746 071 550</a></li>
                        <li class="mb-3"><i class="fas fa-map-marker-alt text-danger me-3"></i> Nairobi, Kenya</li>
                        <li class="mb-3"><i class="fas fa-clock text-info me-3"></i> Mon–Sat, 8 AM – 6 PM EAT</li>
                    </ul>
                    <div class="mt-4">
                        <a href="https://wa.me/254746071550" class="btn btn-success btn-lg me-2" target="_blank">
                            <i class="fab fa-whatsapp"></i> Chat on WhatsApp
                        </a>
                    </div>
                </div>

                <div class="col-lg-7">
                    <div class="contact-form">
                        <h3>Send us a Message</h3>
                        <?php display_flash_message(); ?>
                        <form method="post" novalidate>
                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                            <div class="mb-3">
                                <label class="form-label">Full Name</label>
                                <input type="text" class="form-control" name="name" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email Address</label>
                                <input type="email" class="form-control" name="email" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Subject</label>
                                <input type="text" class="form-control" name="subject" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Message</label>
                                <textarea class="form-control" name="message" rows="6" required minlength="10"></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary w-100 py-3 fw-bold">Send Message</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="py-5 bg-white">
        <div class="container">
            <div class="ratio ratio-16x9 rounded shadow">
                <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3988.817!2d36.8219!3d-1.2921!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x182f10d5e3c2b3a5%3A0x8f0c4e7b8d9e2f1a!2sNairobi%2C%20Kenya!5e0!3m2!1sen!2ske!4v1698000000000" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
            </div>
        </div>
    </section>

    <?php include_once 'footer.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php ob_end_flush(); ?>