<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once '../includes/db.php';
require_once '../includes/auth.php';

check_role('profesor');

$user = get_logged_in_user();

// Get teacher
$stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
$stmt->execute([$user['id']]);
$teacher = $stmt->fetch();

if (!$teacher) {
    die('Teacher profile not found.');
}

$student_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$student_id) {
    header('Location: students.php');
    exit;
}

// Get student details
$stmt = $pdo->prepare("SELECT st.*, u.first_name, u.last_name, u.email, u.created_at, c.name as career_name FROM students st JOIN users u ON st.user_id = u.id LEFT JOIN careers c ON st.career_id = c.id WHERE st.id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch();

if (!$student) {
    header('Location: students.php');
    exit;
}

// Get student statistics
$stats = [];
$stmt = $pdo->prepare("SELECT COUNT(*) as total_applications FROM applications WHERE student_id = ?");
$stmt->execute([$student_id]);
$stats['total_applications'] = $stmt->fetch()['total_applications'];

$stmt = $pdo->prepare("SELECT COUNT(*) as accepted_applications FROM applications WHERE student_id = ? AND status = 'accepted'");
$stmt->execute([$student_id]);
$stats['accepted_applications'] = $stmt->fetch()['accepted_applications'];

$stmt = $pdo->prepare("SELECT COUNT(*) as pending_applications FROM applications WHERE student_id = ? AND status = 'pending'");
$stmt->execute([$student_id]);
$stats['pending_applications'] = $stmt->fetch()['pending_applications'];

$page_title = 'Student Profile: ' . htmlspecialchars($student['first_name'] . ' ' . $student['last_name']);

$content = '
<div class="row">
    <div class="col-md-4">
        <div class="card card-primary card-outline">
            <div class="card-body box-profile">
                <div class="text-center">
                    <img class="profile-user-img img-fluid img-circle" src="../assets/img/avatar.png" alt="Student Avatar">
                </div>
                <h3 class="profile-username text-center">' . htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) . '</h3>
                <p class="text-muted text-center">Student</p>
                <ul class="list-group list-group-unbordered mb-3">
                    <li class="list-group-item">
                        <b>Email</b> <a class="float-right">' . htmlspecialchars($student['email']) . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Career</b> <a class="float-right">' . htmlspecialchars($student['career_name'] ?: $student['major'] ?: 'Not specified') . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Joined</b> <a class="float-right">' . date('M d, Y', strtotime($student['created_at'])) . '</a>
                    </li>
                </ul>
                <div class="text-center">
                    <a href="mailto:' . htmlspecialchars($student['email']) . '" class="btn btn-primary btn-sm"><i class="fas fa-envelope"></i> Contact Student</a>
                    <a href="students.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> Back to Students</a>
                </div>
            </div>
        </div>

        <!-- Statistics Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Application Statistics</h3>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="small-box bg-info">
                            <div class="inner">
                                <h3>' . $stats['total_applications'] . '</h3>
                                <p>Total Apps</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="small-box bg-success">
                            <div class="inner">
                                <h3>' . $stats['accepted_applications'] . '</h3>
                                <p>Accepted</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row text-center mt-2">
                    <div class="col-12">
                        <div class="small-box bg-warning">
                            <div class="inner">
                                <h3>' . $stats['pending_applications'] . '</h3>
                                <p>Pending</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Student Information</h3>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-sm-6">
                        <strong><i class="fas fa-user mr-1"></i> Full Name</strong>
                        <p class="text-muted">' . htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) . '</p>
                        <hr>
                        <strong><i class="fas fa-envelope mr-1"></i> Email</strong>
                        <p class="text-muted">' . htmlspecialchars($student['email']) . '</p>
                        <hr>
                        <strong><i class="fas fa-graduation-cap mr-1"></i> Career/Major</strong>
                        <p class="text-muted">' . htmlspecialchars($student['career_name'] ?: $student['major'] ?: 'Not specified') . '</p>
                        <hr>
                        <strong><i class="fas fa-calendar mr-1"></i> Graduation Year</strong>
                        <p class="text-muted">' . htmlspecialchars($student['graduation_year'] ?: 'Not specified') . '</p>
                    </div>
                    <div class="col-sm-6">
                        <strong><i class="fas fa-calendar-alt mr-1"></i> Registration Date</strong>
                        <p class="text-muted">' . date('F d, Y', strtotime($student['created_at'])) . '</p>
                        <hr>
                        <strong><i class="fas fa-clock mr-1"></i> Account Age</strong>
                        <p class="text-muted">' . floor((time() - strtotime($student['created_at'])) / (60*60*24)) . ' days</p>
                        <hr>
                        <strong><i class="fas fa-chart-line mr-1"></i> Application Activity</strong>
                        <p class="text-muted">' . $stats['total_applications'] . ' total applications</p>
                    </div>
                </div>
                ' . ($student['resume'] ? '<hr>
                <strong><i class="fas fa-file-alt mr-1"></i> Resume</strong>
                <p class="text-muted">' . nl2br(htmlspecialchars($student['resume'])) . '</p>' : '') . '
                ' . ($student['skills'] ? '<hr>
                <strong><i class="fas fa-tools mr-1"></i> Skills</strong>
                <p class="text-muted">' . nl2br(htmlspecialchars($student['skills'])) . '</p>' : '') . '
            </div>
        </div>

        <!-- Recent Applications -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Recent Applications</h3>
                <div class="card-tools">
                    <span class="badge badge-info">' . $stats['total_applications'] . ' Total Applications</span>
                </div>
            </div>
            <div class="card-body">
                ' . ($stats['total_applications'] == 0 ? '<p class="text-muted">No applications yet.</p>' : '') . '';

$recent_apps = $pdo->prepare("SELECT a.*, j.title as job_title, c.company_name FROM applications a JOIN jobs j ON a.job_id = j.id JOIN companies c ON j.company_id = c.id WHERE a.student_id = ? ORDER BY a.applied_date DESC LIMIT 10");
$recent_apps->execute([$student_id]);
$applications = $recent_apps->fetchAll(PDO::FETCH_ASSOC);

foreach ($applications as $app) {
    $status_badge = match($app['status']) {
        'pending' => '<span class="badge bg-warning">Pending</span>',
        'reviewed' => '<span class="badge bg-info">Reviewed</span>',
        'accepted' => '<span class="badge bg-success">Accepted</span>',
        'rejected' => '<span class="badge bg-danger">Rejected</span>',
        default => '<span class="badge bg-secondary">' . ucfirst($app['status']) . '</span>'
    };

    $content .= '<div class="d-flex justify-content-between align-items-center border-bottom py-2">
                    <div>
                        <strong>' . htmlspecialchars($app['job_title']) . '</strong><br>
                        <small class="text-muted">' . htmlspecialchars($app['company_name']) . ' • Applied on ' . date('M d, Y H:i', strtotime($app['applied_date'])) . '</small>
                    </div>
                    <div class="text-right">
                        ' . $status_badge . '<br>
                        <small class="text-muted">' . htmlspecialchars($app['notes'] ?: 'No notes') . '</small>
                    </div>
                </div>';
}

$content .= '</div>
        </div>
    </div>
</div>';

include '../includes/layout.php';
?>