<?php
session_start();
include('db_connection.php');

/* =========================
   AUTH CHECK
========================= */
if (
    !isset($_SESSION['teacher_id']) ||
    !isset($_SESSION['role']) ||
    $_SESSION['role'] !== 'teacher'
) {
    header("Location: teacher_login.php");
    exit();
}

$teacher_id = intval($_SESSION['teacher_id']);
$teacher_name = $_SESSION['name'] ?? 'Teacher';

/* =========================
   SETTINGS
========================= */
$current_term = 'Not Set';
$current_session = 'Not Set';

$settings = $conn->query("SELECT current_term, current_session FROM settings LIMIT 1");
if ($settings && $row = $settings->fetch_assoc()) {
    $current_term = $row['current_term'];
    $current_session = $row['current_session'];
}

/* =========================
   UPCOMING CLASSES
========================= */
$upcoming_classes = [];

$sql = "SELECT t.day, t.start_time, t.end_time, s.subject_name, c.class_name
        FROM timetable t
        JOIN subject s ON t.subject_id = s.subject_id
        JOIN classes c ON t.class_id = c.class_id
        WHERE t.teacher_id = ?
        ORDER BY t.start_time ASC
        LIMIT 5";

$stmt = $conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("i", $teacher_id);
    $stmt->execute();
    $upcoming_classes = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

/* =========================
   ANNOUNCEMENTS
========================= */
$announcements = [];
$res = $conn->query("SELECT activity_name, description FROM upcoming_activities ORDER BY activity_date DESC LIMIT 5");
if ($res) $announcements = $res->fetch_all(MYSQLI_ASSOC);

/* =========================
   NOTIFICATIONS
========================= */
$notifications = [];
$res = $conn->query("SELECT message_head, message_body FROM notifications WHERE role='teacher' ORDER BY created_at DESC LIMIT 5");
if ($res) $notifications = $res->fetch_all(MYSQLI_ASSOC);

/* =========================
   ATTENDANCE
========================= */
$total = 0;
$present = 0;

$sql = "SELECT COUNT(*) total,
               SUM(CASE WHEN status='present' THEN 1 ELSE 0 END) present
        FROM student_attendance
        WHERE teacher_id = ?";

$stmt = $conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("i", $teacher_id);
    $stmt->execute();
    $stmt->bind_result($total, $present);
    $stmt->fetch();
    $stmt->close();
}
$absent = $total - $present;

/* =========================
   PAYROLL (FIXED & SAFE)
========================= */
$payroll = [
    'id' => 0,
    'salary' => 0,
    'net_salary' => 0,
    'absent_days' => 0,
    'payment_date' => '',
    'pay_month' => '',
    'pay_year' => ''
];

$sql = "SELECT 
            id,
            basic_salary,
            net_salary,
            absent_days,
            payment_date,
            pay_month,
            pay_year
        FROM payrolls
        WHERE teacher_id = ?
        ORDER BY pay_year DESC, pay_month DESC, payment_date DESC
        LIMIT 1";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    die("Payroll Query Error: " . $conn->error);
}

$stmt->bind_param("i", $teacher_id);
$stmt->execute();

$result = $stmt->get_result();

if ($result && $row = $result->fetch_assoc()) {
    $payroll = $row;
}

$stmt->close();

/* Payslip link */
$payslip_link = ($payroll['id'] > 0)
    ? "download_payslip.php?id=" . $payroll['id']
    : "";
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Premium Teacher Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
:root{
    --bg:#f4f6f9;
    --card:#ffffff;
    --text:#111;
    --sidebar:#0f172a;
}

body.dark{
    --bg:#0b1220;
    --card:#111827;
    --text:#e5e7eb;
    --sidebar:#020617;
}

body{
    margin:0;
    font-family:Segoe UI;
    background:var(--bg);
    color:var(--text);
}

/* SIDEBAR */
.sidebar{
    position:fixed;
    top:0;
    left:0;
    width:260px;
    height:100%;
    background:var(--sidebar);
    padding-top:20px;
    transition:0.3s;
    z-index:1000;
}

.sidebar h4{
    color:#fff;
    text-align:center;
}

.sidebar a{
    display:block;
    padding:12px 20px;
    color:#cbd5e1;
    text-decoration:none;
}

.sidebar a:hover{
    background:#1e293b;
    color:#fff;
}

/* MAIN */
.main{
    margin-left:260px;
    padding:20px;
}

/* CARDS */
.card-box{
    background:var(--card);
    border-radius:16px;
    padding:20px;
    margin-bottom:15px;
    box-shadow:0 5px 20px rgba(0,0,0,0.08);
}

/* STATS */
.stats{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(180px,1fr));
    gap:10px;
}

.stat{
    padding:15px;
    border-radius:12px;
    color:#fff;
}
.blue{background:#2563eb;}
.green{background:#16a34a;}
.red{background:#dc2626;}
.gray{background:#475569;}

/* TOP BAR */
.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
}

/* MOBILE */
.menu-btn{
    display:none;
    font-size:26px;
    cursor:pointer;
}

@media(max-width:768px){
    .sidebar{
        transform:translateX(-100%);
    }
    .sidebar.active{
        transform:translateX(0);
    }
    .main{margin-left:0;}
    .menu-btn{display:block;}
}
</style>
</head>

<body>

<!-- SIDEBAR -->
<div class="sidebar" id="sidebar">
    <h4>Teacher Panel</h4>
    <a href="teacher_dashboard.php">Dashboard</a>
    <a href="attendance.php">Attendance</a>
    <a href="add_homework.php">Assignments</a>
    <a href="feedback_grading.php">Grades</a>
    <a href="class_timetable.php">Timetable</a>
    <a href="profile.php">Profile</a>
    <a href="debtors.php">Debtors</a>
    <a href="download_payslip.php">Payslip</a>
    <a href="logout.php">Logout</a>
</div>

<!-- MAIN -->
<div class="main">

<!-- TOP BAR -->
<div class="topbar mb-3">
    <span class="menu-btn" onclick="toggleSidebar()">☰</span>
    <button class="btn btn-dark btn-sm" onclick="toggleDark()">🌙 Dark Mode</button>
</div>

<!-- HEADER -->
<div class="card-box">
    <h3>Welcome, <?= htmlspecialchars($teacher_name) ?> 👋</h3>
    <p>Term: <b><?= $current_term ?></b> | Session: <b><?= $current_session ?></b></p>
</div>

<!-- STATS -->
<div class="stats">
    <div class="stat blue"><h5>Attendance</h5><h3><?= $total ?></h3></div>
    <div class="stat green"><h5>Present</h5><h3><?= $present ?></h3></div>
    <div class="stat red"><h5>Absent</h5><h3><?= $absent ?></h3></div>
    <div class="stat gray"><h5>Net Salary</h5><h3>₦<?= number_format($payroll['net_salary']) ?></h3></div>
</div>

<!-- PAYROLL -->
<div class="card-box">
    <h5>Payroll Summary</h5>
    <p><b>Basic Salary:</b> ₦<?= number_format($payroll['basic_salary']) ?></p>
    <p><b>Absent Days:</b> <?= $payroll['absent_days'] ?></p>
    <p><b>Net Salary:</b> ₦<?= number_format($payroll['net_salary']) ?></p>

    <?php if ($payroll['id'] > 0): ?>
        <a href="<?= $payslip_link ?>" class="btn btn-primary btn-sm mt-2">
            Download Payslip
        </a>
    <?php else: ?>
        <p class="text-muted">No payslip available</p>
    <?php endif; ?>
</div>

<!-- UPCOMING -->
<div class="card-box">
    <h5>Upcoming Classes</h5>
    <?php foreach($upcoming_classes as $c): ?>
        <div><?= $c['class_name'] ?> - <?= $c['subject_name'] ?> (<?= $c['day'] ?>)</div>
    <?php endforeach; ?>
</div>

<!-- ANNOUNCEMENTS -->
<div class="card-box">
    <h5>Announcements</h5>
    <?php foreach($announcements as $a): ?>
        <div><b><?= $a['activity_name'] ?></b> - <?= $a['description'] ?></div>
    <?php endforeach; ?>
</div>

<!-- NOTIFICATIONS -->
<div class="card-box">
    <h5>Notifications</h5>
    <?php foreach($notifications as $n): ?>
        <div><b><?= $n['message_head'] ?></b> - <?= $n['message_body'] ?></div>
    <?php endforeach; ?>
</div>

</div>

<script>
function toggleSidebar(){
    document.getElementById("sidebar").classList.toggle("active");
}

function toggleDark(){
    document.body.classList.toggle("dark");
    localStorage.setItem("dark", document.body.classList.contains("dark"));
}

if(localStorage.getItem("dark") === "true"){
    document.body.classList.add("dark");
}
</script>

</body>
</html>