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

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'counselor') {
    header('Location: counselor-login.php');
    exit;
}

// Get counselor data
try {
    $stmt = $pdo->prepare("SELECT c.*, u.email, u.last_login, u.is_active,
                          JSON_UNQUOTE(JSON_EXTRACT(c.specialization, '$')) as specialization_text
                          FROM counselors c 
                          JOIN users u ON c.id = u.id 
                          WHERE c.id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $counselor = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$counselor) {
        die("Counselor profile not found.");
    }
} catch(PDOException $e) {
    die("Error fetching counselor data: " . $e->getMessage());
}

// Get stats
$stats = [
    'my_students' => 0,
    'pending_applications' => 0,
    'pending_documents' => 0,
    'upcoming_appointments' => 0,
    'new_messages' => 0,
];

try {
    // My Students
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE assigned_counselor_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $stats['my_students'] = $stmt->fetchColumn();

    // Pending Applications
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM applications WHERE counselor_id = ? AND application_status IN ('submitted', 'under_review')");
    $stmt->execute([$_SESSION['user_id']]);
    $stats['pending_applications'] = $stmt->fetchColumn();

    // Pending Documents
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM student_documents sd JOIN students s ON sd.student_id = s.id WHERE s.assigned_counselor_id = ? AND sd.status = 'pending'");
    $stmt->execute([$_SESSION['user_id']]);
    $stats['pending_documents'] = $stmt->fetchColumn();

    // Upcoming Appointments
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM appointments WHERE counselor_id = ? AND scheduled_time > NOW()");
    $stmt->execute([$_SESSION['user_id']]);
    $stats['upcoming_appointments'] = $stmt->fetchColumn();

    // New Messages
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM messages WHERE receiver_id = ? AND is_read = 0");
    $stmt->execute([$_SESSION['user_id']]);
    $stats['new_messages'] = $stmt->fetchColumn();
} catch(PDOException $e) {
    // Log error but continue execution with default values
    error_log("Error fetching stats: " . $e->getMessage());
}

// Get recent activities
try {
    $stmt = $pdo->prepare("SELECT a.*, u.email, s.first_name, s.last_name 
                           FROM activities a
                           LEFT JOIN users u ON a.user_id = u.id
                           LEFT JOIN students s ON u.id = s.id
                           ORDER BY a.created_at DESC LIMIT 6");
    $stmt->execute();
    $activities = $stmt->fetchAll();
} catch(PDOException $e) {
    $activities = [];
    error_log("Error fetching activities: " . $e->getMessage());
}

// Get pending applications
try {
    $stmt = $pdo->prepare("SELECT a.id, a.application_status, a.submission_date,
                          s.first_name, s.last_name, p.name as program, u.name as university
                          FROM applications a
                          JOIN students s ON a.student_id = s.id
                          JOIN programs p ON a.program_id = p.id
                          JOIN universities u ON p.university_id = u.id
                          WHERE a.counselor_id = ? AND a.application_status IN ('submitted', 'under_review')
                          ORDER BY a.submission_date DESC LIMIT 5");
    $stmt->execute([$_SESSION['user_id']]);
    $pending_apps = $stmt->fetchAll();
} catch(PDOException $e) {
    $pending_apps = [];
    error_log("Error fetching pending applications: " . $e->getMessage());
}

// Get pending documents
try {
    $stmt = $pdo->prepare("SELECT sd.id, sd.document_type, sd.created_at,
                          s.first_name, s.last_name
                          FROM student_documents sd
                          JOIN students s ON sd.student_id = s.id
                          WHERE s.assigned_counselor_id = ? AND sd.status = 'pending'
                          ORDER BY sd.created_at DESC LIMIT 5");
    $stmt->execute([$_SESSION['user_id']]);
    $pending_docs = $stmt->fetchAll();
} catch(PDOException $e) {
    $pending_docs = [];
    error_log("Error fetching pending documents: " . $e->getMessage());
}

// Get upcoming appointments
try {
    $stmt = $pdo->prepare("SELECT a.*, s.first_name, s.last_name, a.appointment_type
                          FROM appointments a
                          JOIN students s ON a.student_id = s.id
                          WHERE a.counselor_id = ? AND a.scheduled_time > NOW()
                          ORDER BY a.scheduled_time ASC LIMIT 5");
    $stmt->execute([$_SESSION['user_id']]);
    $upcoming_appts = $stmt->fetchAll();
} catch(PDOException $e) {
    $upcoming_appts = [];
    error_log("Error fetching upcoming appointments: " . $e->getMessage());
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Counselor 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>
        .stat-card {
            border-left: 5px solid #3fb7fe;
        }
        .stat-card .icon {
            font-size: 2rem;
            opacity: 0.2;
        }
        .table thead th {
            background-color: #f8f9fa;
            border-top: 0;
        }
        .activity-item {
            border-left: 3px solid #3fb7fe;
            padding-left: 15px;
            margin-bottom: 10px;
        }
        .revenue-card {
            background: linear-gradient(135deg, #28a745, #1e7e34);
            color: white;
        }
        .student-card {
            transition: all 0.3s;
        }
        .student-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>

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

<div class="container-fluid bg-primary text-white py-5">
    <div class="container">
        <h1>Counselor Dashboard</h1>
        <p>Welcome back, <?= htmlspecialchars($counselor['first_name']) ?> | <?= htmlspecialchars($counselor['specialization_text'] ?: 'Study Abroad Consultant') ?></p>
    </div>
</div>

<div class="container py-5">
    <div class="row">
        <div class="col-md-3 mb-4">
            <div class="card stat-card">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-users icon"></i></div>
                    <h5>My Students</h5>
                    <h2><?= $stats['my_students'] ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card stat-card" style="border-left-color: #ffc107;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-file-alt icon" style="color: #ffc107;"></i></div>
                    <h5>Pending Apps</h5>
                    <h2><?= $stats['pending_applications'] ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card stat-card" style="border-left-color: #dc3545;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-clock icon" style="color: #dc3545;"></i></div>
                    <h5>Pending Docs</h5>
                    <h2><?= $stats['pending_documents'] ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card stat-card" style="border-left-color: #28a745;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-calendar-check icon" style="color: #28a745;"></i></div>
                    <h5>Appointments</h5>
                    <h2><?= $stats['upcoming_appointments'] ?></h2>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <!-- Pending Applications -->
            <div class="section-title position-relative mb-4">
                <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Pending Tasks</h6>
                <h1 class="display-5">Applications to Review</h1>
            </div>
            <div class="table-responsive mb-5">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Student</th>
                            <th>Program</th>
                            <th>University</th>
                            <th>Status</th>
                            <th>Submitted</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pending_apps as $app): ?>
                        <tr>
                            <td><?= htmlspecialchars($app['first_name'] . ' ' . $app['last_name']) ?></td>
                            <td><?= htmlspecialchars($app['program']) ?></td>
                            <td><?= htmlspecialchars($app['university']) ?></td>
                            <td><span class="badge badge-warning"><?= ucfirst($app['application_status']) ?></span></td>
                            <td><?= date('M j', strtotime($app['submission_date'])) ?></td>
                            <td>
                                <a href="counselor-applications.php?id=<?= $app['id'] ?>" class="btn btn-sm btn-primary">Review</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($pending_apps)): ?>
                        <tr>
                            <td colspan="6" class="text-center">No pending applications found</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Upcoming Appointments -->
            <div class="section-title position-relative mb-4">
                <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Schedule</h6>
                <h1 class="display-5">Upcoming Appointments</h1>
            </div>
            <div class="table-responsive mb-5">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Student</th>
                            <th>Type</th>
                            <th>Date & Time</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($upcoming_appts as $appt): ?>
                        <tr>
                            <td><?= htmlspecialchars($appt['first_name'] . ' ' . $appt['last_name']) ?></td>
                            <td><?= ucfirst($appt['appointment_type']) ?></td>
                            <td><?= date('M j, Y H:i', strtotime($appt['scheduled_time'])) ?></td>
                            <td>
                                <?php if (!empty($appt['google_meet_link'])): ?>
                                <a href="<?= htmlspecialchars($appt['google_meet_link']) ?>" class="btn btn-sm btn-primary" target="_blank">Join</a>
                                <?php endif; ?>
                                <a href="#" class="btn btn-sm btn-outline-primary">Details</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($upcoming_appts)): ?>
                        <tr>
                            <td colspan="4" class="text-center">No upcoming appointments</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- Recent Activities -->
            <div class="section-title position-relative mb-4">
                <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">System Activity</h6>
                <h1 class="display-5">Recent Activities</h1>
            </div>
            <div class="card">
                <div class="card-body">
                    <?php foreach ($activities as $act): ?>
                    <div class="activity-item">
                        <strong><?= htmlspecialchars($act['activity_type']) ?></strong>: 
                        <?= htmlspecialchars($act['description']) ?>
                        <br>
                        <small class="text-muted">
                            <?= htmlspecialchars($act['first_name'] . ' ' . $act['last_name'] ?: $act['email']) ?> 
                            • <?= date('M j, H:i', strtotime($act['created_at'])) ?>
                        </small>
                    </div>
                    <?php endforeach; ?>
                    <?php if (empty($activities)): ?>
                    <div class="text-center text-muted">No recent activities</div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="mt-4">
                <div class="bg-light p-4 rounded">
                    <h6><i class="fas fa-bolt"></i> Quick Actions</h6>
                    <div class="row mt-3">
                        <div class="col-6 mb-3">
                            <a href="counselor-students.php" class="text-decoration-none">
                                <div class="text-center p-3 bg-white shadow-sm rounded">
                                    <i class="fas fa-users card-icon text-primary"></i>
                                    <h6 class="small">My Students</h6>
                                </div>
                            </a>
                        </div>
                        <div class="col-6 mb-3">
                            <a href="counselor-applications.php" class="text-decoration-none">
                                <div class="text-center p-3 bg-white shadow-sm rounded">
                                    <i class="fas fa-file-alt card-icon text-primary"></i>
                                    <h6 class="small">Applications</h6>
                                </div>
                            </a>
                        </div>
                        <div class="col-6 mb-3">
                            <a href="counselor-appointments.php" class="text-decoration-none">
                                <div class="text-center p-3 bg-white shadow-sm rounded">
                                    <i class="fas fa-calendar card-icon text-primary"></i>
                                    <h6 class="small">Appointments</h6>
                                </div>
                            </a>
                        </div>
                        <div class="col-6 mb-3">
                            <a href="counselor-messages.php" 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">Messages</h6>
                                </div>
                            </a>
                        </div>
                    </div>
                </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>
    document.getElementById('year').textContent = new Date().getFullYear();
</script>
</body>
</html>