<?php
/**
 * JV Overseas Education - Student Dashboard
 * Single-file PHP with integrated HTML and backend logic
 * Matches design of original index.html
 */

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());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'student') {
    // Login form handling
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        
        if (!empty($email) && !empty($password)) {
            $stmt = $pdo->prepare("SELECT u.id, u.email, u.password_hash, u.user_type, u.is_active, 
                                  s.first_name, s.last_name, s.profile_photo 
                                  FROM users u 
                                  JOIN students s ON u.id = s.id 
                                  WHERE u.email = ?");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user && password_verify($password, $user['password_hash']) && $user['is_active']) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['user_type'] = $user['user_type'];
                $_SESSION['first_name'] = $user['first_name'];
                $_SESSION['last_name'] = $user['last_name'];
                $_SESSION['profile_photo'] = $user['profile_photo'] ?: 'img/profile-placeholder.jpg';
                
                // Update last login
                $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?")->execute([$user['id']]);
                
                header('Location: ' . $_SERVER['PHP_SELF']);
                exit;
            } else {
                $error = "Invalid email or password.";
            }
        } else {
            $error = "Please fill in all fields.";
        }
    }

    // Show login form
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Login - 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="css/style.css" rel="stylesheet">
        <style>
            .login-container {
                min-height: 100vh;
                display: flex;
                align-items: center;
                background: linear-gradient(rgba(0,0,0,0.7), rgba(0,0,0,0.7)), url('img/header-bg.jpg');
                background-size: cover;
            }
            .login-box {
                background: rgba(255,255,255,0.95);
                border-radius: 15px;
                padding: 40px;
                max-width: 450px;
                width: 100%;
                margin: 0 auto;
                box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            }
            .logo {
                text-align: center;
                margin-bottom: 30px;
            }
            .logo img {
                height: 60px;
            }
        </style>
    </head>
    <body>
        <div class="container-fluid login-container">
            <div class="container">
                <div class="login-box">
                    <div class="logo">
                        <img src="img/jhoverseas.jpg" alt="JV Overseas">
                    </div>
                    <h2 class="text-center text-primary mb-4">Student Login</h2>
                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                    <?php endif; ?>
                    <form method="POST">
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" name="email" class="form-control form-control-lg" required>
                        </div>
                        <div class="form-group">
                            <label>Password</label>
                            <input type="password" name="password" class="form-control form-control-lg" required>
                        </div>
                        <button type="submit" name="login" class="btn btn-primary btn-block btn-lg">Login</button>
                        <p class="text-center mt-3">
                            <small>Not registered? Contact your counselor.</small>
                        </p>
                    </form>
                </div>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Get student data
$stmt = $pdo->prepare("SELECT s.*, u.email, u.last_login, 
                      CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                      c.phone as counselor_phone
                      FROM students s 
                      LEFT JOIN counselors c ON s.assigned_counselor_id = c.id
                      JOIN users u ON s.id = u.id 
                      WHERE s.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    die("Student profile not found.");
}

// Get applications
$applications = $pdo->prepare("SELECT a.*, p.name as program_name, p.degree_level, 
                              u.name as university_name, u.logo as university_logo
                              FROM applications a
                              JOIN programs p ON a.program_id = p.id
                              JOIN universities u ON p.university_id = u.id
                              WHERE a.student_id = ?
                              ORDER BY a.created_at DESC");
$applications->execute([$_SESSION['user_id']]);
$applications = $applications->fetchAll();

// Get documents
$documents = $pdo->prepare("SELECT * FROM student_documents 
                           WHERE student_id = ? 
                           ORDER BY created_at DESC LIMIT 5");
$documents->execute([$_SESSION['user_id']]);
$documents = $documents->fetchAll();

// Get upcoming appointments
$appointments = $pdo->prepare("SELECT a.*, c.first_name as counselor_first, c.last_name as counselor_last
                              FROM appointments a
                              JOIN counselors c ON a.counselor_id = c.id
                              WHERE a.student_id = ? AND a.scheduled_time > NOW()
                              ORDER BY a.scheduled_time ASC LIMIT 3");
$appointments->execute([$_SESSION['user_id']]);
$appointments = $appointments->fetchAll();

// Get unread notifications
$notifications = $pdo->prepare("SELECT COUNT(*) as count FROM notifications 
                               WHERE user_id = ? AND is_read = 0");
$notifications->execute([$_SESSION['user_id']]);
$notification_count = $notifications->fetchColumn();

// Get visa applications
$visa_applications = $pdo->prepare("SELECT va.*, co.name as country_name
                                   FROM visa_applications va
                                   JOIN countries co ON va.country_id = co.id
                                   WHERE va.student_id = ?
                                   ORDER BY va.created_at DESC LIMIT 1");
$visa_applications->execute([$_SESSION['user_id']]);
$visa_applications = $visa_applications->fetchAll();

// Calculate application progress
$total_apps = count($applications);
$accepted_apps = count(array_filter($applications, function($a) { return $a['application_status'] === 'accepted'; }));
$progress = $total_apps > 0 ? min(100, ($accepted_apps / $total_apps) * 100) : 0;

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: student-dashboard.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Student Dashboard - 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>
        .welcome-card {
            background: linear-gradient(135deg, #3fb7fe, #0056b3);
            color: white;
        }
        .card-icon {
            font-size: 2rem;
            color: #3fb7fe;
        }
        .task-card {
            border-left: 4px solid #3fb7fe;
        }
        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            font-size: 0.7rem;
        }
        .university-card img {
            height: 100px;
            object-fit: contain;
            background: white;
            padding: 10px;
            border-radius: 8px;
        }
        .progress-container {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
        }
        .progress-label {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>

<!-- Navbar -->
<nav class="navbar navbar-expand-lg bg-white navbar-light py-3 px-lg-5">
    <a href="../index.html" class="navbar-brand ml-lg-3">
        <img src="img/jhoverseas.jpg" alt="JV Overseas" height="50">
    </a>
    <div class="collapse navbar-collapse justify-content-end px-lg-3">
        <div class="navbar-nav">
            <a href="student-dashboard.php" class="nav-item nav-link active">Dashboard</a>
            <a href="student-profile.php" class="nav-item nav-link">Profile</a>
            <a href="student-messages.php" class="nav-item nav-link position-relative">
                Messages
                <span class="badge notification-badge bg-primary"><?= $notification_count ?></span>
            </a>
            <a href="student-dashboard.php?logout=1" class="nav-item nav-link">Logout</a>
        </div>
    </div>
</nav>

<!-- Welcome Section -->
<div class="container-fluid bg-light py-5">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-3 mb-4 mb-lg-0 text-center">
                <img src="<?= htmlspecialchars($student['profile_photo'] ?: 'img/profile-placeholder.jpg') ?>" 
                     class="rounded-circle" width="120" height="120" alt="Profile">
            </div>
            <div class="col-lg-9">
                <h1 class="mb-2">Welcome, <?= htmlspecialchars($student['first_name']) ?> <?= htmlspecialchars($student['last_name']) ?></h1>
                <p class="lead mb-1">Target: <?= implode(', ', json_decode($student['preferred_countries'] ?? '[]', true) ?: ['Not specified']) ?></p>
                <?php if ($student['counselor_name']): ?>
                <p><strong>Assigned Counselor:</strong> <?= htmlspecialchars($student['counselor_name']) ?> 
                   <a href="mailto:<?= htmlspecialchars($student['email']) ?>" class="btn btn-sm btn-primary ml-2">Message</a></p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Dashboard Content -->
<div class="container py-5">

    <!-- Application Status -->
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Application Progress</h6>
        <h1 class="display-5">Your Application Journey</h1>
    </div>
    <div class="card mb-5">
        <div class="card-body">
            <div class="progress-container">
                <div class="progress-label">
                    <span>Overall Progress</span>
                    <span><?= round($progress) ?>%</span>
                </div>
                <div class="progress" style="height: 20px;">
                    <div class="progress-bar bg-success" role="progressbar" 
                         style="width: <?= $progress ?>%;" 
                         aria-valuenow="<?= $progress ?>" aria-valuemin="0" aria-valuemax="100">
                        <?= round($progress) ?>%
                    </div>
                </div>
            </div>
            <div class="row mt-4">
                <div class="col-md-4 text-center">
                    <h5 class="text-primary"><?= count($applications) ?></h5>
                    <p>Total Applications</p>
                </div>
                <div class="col-md-4 text-center">
                    <h5 class="text-success"><?= $accepted_apps ?></h5>
                    <p>Admitted</p>
                </div>
                <div class="col-md-4 text-center">
                    <h5 class="text-warning"><?= count($appointments) ?></h5>
                    <p>Upcoming Sessions</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Upcoming Tasks -->
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Tasks & Deadlines</h6>
        <h1 class="display-5">Your To-Do List</h1>
    </div>
    <div class="row mb-5">
        <?php foreach ($documents as $doc): if ($doc['status'] === 'pending' && count($documents) < 3): ?>
        <div class="col-md-6 mb-4">
            <div class="card task-card">
                <div class="card-body">
                    <h5><i class="fas fa-file-alt card-icon mr-2"></i> Upload <?= ucfirst($doc['document_type']) ?></h5>
                    <p class="text-muted">Your document is pending approval</p>
                    <a href="#" class="btn btn-sm btn-outline-primary">Upload Now</a>
                </div>
            </div>
        </div>
        <?php endif; endforeach; ?>
        <?php foreach ($appointments as $appt): if (count($documents) < 3): ?>
        <div class="col-md-6 mb-4">
            <div class="card task-card">
                <div class="card-body">
                    <h5><i class="fas fa-calendar card-icon mr-2"></i> Counseling Session</h5>
                    <p class="text-muted">With <?= htmlspecialchars($appt['counselor_first']) ?> on 
                       <strong><?= date('M j, Y H:i', strtotime($appt['scheduled_time'])) ?></strong></p>
                    <a href="<?= $appt['google_meet_link'] ?>" class="btn btn-sm btn-outline-primary">Join Meeting</a>
                </div>
            </div>
        </div>
        <?php endif; endforeach; ?>
    </div>

    <!-- University Choices -->
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Your Applications</h6>
        <h1 class="display-5">University Applications</h1>
    </div>
    <div class="row mb-5">
        <?php foreach ($applications as $app): ?>
        <div class="col-md-4 mb-4">
            <div class="card h-100">
                <div class="p-3 text-center bg-light">
                    <img src="<?= htmlspecialchars($app['university_logo'] ?: 'img/university-placeholder.png') ?>" 
                         alt="<?= htmlspecialchars($app['university_name']) ?>" class="university-card img">
                </div>
                <div class="card-body">
                    <h5 class="card-title"><?= htmlspecialchars($app['university_name']) ?></h5>
                    <p class="card-text"><small><?= htmlspecialchars($app['degree_level'] . ' in ' . $app['program_name']) ?></small></p>
                    <span class="badge badge-<?= 
                        ($app['application_status'] === 'accepted') ? 'success' :
                        (($app['application_status'] === 'submitted') ? 'info' :
                        (($app['application_status'] === 'rejected') ? 'danger' : 'warning'))
                    ?>"><?= ucfirst($app['application_status']) ?></span>
                    <a href="#" class="btn btn-block btn-primary mt-3">View Details</a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Documents, Visa & Quick Links -->
    <div class="row">
        <div class="col-lg-4 mb-4">
            <div class="section-title position-relative mb-4">
                <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Documents</h6>
                <h1 class="display-6">Upload & Track</h1>
            </div>
            <ul class="list-group">
                <?php foreach ($documents as $doc): ?>
                <li class="list-group-item d-flex justify-content-between align-items-center">
                    <?= ucfirst($doc['document_type']) ?>
                    <span class="badge badge-<?= 
                        ($doc['status'] === 'approved') ? 'success' :
                        (($doc['status'] === 'uploaded') ? 'info' : 'warning')
                    ?>"><?= ucfirst($doc['status']) ?></span>
                </li>
                <?php endforeach; ?>
            </ul>
            <a href="#" class="btn btn-link mt-2">View All Documents</a>
        </div>

        <div class="col-lg-4 mb-4">
            <div class="section-title position-relative mb-4">
                <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Visa Status</h6>
                <h1 class="display-6">Visa Applications</h1>
            </div>
            <?php if (count($visa_applications) > 0): ?>
                <?php foreach ($visa_applications as $visa): ?>
                <div class="card">
                    <div class="card-body">
                        <p><strong>Country:</strong> <?= htmlspecialchars($visa['country_name']) ?></p>
                        <p><strong>Status:</strong> <span class="badge badge-<?= 
                            ($visa['status'] === 'approved') ? 'success' :
                            (($visa['status'] === 'application_submitted') ? 'info' :
                            (($visa['status'] === 'under_review') ? 'warning' : 'secondary'))
                        ?>"><?= ucfirst(str_replace('_', ' ', $visa['status'])) ?></span></p>
                        <p><strong>Expected:</strong> <?= $visa['expected_decision_date'] ?></p>
                        <a href="#" class="btn btn-primary btn-sm">View Checklist</a>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="card">
                    <div class="card-body text-center">
                        <p>No visa applications yet.</p>
                        <a href="#" class="btn btn-primary btn-sm">Start Visa Process</a>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <div class="col-lg-4 mb-4">
            <div class="section-title position-relative mb-4">
                <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Quick Actions</h6>
                <h1 class="display-6">Get Started</h1>
            </div>
            <div class="row">
                <div class="col-6 mb-3">
                    <a href="#" class="text-decoration-none">
                        <div class="text-center p-3 bg-white shadow-sm rounded">
                            <i class="fas fa-calendar-alt card-icon text-primary"></i>
                            <h6 class="small">Book Appointment</h6>
                        </div>
                    </a>
                </div>
                <div class="col-6 mb-3">
                    <a href="#" class="text-decoration-none">
                        <div class="text-center p-3 bg-white shadow-sm rounded">
                            <i class="fas fa-comments card-icon text-primary"></i>
                            <h6 class="small">Chat Now</h6>
                        </div>
                    </a>
                </div>
                <div class="col-6 mb-3">
                    <a href="#" class="text-decoration-none">
                        <div class="text-center p-3 bg-white shadow-sm rounded">
                            <i class="fas fa-money-bill-wave card-icon text-primary"></i>
                            <h6 class="small">Payments</h6>
                        </div>
                    </a>
                </div>
                <div class="col-6 mb-3">
                    <a href="#" class="text-decoration-none">
                        <div class="text-center p-3 bg-white shadow-sm rounded">
                            <i class="fas fa-question-circle card-icon text-primary"></i>
                            <h6 class="small">Help Center</h6>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

</div>

<!-- Footer -->
<div class="container-fluid bg-dark text-white-50 py-4">
    <div class="container text-center">
        <p class="mb-0">© <span id="year"></span> JV Overseas Education Uganda. All Rights Reserved.</p>
    </div>
</div>

<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>
    document.getElementById('year').textContent = new Date().getFullYear();
</script>
</body>
</html>