<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_user.php');

// Restrict access to teachers only
if (!isTeacherLoggedIn()) {
    $_SESSION['msg'] = 'access_denied';
    header("Location: index.php");
    exit();
}

// Get current teacher information
$teacher_id = getTeacherId();
$teacher_name = getTeacherName();

// Check if teacher_id is provided in URL for viewing specific teacher's results
$view_teacher_id = isset($_GET['teacher_id']) ? $_GET['teacher_id'] : $teacher_id;

// Verify that the teacher can only view their own results unless admin
if ($view_teacher_id != $teacher_id) {
    if ($_SESSION['SESS_ACCESS_LEVEL'] != 'Admin') {
        $_SESSION['error_message'] = "You can only view your own results.";
        header("Location: main.php");
        exit();
    }
}

// Check if year parameter is set
if (!isset($_GET['id'])) {
    $_SESSION['error_message'] = "No year selected. Please go back and select a year.";
    header("Location: main.php");
    exit();
}

$selected_year = $_GET['id'];

// Get distinct terms for the selected year and teacher
$terms = sql($DBH, 
    "SELECT DISTINCT term FROM tbl_student_results WHERE year = ? AND teacher_no = ? ORDER BY term", 
    [$selected_year, $view_teacher_id], 
    "rows"
);
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Manage Results - VERBUM DEI INT'L COLLEGE</title>
  <link rel="icon" type="image/png" href="https://portal.vda.com.ng/coll_admin/coll_logo.jpg">
  
  <!-- Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  
  <!-- Custom CSS -->
  <style>
    :root {
      --primary-blue: #1976d2;
      --dark-blue: #0d47a1;
      --light-blue: #64b5f6;
      --accent-blue: #bbdefb;
      --bg-light: #e3f2fd;
    }
    
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: var(--bg-light);
      padding-top: 56px;
    }
    
    .sidebar {
      background: linear-gradient(180deg, var(--dark-blue) 0%, var(--primary-blue) 100%);
      position: fixed;
      top: 56px;
      left: 0;
      width: 250px;
      height: calc(100vh - 56px);
      transition: all 0.3s;
      z-index: 1000;
      overflow-y: auto;
    }
    
    .sidebar .nav-link {
      color: rgba(255, 255, 255, 0.85);
      font-weight: 600;
      padding: 0.75rem 1rem;
      margin-bottom: 0.2rem;
      transition: all 0.2s;
    }
    
    .sidebar .nav-link:hover {
      color: #fff;
      background-color: rgba(255, 255, 255, 0.15);
    }
    
    .sidebar .nav-link.active {
      color: #fff;
      background-color: var(--light-blue);
      box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    
    .main-content {
      margin-left: 250px;
      width: calc(100% - 250px);
      transition: all 0.3s;
      min-height: calc(100vh - 56px);
    }
    
    @media (max-width: 991.98px) {
      .sidebar {
        left: -250px;
      }
      .main-content {
        margin-left: 0;
        width: 100%;
      }
    }
    
    .navbar {
      background-color: var(--primary-blue);
      box-shadow: 0 0.15rem 1.75rem 0 rgba(33, 37, 41, 0.1);
      position: fixed;
      top: 0;
      width: 100%;
      z-index: 1030;
      color: white;
    }
    
    .card {
      border: none;
      border-radius: 0.5rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
      margin-bottom: 1.5rem;
    }
    
    .card-header {
      background-color: var(--accent-blue);
      border-bottom: 1px solid var(--light-blue);
      font-weight: 700;
      color: var(--dark-blue);
    }
    
    .teacher-info {
      display: flex;
      align-items: center;
      background-color: rgba(255,255,255,0.2);
      padding: 8px 12px;
      border-radius: 0.5rem;
      color: white;
    }
    
    .teacher-name {
      margin-right: 5px;
      font-weight: 600;
    }
    
    .teacher-badge {
      font-style: italic;
      opacity: 0.8;
      margin-right: 10px;
      font-size: 0.9rem;
    }
    
    .term-card {
      transition: transform 0.3s, box-shadow 0.3s;
      border-left: 4px solid var(--primary-blue);
    }
    
    .term-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }
    
    .term-icon {
      font-size: 2rem;
      color: var(--primary-blue);
      margin-bottom: 1rem;
    }
    
    .stats-badge {
      background: var(--primary-blue);
      color: white;
      padding: 0.25rem 0.5rem;
      border-radius: 0.25rem;
      font-size: 0.8rem;
    }
    
    .footer {
      background-color: var(--dark-blue);
      color: white;
      padding: 20px 0;
      margin-top: 30px;
    }
  </style>
</head>

<body>
  <!-- Top Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container-fluid">
      <button id="sidebarToggle" class="btn btn-link d-lg-none me-2">
        <i class="fas fa-bars"></i>
      </button>
      <a class="navbar-brand d-none d-lg-block" href="#">
        VERBUM DEI INT'L COLLEGE
      </a>
      <div class="ms-auto d-flex align-items-center">
        <div class="teacher-info me-3">
          <span class="teacher-name"><?php echo htmlspecialchars($teacher_name); ?></span>
          <span class="teacher-badge">(Teacher)</span>
          <i class="fas fa-chalkboard-teacher"></i>
        </div>
        <div class="dropdown">
          <button class="btn btn-outline-light dropdown-toggle" type="button" id="profileDropdown" data-bs-toggle="dropdown">
            <i class="fas fa-user"></i>
          </button>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="edit_profile.php"><i class="fas fa-user-edit me-2"></i>Edit Profile</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
          </ul>
        </div>
      </div>
    </div>
  </nav>

  <!-- Sidebar -->
  <nav id="sidebar" class="sidebar">
    <div class="position-sticky pt-3">
      <div class="text-center mb-4 d-none d-lg-block">
        <img src="https://portal.vda.com.ng/coll_admin/coll_logo.jpg" alt="School Logo" class="rounded-circle" width="80">
        <h5 class="mt-2 text-white">VERBUM DEI INT'L COLLEGE</h5>
        <p class="text-white-50 small">Teacher Dashboard</p>
      </div>
      
      <ul class="nav flex-column">
        <li class="nav-item">
          <a class="nav-link" href="main.php">
            <i class="fas fa-fw fa-tachometer-alt"></i>
            Teacher Dashboard
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="upload_results.php">
            <i class="fas fa-fw fa-upload"></i>
            Upload Tests & Exams
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="upload_attendance.php">
            <i class="fas fa-fw fa-calendar-check"></i>
            Upload Attendance
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="upload_skills.php">
            <i class="fas fa-fw fa-chart-bar"></i>
            Upload Skills & Psychomotor
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="download_broadsheet.php">
            <i class="fas fa-fw fa-file-pdf"></i>
            View Broadsheets
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="https://portal.vda.com.ng" target="_blank">
            <i class="fas fa-fw fa-external-link-alt"></i>
            Go to Main School Portal
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="logout.php">
            <i class="fas fa-fw fa-sign-out-alt"></i>
            Logout
          </a>
        </li>
      </ul>
    </div>
  </nav>

  <!-- Main Content -->
  <main class="main-content">
    <div class="container-fluid px-4 pt-4">
      <!-- Page Heading -->
      <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">
          <i class="fas fa-file-alt me-2"></i>My Result Broadsheets
        </h1>
        <div class="d-none d-sm-inline-block">
          <span class="badge bg-light text-dark p-2">
            <i class="fas fa-phone-alt me-1"></i> Support: MENDOH - 08032929756
          </span>
        </div>
      </div>

      <!-- Breadcrumb -->
      <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="main.php"><i class="fas fa-home me-1"></i>Dashboard</a></li>
          <li class="breadcrumb-item"><a href="main.php">Academic Years</a></li>
          <li class="breadcrumb-item active"><?php echo htmlspecialchars($selected_year); ?></li>
        </ol>
      </nav>

      <!-- Year Header -->
      <div class="card border-primary mb-4">
        <div class="card-body text-center bg-light">
          <h2 class="text-primary mb-2">
            <i class="fas fa-calendar-alt me-2"></i>Academic Year: <?php echo htmlspecialchars($selected_year); ?>
          </h2>
          <p class="text-muted mb-0">Select a term to view class broadsheets</p>
        </div>
      </div>

      <!-- Terms Section -->
      <div class="row">
        <?php if(!empty($terms)): ?>
          <?php foreach($terms as $term): ?>
            <?php
            $term_name = $term['term'];
            
            // Get statistics for this term
            $class_count = sql($DBH, 
                "SELECT COUNT(DISTINCT class) FROM tbl_student_results WHERE year = ? AND term = ? AND teacher_no = ?", 
                [$selected_year, $term_name, $view_teacher_id], 
                "rows"
            )[0][0];
            
            $student_count = sql($DBH, 
                "SELECT COUNT(DISTINCT registration_no) FROM tbl_student_results WHERE year = ? AND term = ? AND teacher_no = ?", 
                [$selected_year, $term_name, $view_teacher_id], 
                "rows"
            )[0][0];
            
            $subject_count = sql($DBH, 
                "SELECT COUNT(DISTINCT subject) FROM tbl_student_results WHERE year = ? AND term = ? AND teacher_no = ?", 
                [$selected_year, $term_name, $view_teacher_id], 
                "rows"
            )[0][0];
            ?>
            
            <div class="col-xl-4 col-md-6 mb-4">
              <div class="card term-card h-100">
                <div class="card-body text-center">
                  <div class="term-icon">
                    <i class="fas fa-folder-open"></i>
                  </div>
                  <h4 class="card-title text-primary"><?php echo htmlspecialchars($term_name); ?></h4>
                  <p class="card-text text-muted">View class broadsheets for <?php echo htmlspecialchars($term_name); ?></p>
                  
                  <div class="row mt-3">
                    <div class="col-4">
                      <div class="stats-badge">
                        <i class="fas fa-building"></i> <?php echo $class_count; ?>
                      </div>
                      <small>Classes</small>
                    </div>
                    <div class="col-4">
                      <div class="stats-badge">
                        <i class="fas fa-users"></i> <?php echo $student_count; ?>
                      </div>
                      <small>Students</small>
                    </div>
                    <div class="col-4">
                      <div class="stats-badge">
                        <i class="fas fa-book"></i> <?php echo $subject_count; ?>
                      </div>
                      <small>Subjects</small>
                    </div>
                  </div>
                  
                  <a href="teacher_class.php?year=<?php echo urlencode($selected_year); ?>&term=<?php echo urlencode($term_name); ?>&teacher_id=<?php echo $view_teacher_id; ?>" 
                     class="btn btn-primary mt-3">
                    <i class="fas fa-table me-1"></i> View Broadsheets
                  </a>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        <?php else: ?>
          <div class="col-12">
            <div class="card">
              <div class="card-body text-center py-5">
                <i class="fas fa-folder-open fa-3x text-muted mb-3"></i>
                <h4 class="text-muted">No Results Found</h4>
                <p class="text-muted">You haven't uploaded any results for <?php echo htmlspecialchars($selected_year); ?> yet.</p>
                <a href="upload_results.php" class="btn btn-primary">
                  <i class="fas fa-upload me-1"></i> Upload Results
                </a>
              </div>
            </div>
          </div>
        <?php endif; ?>
      </div>

      <!-- Quick Stats -->
      <?php if(!empty($terms)): ?>
      <div class="row mt-4">
        <div class="col-12">
          <div class="card">
            <div class="card-header">
              <h5 class="mb-0"><i class="fas fa-chart-bar me-2"></i>Quick Statistics</h5>
            </div>
            <div class="card-body">
              <div class="row text-center">
                <div class="col-md-3">
                  <h3 class="text-primary"><?php echo count($terms); ?></h3>
                  <p class="text-muted">Terms</p>
                </div>
                <div class="col-md-3">
                  <?php
                  $total_classes = sql($DBH, 
                      "SELECT COUNT(DISTINCT class) FROM tbl_student_results WHERE year = ? AND teacher_no = ?", 
                      [$selected_year, $view_teacher_id], 
                      "rows"
                  )[0][0];
                  ?>
                  <h3 class="text-success"><?php echo $total_classes; ?></h3>
                  <p class="text-muted">Total Classes</p>
                </div>
                <div class="col-md-3">
                  <?php
                  $total_students = sql($DBH, 
                      "SELECT COUNT(DISTINCT registration_no) FROM tbl_student_results WHERE year = ? AND teacher_no = ?", 
                      [$selected_year, $view_teacher_id], 
                      "rows"
                  )[0][0];
                  ?>
                  <h3 class="text-info"><?php echo $total_students; ?></h3>
                  <p class="text-muted">Total Students</p>
                </div>
                <div class="col-md-3">
                  <?php
                  $total_results = sql($DBH, 
                      "SELECT COUNT(*) FROM tbl_student_results WHERE year = ? AND teacher_no = ?", 
                      [$selected_year, $view_teacher_id], 
                      "rows"
                  )[0][0];
                  ?>
                  <h3 class="text-warning"><?php echo $total_results; ?></h3>
                  <p class="text-muted">Result Records</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <?php endif; ?>
    </div>
  </main>

  <!-- Footer -->
  <footer class="footer">
    <div class="container-fluid">
      <div class="row align-items-center">
        <div class="col-md-6">
          <span class="copyright-text">Copyright &copy; VERBUM DEI INT'L COLLEGE <?php echo date("Y"); ?></span>
        </div>
        <div class="col-md-6">
          <div class="text-md-end">
            <a href="https://dataswift.com.ng" target="_blank" rel="noopener noreferrer" class="text-white">
              <span>Powered by DataSwift</span>
              <img src="datalogo.png" alt="DataSwift Logo" class="ms-2" height="20">
            </a>
          </div>
        </div>
      </div>
    </div>
  </footer>

  <!-- Bootstrap 5 JS Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  
  <script>
    // Toggle sidebar on mobile
    document.getElementById('sidebarToggle').addEventListener('click', function() {
        document.getElementById('sidebar').classList.toggle('active');
        document.querySelector('.main-content').classList.toggle('active');
    });
  </script>
</body>
</html>