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

// Initialize variables
$msg = '';
$results = [];
$name = '';
$class = '';

// Process form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $reg_no = trim($_POST['reg_no'] ?? '');
    $session = trim($_POST['session'] ?? '');
    
    try {
        // Get student info from tbl_user
        $stmt = $DBH->prepare("SELECT fullname, registration_no FROM tbl_user WHERE registration_no = ? LIMIT 1");
        $stmt->execute([$reg_no]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($student) {
            $name = $student['fullname'];
            
            // Get all pins used by this student in the selected session
            $query = "SELECT p.* FROM tbl_pin p 
                     WHERE p.reg_no = ? AND p.year = ?
                     ORDER BY p.date_time DESC";
            
            $stmt = $DBH->prepare($query);
            $stmt->execute([$reg_no, $session]);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if (count($results) > 0) {
                $class = $results[0]['class'];
                $msg = "<div class='alert alert-success'>Found ".count($results)." PIN(s) used by this student</div>";
            } else {
                $msg = "<div class='alert alert-warning'>No PINs found for ".htmlspecialchars($name)." (".htmlspecialchars($reg_no).") in ".htmlspecialchars($session)."</div>";
            }
        } else {
            // Check if the registration number exists in tbl_pin but not tbl_user
            $stmt = $DBH->prepare("SELECT reg_no FROM tbl_pin WHERE reg_no = ? LIMIT 1");
            $stmt->execute([$reg_no]);
            $pinRecord = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($pinRecord) {
                $msg = "<div class='alert alert-warning'>Admission number found in PIN records but not in student database. Please check student registration.</div>";
            } else {
                $msg = "<div class='alert alert-danger'>Admission number not found in any records: ".htmlspecialchars($reg_no)."</div>";
            }
        }
    } catch (PDOException $e) {
        $msg = "<div class='alert alert-danger'>Database error: ".htmlspecialchars($e->getMessage())."</div>";
    }
}
?>

<!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>British Learner's College - Find PIN User</title>
  <link rel="icon" type="image/png" href="https://bkms.com.ng/portal/coll_admin/sch_logo.jpeg">
  
  <!-- 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: #2e7d32; /* Dark green */
      --secondary-color: #4caf50; /* Medium green */
      --accent-color: #8bc34a; /* Light green */
      --dark-color: #1b5e20; /* Very dark green */
      --light-color: #f1f8e9; /* Very light green */
    }
    
    html, body {
      height: 100%;
    }
    
    body {
      font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background-color: var(--light-color);
      display: flex;
      flex-direction: column;
    }
    
    /* 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);
    }
    
    /* Sidebar Styles */
    .sidebar {
      background: linear-gradient(180deg, var(--dark-color) 0%, var(--primary-color) 100%);
      position: fixed;
      top: 56px; /* Below navbar */
      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;
      flex: 1 0 auto;
      padding-top: 56px;
    }
    
    @media (min-width: 992px) {
      .sidebar {
        left: 0;
      }
      .main-content {
        margin-left: 250px;
        width: calc(100% - 250px);
      }
    }
    
    /* 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;
    }
    
    /* Table Styles */
    .table-responsive {
      overflow-x: auto;
    }
    
    .table th {
      background-color: var(--light-color);
    }
    
    /* Footer styles */
    .footer {
      background-color: var(--dark-color);
      color: white;
      padding: 20px 0;
      flex-shrink: 0;
      width: 100%;
    }
    
    @media (min-width: 992px) {
      .footer {
        margin-left: 250px;
        width: calc(100% - 250px);
      }
    }
  </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="#">
        BRITISH LEARNER'S COLLEGE
      </a>
      <div class="ms-auto d-flex align-items-center">
        <div class="admin-info me-3">
          <span class="admin-name"><?php echo $admin_name; ?></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://bkms.com.ng/portal/coll_admin/sch_logo.jpeg" alt="School Logo" class="rounded-circle" width="80">
        <h5 class="mt-2 text-white">BRITISH LEARNER'S 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>
        <!-- Other menu items... -->
        <li class="nav-item">
          <a class="nav-link active" href="find_pin_user.php">
            <i class="fas fa-fw fa-key"></i>
            Find PIN User
          </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">Find PIN User</h1>
      </div>

      <!-- Messages -->
      <?php echo $msg; ?>

      <!-- Search Form -->
      <div class="card shadow mb-4">
        <div class="card-header py-3">
          <h6 class="m-0 font-weight-bold text-primary">Search PIN Usage</h6>
        </div>
        <div class="card-body">
          <form method="post" class="row g-3">
            <div class="col-md-6">
              <label for="reg_no" class="form-label">Admission Number</label>
              <input type="text" class="form-control" id="reg_no" name="reg_no" required>
            </div>
            <div class="col-md-6">
              <label for="session" class="form-label">Session/Year</label>
              <input type="text" class="form-control" id="session" name="session" required>
            </div>
            <div class="col-12">
              <button type="submit" class="btn btn-primary">
                <i class="fas fa-search me-1"></i> Search
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Results Section -->
      <?php if (!empty($results)): ?>
      <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
          <h6 class="m-0 font-weight-bold text-primary">PIN Usage Details</h6>
          <div>
            <span class="badge bg-primary">Student: <?php echo htmlspecialchars($name); ?></span>
            <span class="badge bg-secondary ms-2">Class: <?php echo htmlspecialchars($class); ?></span>
          </div>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-bordered table-hover">
              <thead class="thead-light">
                <tr>
                  <th>PIN</th>
                  <th>Serial</th>
                  <th>Class</th>
                  <th>Term</th>
                  <th>Session</th>
                  <th>Date Used</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($results as $row): ?>
                <tr>
                  <td><?php echo htmlspecialchars($row['pin']); ?></td>
                  <td><?php echo htmlspecialchars($row['Serial']); ?></td>
                  <td><?php echo htmlspecialchars($row['class']); ?></td>
                  <td><?php echo htmlspecialchars($row['term']); ?></td>
                  <td><?php echo htmlspecialchars($row['year']); ?></td>
                  <td><?php echo htmlspecialchars($row['date_time']); ?></td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </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; BRITISH LEARNER'S COLLEGE <?php echo date("Y"); ?></span>
        </div>
        <div class="col-md-6">
          <div class="powered-by">
            <span>Powered by DataSwift</span>
          </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>
  
  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.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');
    });
  </script>
</body>
</html>