<?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 countries for dropdown
$countries = $pdo->query("SELECT id, name FROM countries ORDER BY name")->fetchAll();

// Get programs for dropdown
$programs = $pdo->query("SELECT p.id, p.name, u.name as university_name 
                        FROM programs p 
                        JOIN universities u ON p.university_id = u.id 
                        ORDER BY u.name, p.name")->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_consultation'])) {
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $country_id = $_POST['country_id'] ?? null;
    $preferred_program_id = $_POST['preferred_program_id'] ?? null;
    $current_education = $_POST['current_education'] ?? '';
    $academic_score = $_POST['academic_score'] ?? '';
    $english_score = $_POST['english_score'] ?? '';
    $intake_month = $_POST['intake_month'] ?? '';
    $budget = $_POST['budget'] ?? '';
    $message = $_POST['message'] ?? '';
    
    // Validate form data
    if (empty($first_name) || empty($last_name) || empty($email) || empty($phone) || !$country_id) {
        $error = "First name, last name, email, phone, and country are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } elseif (!is_numeric($academic_score) || $academic_score < 0 || $academic_score > 100) {
        $error = "Academic score must be a number between 0 and 100.";
    } elseif ($english_score && (!is_numeric($english_score) || $english_score < 0)) {
        $error = "English score must be a positive number.";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();
            
            // Create student profile (as prospective)
            $stmt = $pdo->prepare("INSERT INTO users (email, password_hash, user_type, is_active, created_at, updated_at) 
                                  VALUES (?, ?, 'student', 1, NOW(), NOW())");
            
            // Generate a temporary password (will be set by user later)
            $temp_password = bin2hex(random_bytes(8));
            $password_hash = password_hash($temp_password, PASSWORD_DEFAULT);
            
            $stmt->execute([$email, $password_hash]);
            $user_id = $pdo->lastInsertId();
            
            // Create student record
            $stmt = $pdo->prepare("INSERT INTO students (
                id, first_name, last_name, phone, country_id, current_education, 
                academic_score, english_score, preferred_program_id, intake_month, 
                budget, message, status, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'prospective', NOW(), NOW())");
            
            $stmt->execute([
                $user_id, $first_name, $last_name, $phone, $country_id, $current_education,
                $academic_score, $english_score, $preferred_program_id, $intake_month,
                $budget, $message
            ]);
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $user_id,
                "consultation_submitted",
                "Prospective student {$first_name} {$last_name} submitted consultation form"
            ]);
            
            // 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', ?, 'consultation', NOW())")->execute([
                    $admin['id'],
                    "New Consultation Request",
                    "A new consultation request has been submitted by {$first_name} {$last_name}",
                    $user_id
                ]);
            }
            
            // Commit transaction
            $pdo->commit();
            
            // Set success message and clear form data
            $success = "Thank you for your submission! Our education consultant will contact you within 24 hours.";
            $_POST = array();
            
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to submit your request. Please try again.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Free Consultation - 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>
        .consultation-form .form-control {
            height: 50px;
            border-radius: 0;
            border-width: 0 0 1px 0;
            border-color: #ddd;
        }
        .consultation-form textarea.form-control {
            height: 120px;
        }
        .consultation-form .form-control:focus {
            box-shadow: none;
            border-color: #3FB7FE;
        }
        .consultation-header {
            background: linear-gradient(rgba(63, 183, 254, 0.9), rgba(63, 183, 254, 0.9)), url(img/apply-bg.jpg) center center no-repeat;
            background-size: cover;
        }
        .process-step {
            transition: all 0.3s;
        }
        .process-step:hover {
            transform: translateY(-10px);
        }
    </style>
</head>
<body>

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

<!-- Header Start -->
<div class="jumbotron jumbotron-fluid consultation-header">
    <div class="container text-center py-5">
        <h1 class="text-white mb-4">Book a Free Consultation</h1>
        <p class="text-white mb-4">Our education experts will assess your profile and provide personalized guidance on courses, universities, scholarships, and visa processes.</p>
        <a href="#consultation-form" class="btn btn-secondary py-3 px-5 mt-3">Apply Now</a>
    </div>
</div>
<!-- Header End -->

<!-- Consultation Form Start -->
<div id="consultation-form" 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">Get Started</h6>
                    <h1 class="display-4">Free Consultation Form</h1>
                </div>
                <p class="mb-4">Fill out this form to schedule your free consultation session with one of our education experts. We'll contact you within 24 hours to discuss your study abroad options.</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="consultation-form" method="POST">
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <input class="form-control" name="first_name" placeholder="First Name *" 
                                       value="<?= htmlspecialchars($_POST['first_name'] ?? '') ?>" type="text" required>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <input class="form-control" name="last_name" placeholder="Last Name *" 
                                       value="<?= htmlspecialchars($_POST['last_name'] ?? '') ?>" type="text" required>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <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-sm-6">
                            <div class="form-group">
                                <input class="form-control" name="phone" placeholder="Your Phone *" 
                                       value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>" type="tel" required>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <select class="form-control" name="country_id" required>
                                    <option value="">Select Country *</option>
                                    <?php foreach ($countries as $c): ?>
                                    <option value="<?= $c['id'] ?>" <?= ($c['id'] == ($_POST['country_id'] ?? '')) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($c['name']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <select class="form-control" name="preferred_program_id">
                                    <option value="">Preferred Program (Optional)</option>
                                    <?php foreach ($programs as $p): ?>
                                    <option value="<?= $p['id'] ?>" <?= ($p['id'] == ($_POST['preferred_program_id'] ?? '')) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($p['university_name'] . ' - ' . $p['name']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <input class="form-control" name="current_education" placeholder="Current Education" 
                                       value="<?= htmlspecialchars($_POST['current_education'] ?? '') ?>" type="text">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <input class="form-control" name="academic_score" placeholder="Academic Score (%)" 
                                       value="<?= htmlspecialchars($_POST['academic_score'] ?? '') ?>" type="number" min="0" max="100">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <input class="form-control" name="english_score" placeholder="English Score (IELTS/TOEFL)" 
                                       value="<?= htmlspecialchars($_POST['english_score'] ?? '') ?>" type="number" step="0.5" min="0" max="9">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <select class="form-control" name="intake_month">
                                    <option value="">Preferred Intake Month</option>
                                    <option value="January" <?= ($_POST['intake_month'] ?? '') === 'January' ? 'selected' : '' ?>>January</option>
                                    <option value="February" <?= ($_POST['intake_month'] ?? '') === 'February' ? 'selected' : '' ?>>February</option>
                                    <option value="March" <?= ($_POST['intake_month'] ?? '') === 'March' ? 'selected' : '' ?>>March</option>
                                    <option value="April" <?= ($_POST['intake_month'] ?? '') === 'April' ? 'selected' : '' ?>>April</option>
                                    <option value="May" <?= ($_POST['intake_month'] ?? '') === 'May' ? 'selected' : '' ?>>May</option>
                                    <option value="June" <?= ($_POST['intake_month'] ?? '') === 'June' ? 'selected' : '' ?>>June</option>
                                    <option value="July" <?= ($_POST['intake_month'] ?? '') === 'July' ? 'selected' : '' ?>>July</option>
                                    <option value="August" <?= ($_POST['intake_month'] ?? '') === 'August' ? 'selected' : '' ?>>August</option>
                                    <option value="September" <?= ($_POST['intake_month'] ?? '') === 'September' ? 'selected' : '' ?>>September</option>
                                    <option value="October" <?= ($_POST['intake_month'] ?? '') === 'October' ? 'selected' : '' ?>>October</option>
                                    <option value="November" <?= ($_POST['intake_month'] ?? '') === 'November' ? 'selected' : '' ?>>November</option>
                                    <option value="December" <?= ($_POST['intake_month'] ?? '') === 'December' ? 'selected' : '' ?>>December</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <input class="form-control" name="budget" placeholder="Estimated Budget ($)" 
                                       value="<?= htmlspecialchars($_POST['budget'] ?? '') ?>" type="number" min="0">
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-group">
                                <textarea class="form-control" rows="5" name="message" placeholder="Additional Information or Questions"><?= htmlspecialchars($_POST['message'] ?? '') ?></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <button class="btn btn-primary py-3 px-5" type="submit" name="submit_consultation">Submit Request</button>
                    </div>
                </form>
                <?php endif; ?>
            </div>
            <div class="col-lg-5">
                <!-- How It Works Section -->
                <div class="section-title position-relative mb-4">
                    <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Our Process</h6>
                    <h1 class="display-4">How It Works</h1>
                </div>
                <p class="mb-4">Our consultation process is designed to help you make informed decisions about your international education journey.</p>
                
                <div class="row">
                    <div class="col-12 process-step mb-4">
                        <div class="d-inline-flex align-items-center justify-content-center bg-primary rounded-circle mb-4" style="width: 80px; height: 80px;">
                            <i class="fa fa-file-alt text-white" style="font-size: 30px;"></i>
                        </div>
                        <h5>1. Submit Your Profile</h5>
                        <p class="m-0">Fill out the consultation form with your academic background, preferences, and goals.</p>
                    </div>
                    <div class="col-12 process-step mb-4">
                        <div class="d-inline-flex align-items-center justify-content-center bg-primary rounded-circle mb-4" style="width: 80px; height: 80px;">
                            <i class="fa fa-phone-alt text-white" style="font-size: 30px;"></i>
                        </div>
                        <h5>2. Schedule a Call</h5>
                        <p class="m-0">Our consultant will contact you within 24 hours to schedule a detailed consultation call.</p>
                    </div>
                    <div class="col-12 process-step mb-4">
                        <div class="d-inline-flex align-items-center justify-content-center bg-primary rounded-circle mb-4" style="width: 80px; height: 80px;">
                            <i class="fa fa-graduation-cap text-white" style="font-size: 30px;"></i>
                        </div>
                        <h5>3. Get Personalized Advice</h5>
                        <p class="m-0">Receive expert guidance on university selection, application strategy, and funding options.</p>
                    </div>
                    <div class="col-12 process-step">
                        <div class="d-inline-flex align-items-center justify-content-center bg-primary rounded-circle mb-4" style="width: 80px; height: 80px;">
                            <i class="fa fa-check text-white" style="font-size: 30px;"></i>
                        </div>
                        <h5>4. Start Your Journey</h5>
                        <p class="m-0">Begin your application process with confidence, knowing you have expert support.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Consultation Form End -->

<?php include 'footer.php'; ?>
<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/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>
</body>
</html>