<?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 program ID from URL
$program_id = $_GET['id'] ?? null;

if (!$program_id) {
    die("Program ID is required.");
}

// Get program data
$stmt = $pdo->prepare("SELECT p.*, u.name as university_name, u.logo as university_logo, 
                      u.country_id, u.city as university_city, c.name as country_name,
                      CASE 
                          WHEN p.degree_level = 'bachelors' THEN 'Bachelor\'s'
                          WHEN p.degree_level = 'masters' THEN 'Master\'s'
                          ELSE UPPER(LEFT(p.degree_level, 1)) || LOWER(SUBSTRING(p.degree_level, 2))
                      END as degree_level_display
                      FROM programs p
                      JOIN universities u ON p.university_id = u.id
                      JOIN countries c ON u.country_id = c.id
                      WHERE p.id = ?");
$stmt->execute([$program_id]);
$program = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$program) {
    die("Program not found.");
}

// Get application deadlines
$intake_months = json_decode($program['intake_months'] ?? '[]', true);

// Get admission requirements
$academic_requirements = json_decode($program['academic_requirements'] ?? '[]', true);
$language_requirements = json_decode($program['language_requirements'] ?? '[]', true);

// Get stats for this program
$stats = [
    'total_applications' => $pdo->query("SELECT COUNT(*) FROM applications WHERE program_id = {$program_id}")->fetchColumn(),
    'accepted_applications' => $pdo->query("SELECT COUNT(*) FROM applications WHERE program_id = {$program_id} AND application_status = 'accepted'")->fetchColumn(),
    'acceptance_rate' => 0,
];

if ($stats['total_applications'] > 0) {
    $stats['acceptance_rate'] = round(($stats['accepted_applications'] / $stats['total_applications']) * 100, 1);
}

// Get testimonials for this program
$testimonials = $pdo->prepare("SELECT t.*, s.first_name, s.last_name
                              FROM testimonials t
                              JOIN students s ON t.student_id = s.id
                              JOIN applications a ON t.application_id = a.id
                              WHERE a.program_id = ? AND t.is_approved = 1 AND t.is_featured = 1
                              ORDER BY t.created_at DESC
                              LIMIT 3");
$testimonials->execute([$program_id]);
$testimonials = $testimonials->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_consultation'])) {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $message = trim($_POST['message'] ?? '');
    
    // Validate form data
    if (empty($name) || empty($email)) {
        $error = "Name and email are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } else {
        try {
            // Save consultation request to database
            $stmt = $pdo->prepare("INSERT INTO contact_messages (
                name, email, subject, message, phone, ip_address, user_agent, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
            
            $stmt->execute([
                $name, $email, "Consultation for {$program['name']}", $message, $phone,
                $_SERVER['REMOTE_ADDR'],
                $_SERVER['HTTP_USER_AGENT']
            ]);
            
            // 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 Consultation Request",
                    "A new consultation has been requested for {$program['name']} by {$name} ({$email})",
                    $pdo->lastInsertId()
                ]);
            }
            
            $success = "Thank you for your interest! We'll contact you within 24 hours to schedule your consultation.";
            $_POST = array(); // Clear form data
            
        } catch (Exception $e) {
            $error = "Failed to submit your request. Please try again.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?= htmlspecialchars($program['name']) ?> - <?= htmlspecialchars($program['university_name']) ?> - 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>
        .program-header {
            background: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('<?= htmlspecialchars($program['university_logo'] ?: 'img/university-placeholder.png') ?>');
            background-size: cover;
            background-position: center;
            color: white;
            padding: 80px 0;
            margin-bottom: 30px;
        }
        .university-logo-large {
            width: 120px;
            height: 120px;
            object-fit: contain;
            background: white;
            padding: 10px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .degree-badge {
            font-size: 1.1em;
            padding: 8px 15px;
            border-radius: 30px;
            font-weight: 600;
        }
        .degree-bachelors {
            background: #d1ecf1;
            color: #0c5460;
        }
        .degree-masters {
            background: #d4edda;
            color: #155724;
        }
        .degree-phd {
            background: #f8d7da;
            color: #721c24;
        }
        .degree-diploma {
            background: #fff3cd;
            color: #856404;
        }
        .degree-certificate {
            background: #d6d8d9;
            color: #383d41;
        }
        .stat-item {
            border-left: 4px solid #3fb7fe;
            padding-left: 20px;
            margin-bottom: 15px;
        }
        .requirement-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .requirement-item:last-child {
            border-bottom: none;
        }
        .testimonial-card {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            background: #f8f9fa;
        }
        .rating {
            color: #ffc107;
            margin-bottom: 10px;
        }
        .consultation-form {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 10px;
        }
        .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;
        }
    </style>
</head>
<body>

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

<!-- Program Header -->
<div class="program-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-8">
                <h1 class="display-4"><?= htmlspecialchars($program['name']) ?></h1>
                <div class="d-flex align-items-center mb-3">
                    <span class="degree-badge degree-<?= $program['degree_level'] ?>">
                        <?= htmlspecialchars($program['degree_level_display']) ?>
                    </span>
                    <span class="ml-3">Duration: <?= $program['duration_months'] ?> months</span>
                </div>
                <div class="d-flex align-items-center">
                    <div class="mr-3">
                        <i class="fa fa-map-marker-alt text-white mr-2"></i>
                        <span><?= htmlspecialchars($program['university_city'] ?? $program['country_name']) ?></span>
                    </div>
                    <div>
                        <i class="fa fa-money-check text-white mr-2"></i>
                        <span>Tuition: $<?= number_format($program['tuition_fee'], 2) ?>/year</span>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 text-center">
                <img src="<?= htmlspecialchars($program['university_logo'] ?: 'img/university-placeholder.png') ?>" 
                     alt="<?= htmlspecialchars($program['university_name']) ?>" class="university-logo-large">
                <h5 class="mt-3 text-white"><?= htmlspecialchars($program['university_name']) ?></h5>
                <p class="text-white"><?= htmlspecialchars($program['country_name']) ?></p>
            </div>
        </div>
    </div>
</div>

<div class="container py-5">
    <div class="row">
        <div class="col-lg-8">
            <!-- Program Description -->
            <div class="section-card mb-5">
                <div class="section-header">Program Overview</div>
                <div class="section-body">
                    <p><?= htmlspecialchars($program['program_description'] ?: 'No description available for this program.') ?></p>
                </div>
            </div>
            
            <!-- Key Information -->
            <div class="section-card mb-5">
                <div class="section-header">Key Information</div>
                <div class="section-body">
                    <div class="row">
                        <div class="col-md-6 mb-4">
                            <div class="stat-item">
                                <h6 class="text-primary">Tuition Fee</h6>
                                <h5>$<?= number_format($program['tuition_fee'], 2) ?>/year</h5>
                            </div>
                        </div>
                        <div class="col-md-6 mb-4">
                            <div class="stat-item">
                                <h6 class="text-primary">Program Duration</h6>
                                <h5><?= $program['duration_months'] ?> months</h5>
                            </div>
                        </div>
                        <div class="col-md-6 mb-4">
                            <div class="stat-item">
                                <h6 class="text-primary">Intake Periods</h6>
                                <h5><?= htmlspecialchars(implode(', ', $intake_months ?: ['Not specified'])) ?></h5>
                            </div>
                        </div>
                        <div class="col-md-6 mb-4">
                            <div class="stat-item">
                                <h6 class="text-primary">Application Deadline</h6>
                                <h5>Varies by intake</h5>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Admission Requirements -->
            <div class="section-card mb-5">
                <div class="section-header">Admission Requirements</div>
                <div class="section-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h5>Academic Requirements</h5>
                            <ul class="list-unstyled">
                                <?php if (empty($academic_requirements)): ?>
                                <li class="mb-2">• No specific requirements listed</li>
                                <?php else: ?>
                                <?php foreach ($academic_requirements as $requirement): ?>
                                <li class="mb-2">• <?= htmlspecialchars($requirement) ?></li>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </ul>
                        </div>
                        <div class="col-md-6">
                            <h5>Language Requirements</h5>
                            <ul class="list-unstyled">
                                <?php if (empty($language_requirements)): ?>
                                <li class="mb-2">• No specific requirements listed</li>
                                <?php else: ?>
                                <?php foreach ($language_requirements as $requirement): ?>
                                <li class="mb-2">• <?= htmlspecialchars($requirement) ?></li>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Curriculum -->
            <div class="section-card mb-5">
                <div class="section-header">Program Curriculum</div>
                <div class="section-body">
                    <p>The <?= htmlspecialchars($program['name']) ?> program at <?= htmlspecialchars($program['university_name']) ?> offers a comprehensive curriculum designed to provide students with the knowledge and skills needed for a successful career in this field.</p>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Core Courses</h6>
                            <ul>
                                <li>Introduction to <?= htmlspecialchars($program['name']) ?></li>
                                <li>Advanced <?= htmlspecialchars($program['name']) ?> Principles</li>
                                <li>Research Methods</li>
                                <li>Data Analysis and Interpretation</li>
                                <li>Professional Practice</li>
                            </ul>
                        </div>
                        <div class="col-md-6">
                            <h6>Elective Courses</h6>
                            <ul>
                                <li>Special Topics in <?= htmlspecialchars($program['name']) ?></li>
                                <li>Industry Internship</li>
                                <li>Capstone Project</li>
                                <li>Global Perspectives</li>
                                <li>Leadership and Management</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Student Testimonials -->
            <?php if (!empty($testimonials)): ?>
            <div class="section-card mb-5">
                <div class="section-header">Student Success Stories</div>
                <div class="section-body">
                    <?php foreach ($testimonials as $testimonial): ?>
                    <div class="testimonial-card">
                        <div class="rating">
                            <?php for ($i = 0; $i < 5; $i++): ?>
                                <i class="fas fa-star"></i>
                            <?php endfor; ?>
                        </div>
                        <p class="mb-3">"<?= htmlspecialchars($testimonial['content']) ?>"</p>
                        <div class="d-flex align-items-center">
                            <img src="img/profile-placeholder.jpg" alt="<?= htmlspecialchars($testimonial['first_name']) ?>" class="rounded-circle" style="width: 40px; height: 40px;">
                            <div class="ml-2">
                                <h6 class="mb-0"><?= htmlspecialchars($testimonial['first_name']) ?></h6>
                                <small class="text-muted">Student at <?= htmlspecialchars($program['university_name']) ?></small>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="col-lg-4">
            <!-- Application Stats -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Application Statistics</h5>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled">
                        <li class="mb-3"><i class="fas fa-file-alt mr-2"></i> 
                            <strong>Total Applications:</strong><br>
                            <?= $stats['total_applications'] ?>
                        </li>
                        <li class="mb-3"><i class="fas fa-check-circle mr-2"></i> 
                            <strong>Accepted Applications:</strong><br>
                            <?= $stats['accepted_applications'] ?>
                        </li>
                        <li class="mb-3"><i class="fas fa-percentage mr-2"></i> 
                            <strong>Acceptance Rate:</strong><br>
                            <?= $stats['acceptance_rate'] ?>%
                        </li>
                        <li class="mb-3"><i class="fas fa-award mr-2"></i> 
                            <strong>Average Scholarship:</strong><br>
                            $5,000 - $15,000
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- Quick Apply -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Ready to Apply?</h5>
                </div>
                <div class="card-body">
                    <p>Get personalized guidance on your application to <?= htmlspecialchars($program['university_name']) ?>.</p>
                    <a href="apply.php" class="btn btn-primary btn-block">Get Free Consultation</a>
                    <a href="contact.php" class="btn btn-outline-primary btn-block mt-2">Contact Us</a>
                </div>
            </div>
            
            <!-- Consultation Form -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Request Information</h5>
                </div>
                <div class="card-body">
                    <?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 method="POST">
                        <div class="form-group">
                            <input type="text" name="name" class="form-control" placeholder="Your Name *" required>
                        </div>
                        <div class="form-group">
                            <input type="email" name="email" class="form-control" placeholder="Your Email *" required>
                        </div>
                        <div class="form-group">
                            <input type="text" name="phone" class="form-control" placeholder="Your Phone">
                        </div>
                        <div class="form-group">
                            <textarea name="message" class="form-control" rows="3" placeholder="Your Questions"></textarea>
                        </div>
                        <button type="submit" name="request_consultation" class="btn btn-primary btn-block">Request Information</button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- University Info -->
            <div class="card">
                <div class="card-header">
                    <h5>About <?= htmlspecialchars($program['university_name']) ?></h5>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <img src="<?= htmlspecialchars($program['university_logo'] ?: 'img/university-placeholder.png') ?>" 
                             alt="<?= htmlspecialchars($program['university_name']) ?>" class="university-logo mr-3">
                        <div>
                            <h6><?= htmlspecialchars($program['university_name']) ?></h6>
                            <small class="text-muted"><?= htmlspecialchars($program['country_name']) ?></small>
                        </div>
                    </div>
                    <p class="mb-3">A world-renowned institution consistently ranked among the top universities globally.</p>
                    <a href="university-profile.php?id=<?= $program['university_id'] ?>" class="btn btn-outline-primary btn-block">View University Profile</a>
                </div>
            </div>
        </div>
    </div>
</div>

<?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/waypoints/waypoints.min.js"></script>
<script src="lib/counterup/counterup.min.js"></script>
<script src="lib/owlcarousel/owl.carousel.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>