<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Get system settings
$system_settings = [
    'site_email' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'site_email'")->fetchColumn() ?: 'info@jvoverseas.com',
    'contact_email' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'contact_email'")->fetchColumn() ?: 'info@jvoverseas.com',
    'contact_phone' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'contact_phone'")->fetchColumn() ?: '+256 788 289 235',
    'contact_address' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'contact_address'")->fetchColumn() ?: 'Kampala, Uganda',
];

// Handle contact form submission
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message'])) {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    
    // Validate form data
    if (empty($name) || empty($email) || empty($subject) || empty($message)) {
        $error = "All fields are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();
            
            // Save contact message to database
            $stmt = $pdo->prepare("INSERT INTO contact_messages (
                name, email, subject, message, ip_address, user_agent, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, NOW())");
            
            $stmt->execute([
                $name, $email, $subject, $message,
                $_SERVER['REMOTE_ADDR'],
                $_SERVER['HTTP_USER_AGENT']
            ]);
            
            $message_id = $pdo->lastInsertId();
            
            // Create notification for admins
            $admin_users = $pdo->query("SELECT id FROM users WHERE user_type = 'admin' AND is_active = 1")->fetchAll();
            foreach ($admin_users as $admin) {
                $pdo->prepare("INSERT INTO notifications (
                    user_id, title, message, is_read, notification_type, related_id, related_type, created_at
                ) VALUES (?, ?, ?, 0, 'system', ?, 'contact', NOW())")->execute([
                    $admin['id'],
                    "New Contact Message",
                    "A new message has been received from {$name} ({$email}): {$subject}",
                    $message_id
                ]);
            }
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (NULL, 'contact_message', 'Contact message from {$name} ({$email}): {$subject}', NOW())")->execute();
            
            // Commit transaction
            $pdo->commit();
            
            // Set success message and clear form data
            $success = "Thank you for your message! We'll get back to you within 24 hours.";
            $_POST = array();
            
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to send your message. Please try again.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Contact Us - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .contact-info-item {
            transition: all 0.3s;
        }
        .contact-info-item:hover {
            transform: translateY(-10px);
        }
        .contact-form .form-control {
            height: 50px;
            border-radius: 0;
            border-width: 0 0 1px 0;
            border-color: #ddd;
        }
        .contact-form textarea.form-control {
            height: 120px;
        }
        .contact-form .form-control:focus {
            box-shadow: none;
            border-color: #3FB7FE;
        }
        .map-container {
            height: 400px;
            background: #eee;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>
<body>

<?php include 'navbar.php'; ?>

<!-- Header Start -->
<div class="jumbotron jumbotron-fluid page-header position-relative overlay-bottom" style="margin-bottom: 90px;">
    <div class="container text-center py-5">
        <h1 class="text-white display-1">Contact Us</h1>
        <div class="d-inline-flex text-white mb-5">
            <p class="m-0 text-uppercase"><a class="text-white" href="index.php">Home</a></p>
            <i class="fa fa-angle-double-right pt-1 px-3"></i>
            <p class="m-0 text-uppercase">Contact</p>
        </div>
        <div class="mx-auto mb-5" style="width: 100%; max-width: 600px;">
            <div class="input-group">
                <div class="input-group-prepend">
                    <button class="btn btn-secondary px-4 px-lg-5" type="button">Search</button>
                </div>
                <input type="text" class="form-control form-control-lg" placeholder="Search here">
            </div>
        </div>
    </div>
</div>
<!-- Header End -->

<!-- Contact Info Start -->
<div class="container-fluid py-5">
    <div class="container py-5">
        <div class="row">
            <div class="col-lg-3 col-md-6 mb-4">
                <div class="bg-primary text-center contact-info-item p-4">
                    <i class="fa fa-2x fa-phone-alt text-white mb-3"></i>
                    <h4 class="text-white">Call Today</h4>
                    <p class="text-white mb-0">
                        <a class="text-white" href="tel:<?= htmlspecialchars(str_replace(' ', '', $system_settings['contact_phone'])) ?>">
                            <?= htmlspecialchars($system_settings['contact_phone']) ?>
                        </a>
                    </p>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-4">
                <div class="bg-secondary text-center contact-info-item p-4">
                    <i class="fa fa-2x fa-envelope-open text-white mb-3"></i>
                    <h4 class="text-white">Email Us</h4>
                    <p class="text-white mb-0">
                        <a class="text-white" href="mailto:<?= htmlspecialchars($system_settings['contact_email']) ?>">
                            <?= htmlspecialchars($system_settings['contact_email']) ?>
                        </a>
                    </p>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-4">
                <div class="bg-primary text-center contact-info-item p-4">
                    <i class="fa fa-2x fa-map-marker-alt text-white mb-3"></i>
                    <h4 class="text-white">Visit Us</h4>
                    <p class="text-white mb-0"><?= htmlspecialchars($system_settings['contact_address']) ?></p>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-4">
                <div class="bg-secondary text-center contact-info-item p-4">
                    <i class="fa fa-2x fa-clock text-white mb-3"></i>
                    <h4 class="text-white">Working Hours</h4>
                    <p class="text-white mb-0">Mon - Fri: 9:00 AM - 5:00 PM</p>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Contact Info End -->

<!-- Contact Start -->
<div class="container-fluid py-5">
    <div class="container py-5">
        <div class="row">
            <div class="col-lg-7 mb-5 mb-lg-0">
                <div class="section-title position-relative mb-4">
                    <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Need Help?</h6>
                    <h1 class="display-4">Send Us a Message</h1>
                </div>
                <p class="mb-4">Have questions about studying abroad? Fill out the form below and our education experts will get back to you within 24 hours.</p>
                
                <?php if ($error): ?>
                <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
                <?php else: ?>
                <form class="contact-form" method="POST">
                    <div class="row">
                        <div class="col-12">
                            <div class="form-group">
                                <input class="form-control" name="name" placeholder="Your Name *" 
                                       value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" type="text" required>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-group">
                                <input class="form-control" name="email" placeholder="Your Email *" 
                                       value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" type="email" required>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-group">
                                <input class="form-control" name="subject" placeholder="Subject *" 
                                       value="<?= htmlspecialchars($_POST['subject'] ?? '') ?>" type="text" required>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-group">
                                <textarea class="form-control" rows="5" name="message" placeholder="Message *" required><?= htmlspecialchars($_POST['message'] ?? '') ?></textarea>
                            </div>
                        </div>
                    </div>
                    <div>
                        <button class="btn btn-primary py-3 px-5" type="submit" name="send_message">Send Message</button>
                    </div>
                </form>
                <?php endif; ?>
            </div>
            <div class="col-lg-5">
                <div class="section-title position-relative mb-4">
                    <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Find Us</h6>
                    <h1 class="display-4">Our Location</h1>
                </div>
                <div class="map-container">
                    <!-- Replace with actual map embed -->
                    <div class="text-center">
                        <i class="fa fa-map-marker-alt fa-3x text-primary mb-3"></i>
                        <h5>Our Office Location</h5>
                        <p><?= htmlspecialchars($system_settings['contact_address']) ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Contact End -->

<!-- Footer Start -->
<div class="container-fluid position-relative overlay-top bg-dark text-white-50 py-5" style="margin-top: 90px;">
    <div class="container mt-5 pt-5">
        <div class="row">
            <div class="col-md-6 mb-5">
                <a href="index.php" class="navbar-brand">
                    <img src="img/jhoverseas.jpg" alt="JV Overseas Logo" style="height: 50px;">
                </a>
                <p class="m-0">JV Overseas Education Uganda is a leading educational consultancy helping students access higher education opportunities worldwide.</p>
            </div>
            <div class="col-md-6 mb-5">
                <h3 class="text-white mb-4">Quick Links</h3>
                <div class="d-flex flex-column justify-content-start">
                    <a class="text-white-50 mb-2" href="index.php"><i class="fa fa-angle-right mr-2"></i>Home</a>
                    <a class="text-white-50 mb-2" href="about.php"><i class="fa fa-angle-right mr-2"></i>About Us</a>
                    <a class="text-white-50 mb-2" href="services.php"><i class="fa fa-angle-right mr-2"></i>Services</a>
                    <a class="text-white-50 mb-2" href="universities.php"><i class="fa fa-angle-right mr-2"></i>Universities</a>
                    <a class="text-white-50 mb-2" href="apply.php"><i class="fa fa-angle-right mr-2"></i>Free Consultation</a>
                    <a class="text-white-50 mb-2" href="contact.php"><i class="fa fa-angle-right mr-2"></i>Contact Us</a>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 mb-5">
                <h3 class="text-white mb-4">Get In Touch</h3>
                <p class="m-0"><i class="fa fa-map-marker-alt mr-2"></i>Kampala, Uganda</p>
                <p class="m-0"><i class="fa fa-phone-alt mr-2"></i><a href="tel:+256788289235" class="text-white-50">+256 788 289 235</a></p>
                <p class="m-0"><i class="fa fa-envelope mr-2"></i><a href="mailto:info@jvoverseas.com" class="text-white-50">info@jvoverseas.com</a></p>
                <div class="d-flex flex-column justify-content-start">
                    <div class="d-flex align-items-center mt-2">
                        <a class="text-white-50 mr-2" href="#"><i class="fab fa-twitter"></i></a>
                        <a class="text-white-50 mr-2" href="#"><i class="fab fa-facebook-f"></i></a>
                        <a class="text-white-50 mr-2" href="#"><i class="fab fa-linkedin-in"></i></a>
                        <a class="text-white-50 mr-2" href="#"><i class="fab fa-instagram"></i></a>
                    </div>
                </div>
            </div>
            <div class="col-md-6 mb-5">
                <h3 class="text-white mb-4">Newsletter</h3>
                <p>Stay updated with our latest news and education opportunities.</p>
                <form action="newsletter-subscribe.php" method="POST">
                    <div class="form-inline">
                        <div class="input-group">
                            <input type="email" class="form-control" name="email" placeholder="Your Email" required>
                            <div class="input-group-append">
                                <button class="btn btn-primary" type="submit">Subscribe</button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- Footer End -->

<!-- Back to Top -->
<a href="#" class="btn btn-lg btn-primary rounded-0 btn-lg-square back-to-top"><i class="fa fa-angle-double-up"></i></a>

<!-- JavaScript Libraries -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script src="lib/easing/easing.min.js"></script>
<script src="lib/waypoints/waypoints.min.js"></script>
<script src="lib/counterup/counterup.min.js"></script>
<script src="lib/owlcarousel/owl.carousel.min.js"></script>
<script src="mail/jqBootstrapValidation.min.js"></script>
<script src="mail/contact.js"></script>
<script src="js/main.js"></script>

<script>
// Set current year in footer
document.getElementById('year')?.textContent = new Date().getFullYear();
</script>