<?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_admin.php');

// Handle messages
$msg = '';
if(isset($_GET['msg'])) {
    if($_GET['msg'] == "refered") {
        $msg = "<div class='alert alert-success'>Refered successfully</div>";
    } else if($_GET['msg'] == "failed") {
        $msg = "<div class='alert alert-warning'>Something went wrong, please try again</div>";
    }
}

if(isset($_SESSION['msg']) && $_SESSION['msg'] == "update") {
    $msg = "<div class='alert alert-success'>Order Update Succesful. Customer will receive email. <a href='new_order.php' class='btn btn-sm btn-light'>Refresh</a></div>";
}

// Process results if val and hsh parameters exist
if(isset($_GET['val']) && isset($_GET['hsh'])) {
    $rows1 = sql($DBH, "SELECT * FROM tbl_student_results where csv_no = ?", [$_GET['val']], "rows");
    foreach($rows1 as $row1) {    
        $total = ($row1['test'] + $row1['home_work'] + $row1['project'] + $row1['exam']);
        sql($DBH, "UPDATE tbl_student_results set total = ?, teacher_no = ? WHERE registration_no =? AND test = ?", 
            [$total, $_GET['hsh'], $row1['registration_no'], $row1['test']]);
        
        // Calculate positions and grades
        $rows2 = sql($DBH, "SELECT * FROM tbl_student_results where csv_no = ? ORDER by (total) desc", [$_GET['val']], "rows");
        $sno = 0;
        foreach($rows2 as $row2) {    
            $sno++;
            $us_total = $row2['total'];
            
            if($us_total <= 39) {
                $grade = "Poor";
            } else if ($us_total > 39 && $us_total <= 49) {
                $grade = "Fair";
            } else if ($us_total > 49 && $us_total <= 59) {
                $grade = "Credit";
            } else if ($us_total > 59 && $us_total <= 69) {
                $grade = "Good";
            } else if ($us_total > 69 && $us_total <= 79) {
                $grade = "Very Good";
            } else if ($us_total > 79 && $us_total <= 100) {
                $grade = "Excellent";
            }
            
            sql($DBH, "UPDATE tbl_student_results set grade = ?, position = ? WHERE registration_no =? AND test = ?", 
                [$grade, $sno, $row2['registration_no'], $row2['test']]);
        }
    }
}

// Get all result classes for the selected term and year
$result_classes = [];
if(isset($_GET['id']) && isset($_GET['examyear'])) {
    $result_classes = sql($DBH, 
        "SELECT DISTINCT class FROM tbl_student_results WHERE term = ? AND year = ? ORDER BY class", 
        [$_GET['id'], $_GET['examyear']], 
        "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>Verbum Dei International College - Manage Results</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-color: #0d47a1;
      --secondary-color: #1976d2;
      --accent-color: #bbdefb;
      --dark-color: #002171;
      --light-color: #e3f2fd;
    }
    
    body {
      font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background-color: var(--light-color);
      padding-top: 56px;
    }
    
    /* Sidebar Styles */
    .sidebar {
      background: linear-gradient(180deg, var(--dark-color) 0%, var(--primary-color) 100%);
      position: fixed;
      top: 56px;
      left: -250px;
      width: 250px;
      height: calc(100vh - 56px);
      transition: all 0.3s;
      z-index: 1000;
      overflow-y: auto;
    }
    
    .sidebar.active {
      left: 0;
    }
    
    .sidebar .nav-link {
      color: rgba(255, 255, 255, 0.8);
      font-weight: 600;
      padding: 0.75rem 1rem;
      margin-bottom: 0.2rem;
    }
    
    .sidebar .nav-link:hover {
      color: #fff;
      background-color: rgba(255, 255, 255, 0.1);
    }
    
    .sidebar .nav-link.active {
      color: #fff;
      background-color: var(--secondary-color);
    }
    
    .sidebar .nav-link i {
      margin-right: 0.5rem;
    }
    
    /* Main Content Styles */
    .main-content {
      margin-left: 0;
      width: 100%;
      transition: all 0.3s;
    }
    
    @media (min-width: 992px) {
      .sidebar {
        left: 0;
      }
      .main-content {
        margin-left: 250px;
        width: calc(100% - 250px);
      }
      body {
        padding-top: 0;
      }
    }
    
    /* Navbar Styles */
    .navbar {
      background-color: var(--light-color);
      box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
      position: fixed;
      top: 0;
      width: 100%;
      z-index: 1030;
    }
    
    .navbar-brand {
      font-weight: 800;
      font-size: 1.2rem;
      color: var(--dark-color);
    }
    
    /* Card Styles */
    .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: #f8f9fc;
      border-bottom: 1px solid #e3e6f0;
      font-weight: 700;
    }
    
    /* Button Styles */
    .btn-primary {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
    }
    
    /* Result Folder Styles */
    .result-folder {
      width: 250px; /* Increased width */
      min-height: 120px; /* Added min-height */
      transition: all 0.2s ease;
      border-left: 4px solid var(--primary-color);
      background: white;
      padding: 15px;
      margin: 10px;
      border-radius: 0.5rem;
      box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
      display: flex;
      flex-direction: column;
    }
    
    .result-folder:hover {
      transform: translateY(-3px);
      box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15);
    }
    
    .folder-container {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      padding: 15px;
      background-color: var(--light-color);
      border-radius: 0.5rem;
    }
    
    .class-name {
      font-size: 1rem;
      font-weight: 600;
      margin-bottom: 10px;
      white-space: normal; /* Allow text to wrap */
      word-break: break-word; /* Break long words */
    }
    
    .folder-actions {
      margin-top: auto; /* Push buttons to bottom */
      display: flex;
      flex-direction: column;
      gap: 8px;
    }
    
    /* Footer styles */
    .footer {
      background-color: var(--dark-color);
      color: white;
      padding: 20px 0;
      margin-top: 30px;
    }
    
    .copyright-text {
      font-weight: 600;
      font-size: 1rem;
    }
    
    .powered-by {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      color: white;
    }
    
    .powered-by img {
      height: 30px;
      margin-left: 10px;
    }
  </style>
</head>

<body>
  <!-- Top Navigation -->
  <nav class="navbar navbar-expand-lg navbar-light">
    <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="admin-info me-3">
          <span class="admin-name"><?php echo $_SESSION['fullname']; ?></span>
          <span class="admin-access">(Administrator)</span>
          <i class="fas fa-user-circle admin-icon"></i>
        </div>
        <a href="logout.php" class="btn btn-sm btn-outline-danger">
          <i class="fas fa-sign-out-alt"></i>
        </a>
      </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">Admin 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>
            Admin Centre
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="post_session.php">
            <i class="fas fa-fw fa-calendar-alt"></i>
            School Year/Session
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="post_classes.php">
            <i class="fas fa-fw fa-building"></i>
            Create Classes
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="add_students.php">
            <i class="fas fa-fw fa-user-plus"></i>
            Register New Student
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="post_subjects.php">
            <i class="fas fa-fw fa-book"></i>
            Create Subjects
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="teachers.php">
            <i class="fas fa-fw fa-chalkboard-teacher"></i>
            Manage Teachers
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="students.php">
            <i class="fas fa-fw fa-users"></i>
            Manage Students
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="deactivate_students.php">
            <i class="fas fa-fw fa-user-lock"></i>
            Activate/Deactivate
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="upload_results.php">
            <i class="fas fa-fw fa-upload"></i>
            Upload Results
          </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">Manage Student Results</h1>
            <div class="d-none d-sm-inline-block">
                <span class="badge bg-primary p-2">
                    <i class="fas fa-phone-alt me-1"></i> Support: MENDOH - 08032929756
                </span>
            </div>
        </div>

        <!-- Messages -->
        <?php if (!empty($msg)) echo $msg; ?>

        <!-- Result Folders Section -->
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background-color: var(--light-color);">
                <h6 class="m-0 font-weight-bold text-primary">Result Folders - <?= isset($_GET['id']) ? htmlspecialchars($_GET['id']) : '' ?> Term <?= isset($_GET['examyear']) ? htmlspecialchars($_GET['examyear']) : '' ?></h6>
            </div>
            <div class="card-body" style="background-color: var(--light-color);">
                <div class="folder-container">
                    <?php
                    if(!empty($result_classes)) {
                        foreach($result_classes as $class) {
                            $class_name = $class['class'];
                            $g_id = $_GET['id'] ?? '';
                            $g_yr = $_GET['examyear'] ?? '';
                            
                            echo '
                            <div class="result-folder">
                                <div class="class-name">'.htmlspecialchars($class_name).'</div>
                                <div class="folder-actions">
                                    <a href="main_students.php?id='.htmlspecialchars($class_name).'&term='.htmlspecialchars($g_id).'&examyear='.htmlspecialchars($g_yr).'" 
                                        class="btn btn-sm btn-primary" target="_blank">
                                        <i class="fas fa-eye me-1"></i> View
                                    </a>
                                    <a href="#" onclick="return confirmDelete(\''.htmlspecialchars($class_name).'\', \''.htmlspecialchars($g_id).'\', \''.htmlspecialchars($g_yr).'\')" 
                                        class="btn btn-sm btn-danger">
                                        <i class="fas fa-trash me-1"></i> Delete
                                    </a>
                                </div>
                            </div>';
                        }
                    } else {
                        echo '<div class="alert alert-info w-100">No results found for the selected term and year.</div>';
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <footer class="footer mt-auto py-3">
      <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="powered-by">
              <a href="https://dataswift.com.ng" target="_blank" rel="noopener noreferrer" class="powered-by-link">
                <span>Powered by DataSwift</span>
                <img src="datalogo.png" alt="DataSwift Logo">
              </a>
            </div>
          </div>
        </div>
      </div>
    </footer>
</main>

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

    // Delete confirmation
    function confirmDelete(className, termId, examYear) {
      if(confirm('Are you sure you want to delete all results for ' + className + '? This action cannot be undone!')) {
        window.location.href = 'settings.php?delete_results=' + encodeURIComponent(className) + '&term=' + encodeURIComponent(termId) + '&examyear=' + encodeURIComponent(examYear);
      }
      return false;
    }
  </script>
</body>
</html>