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

// Check if the user is logged in
if (isset($_SESSION['SESS_ID_ADMIN'])) {
    $userId = $_SESSION['SESS_ID_ADMIN'];

    // Fetch user details based on the ID
    $query = "SELECT * FROM tbl_admin WHERE id = :id";
    $stmt = $DBH->prepare($query);
    $stmt->bindParam(':id', $userId, PDO::PARAM_INT);
    $stmt->execute();

    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $adminName = $row['username'];
    }
}

// School information
$schoolName = "Henzy Royal International School";
$schoolAddress = "No 17 Amadi Street, Amakohia, Uratta Owerri Imo State Nigeria";
$supportPhone = "+234 803 292 9756";
$supportEmail = "support@hris.com.ng";

// Initialize variables
$pin = $_GET['pin'] ?? '';
$pinInfo = null;
$error_message = '';
$success_message = '';
$warning_message = '';

// Get all available students for dropdown
$students = sql($DBH, "SELECT reg_no, name, class FROM tbl_user ORDER BY name", [], "rows");

// Get distinct batches for dropdown
$batches = sql($DBH, "SELECT DISTINCT batch FROM tbl_pin WHERE batch IS NOT NULL ORDER BY batch DESC", [], "rows");

// Get distinct batch_ids for dropdown
$batch_ids = sql($DBH, "SELECT DISTINCT batch_id FROM tbl_pin WHERE batch_id IS NOT NULL ORDER BY batch_id DESC", [], "rows");

// Get distinct years for dropdown
$years = sql($DBH, "SELECT DISTINCT year FROM tbl_pin WHERE year IS NOT NULL ORDER BY year DESC", [], "rows");

// Get distinct terms for dropdown
$terms = sql($DBH, "SELECT DISTINCT term FROM tbl_pin WHERE term IS NOT NULL ORDER BY term", [], "rows");

// Get distinct classes for dropdown
$classes = sql($DBH, "SELECT DISTINCT class FROM tbl_pin WHERE class IS NOT NULL ORDER BY class", [], "rows");

// If PIN is provided, fetch its details
if (!empty($pin)) {
    $pinInfo = sql($DBH, 
        "SELECT p.*, u.name as student_name, u.class as student_class 
         FROM tbl_pin p 
         LEFT JOIN tbl_user u ON p.reg_no = u.reg_no 
         WHERE p.pin = ?", 
        [$pin], 
        "row"
    );
    
    if (!$pinInfo) {
        $warning_message = "PIN not found: $pin";
    }
}

// Handle form submission for updating PIN
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_pin'])) {
    $original_pin = $_POST['original_pin'];
    $new_pin = trim($_POST['pin']);
    $serial = trim($_POST['serial']);
    $batch_id = trim($_POST['batch_id']);
    $batch = trim($_POST['batch']);
    $year = trim($_POST['year']);
    $term = trim($_POST['term']);
    $class = trim($_POST['class']);
    $reg_no = trim($_POST['reg_no']);
    $dt_stamp_start = trim($_POST['dt_stamp_start']);
    $dt_stamp_end = trim($_POST['dt_stamp_end']);
    $used_count = intval($_POST['used_count'] ?? 0);
    
    // Validate inputs
    if (empty($new_pin)) {
        $error_message = "PIN cannot be empty";
    } else {
        // Check if PIN already exists (if changed)
        if ($new_pin != $original_pin) {
            $checkPin = sql($DBH, "SELECT pin FROM tbl_pin WHERE pin = ?", [$new_pin], "row");
            if ($checkPin) {
                $error_message = "PIN '$new_pin' already exists in the database";
            }
        }
        
        if (empty($error_message)) {
            // Begin transaction
            $DBH->beginTransaction();
            
            try {
                // Update PIN information
                $updateQuery = "UPDATE tbl_pin SET 
                                pin = ?,
                                Serial = ?,
                                batch_id = ?,
                                batch = ?,
                                year = ?,
                                term = ?,
                                class = ?,
                                reg_no = ?,
                                dt_stamp_start = ?,
                                dt_stamp_end = ?,
                                used_count = ?,
                                updated_at = NOW()
                                WHERE pin = ?";
                
                $stmt = $DBH->prepare($updateQuery);
                $result = $stmt->execute([
                    $new_pin,
                    $serial,
                    $batch_id,
                    $batch,
                    $year,
                    $term,
                    $class,
                    $reg_no ?: null,
                    $dt_stamp_start ?: null,
                    $dt_stamp_end ?: null,
                    $used_count,
                    $original_pin
                ]);
                
                if ($result) {
                    $DBH->commit();
                    $success_message = "PIN successfully updated";
                    
                    // Refresh PIN info
                    $pinInfo = sql($DBH, 
                        "SELECT p.*, u.name as student_name, u.class as student_class 
                         FROM tbl_pin p 
                         LEFT JOIN tbl_user u ON p.reg_no = u.reg_no 
                         WHERE p.pin = ?", 
                        [$new_pin], 
                        "row"
                    );
                    
                    // Update URL if PIN changed
                    if ($new_pin != $original_pin) {
                        header("Location: edit_pin.php?pin=" . urlencode($new_pin) . "&success=updated");
                        exit();
                    }
                } else {
                    throw new Exception("Failed to update PIN");
                }
            } catch (Exception $e) {
                $DBH->rollBack();
                $error_message = "Error: " . $e->getMessage();
            }
        }
    }
}

// Handle PIN deletion
if (isset($_GET['delete']) && $_GET['delete'] == '1' && !empty($pin)) {
    $deleteQuery = "DELETE FROM tbl_pin WHERE pin = ?";
    $stmt = $DBH->prepare($deleteQuery);
    
    if ($stmt->execute([$pin])) {
        $_SESSION['success'] = "PIN successfully deleted";
        header("Location: find_student_pin.php");
        exit();
    } else {
        $error_message = "Failed to delete PIN";
    }
}

// Handle PIN reset (mark as unused)
if (isset($_POST['reset_pin']) && !empty($pin)) {
    $resetQuery = "UPDATE tbl_pin SET reg_no = NULL, date_time = NULL, used_count = 0 WHERE pin = ?";
    $stmt = $DBH->prepare($resetQuery);
    
    if ($stmt->execute([$pin])) {
        $success_message = "PIN has been reset and is now unused";
        
        // Refresh PIN info
        $pinInfo = sql($DBH, 
            "SELECT p.*, u.name as student_name, u.class as student_class 
             FROM tbl_pin p 
             LEFT JOIN tbl_user u ON p.reg_no = u.reg_no 
             WHERE p.pin = ?", 
            [$pin], 
            "row"
        );
    } else {
        $error_message = "Failed to reset PIN";
    }
}

// Handle messages from session
if (isset($_GET['success']) && $_GET['success'] == 'updated') {
    $success_message = "PIN successfully updated";
}
?>

<!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>Edit PIN - Henzy Royal International School</title>
  <link rel="icon" type="image/png" href="coll_logo.png">
  
  <!-- 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">
  
  <!-- Google Fonts - Poppins -->
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  
  <!-- Select2 CSS for better dropdowns -->
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
  <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
  
  <!-- Custom CSS -->
  <style>
    :root {
      --primary-blue: #1a4b8c;    /* Royal Blue */
      --secondary-gold: #FFD700;    /* Gold */
      --dark-blue: #0f2b4f;         /* Dark Blue */
      --light-blue: #4a7db5;         /* Medium Blue */
      --light-gold: #FFF1B8;          /* Light Gold */
      --bg-light: #f5f9ff;
    }
    
    body {
      font-family: 'Poppins', sans-serif;
      background-color: var(--bg-light);
      padding-top: 56px;
      color: #333;
      font-size: 0.9rem;
    }
    
    /* Navbar Styles */
    .navbar {
      background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
      box-shadow: 0 0.15rem 1.75rem 0 rgba(26, 75, 140, 0.2);
      position: fixed;
      top: 0;
      width: 100%;
      z-index: 1030;
      color: white;
      border-bottom: 2px solid var(--secondary-gold);
    }
    
    .navbar-brand {
      font-weight: 800;
      font-size: 1.2rem;
      color: white;
      display: flex;
      align-items: center;
    }
    
    .navbar-brand img {
      border-radius: 4px;
      margin-right: 10px;
    }
    
    /* Sidebar Styles */
    .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;
      border-right: 3px solid var(--secondary-gold);
    }
    
    .sidebar .nav-link {
      color: rgba(255, 255, 255, 0.9);
      font-weight: 500;
      padding: 0.75rem 1rem;
      margin-bottom: 0.2rem;
      transition: all 0.2s;
      border-left: 3px solid transparent;
    }
    
    .sidebar .nav-link:hover {
      color: white;
      background-color: rgba(255, 215, 0, 0.15);
      border-left-color: var(--secondary-gold);
    }
    
    .sidebar .nav-link.active {
      color: var(--dark-blue);
      background-color: var(--secondary-gold);
      border-left-color: var(--dark-blue);
      font-weight: 600;
    }
    
    .sidebar .nav-link i {
      margin-right: 0.5rem;
      width: 20px;
      text-align: center;
    }
    
    .sidebar-logo {
      text-align: center;
      margin-bottom: 1rem;
      padding: 1rem;
    }
    
    .logo-text {
      font-size: 1.5rem;
      font-weight: 900;
      color: white;
      letter-spacing: 2px;
      line-height: 1.2;
    }
    
    .logo-text span {
      color: var(--secondary-gold);
    }
    
    .logo-tagline {
      font-size: 0.65rem;
      color: var(--secondary-gold);
      letter-spacing: 1px;
    }
    
    /* Main Content Styles */
    .main-content {
      margin-left: 250px;
      width: calc(100% - 250px);
      transition: all 0.3s;
      min-height: calc(100vh - 56px);
      padding-bottom: 60px;
    }
    
    @media (max-width: 991.98px) {
      .sidebar {
        left: -250px;
      }
      .main-content {
        margin-left: 0;
        width: 100%;
      }
      body {
        padding-top: 56px;
      }
    }
    
    /* Welcome banner */
    .welcome-banner {
      background: linear-gradient(135deg, var(--primary-blue), var(--light-blue));
      color: white;
      border-radius: 0.5rem;
      padding: 0.75rem 1rem;
      margin: 1rem;
      box-shadow: 0 4px 6px rgba(0,0,0,0.1);
      border-left: 5px solid var(--secondary-gold);
    }
    
    /* Form Styles */
    .form-container {
      background-color: white;
      border-radius: 0.5rem;
      padding: 1.5rem;
      margin: 1rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(26, 75, 140, 0.1);
      border: 1px solid rgba(255, 215, 0, 0.2);
    }
    
    /* PIN Display */
    .pin-display-large {
      font-family: 'Courier New', monospace;
      font-size: 2rem;
      font-weight: 700;
      letter-spacing: 4px;
      color: var(--dark-blue);
      background: linear-gradient(135deg, #f5f5f5, #ffffff);
      padding: 1rem 1.5rem;
      border-radius: 0.5rem;
      border: 2px solid var(--secondary-gold);
      display: inline-block;
      margin: 0.5rem 0;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    /* Status badges */
    .badge-status {
      padding: 0.35rem 0.75rem;
      border-radius: 2rem;
      font-size: 0.75rem;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      display: inline-block;
    }
    
    .badge-used {
      background: linear-gradient(135deg, #28a745, #218838);
      color: white;
    }
    
    .badge-unused {
      background: linear-gradient(135deg, #6c757d, #5a6268);
      color: white;
    }
    
    /* Admin Info Styles */
    .admin-info {
      display: flex;
      align-items: center;
      background-color: rgba(255, 215, 0, 0.2);
      padding: 8px 12px;
      border-radius: 8px;
      color: white;
    }
    
    .admin-name {
      margin-right: 5px;
      font-weight: 600;
    }
    
    .admin-access {
      font-style: italic;
      opacity: 0.8;
      margin-right: 10px;
      font-size: 0.9rem;
    }
    
    .admin-icon {
      font-size: 1.5rem;
      color: var(--secondary-gold);
    }
    
    /* Footer styles */
    .footer {
      background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
      color: white;
      padding: 12px 0;
      position: fixed;
      bottom: 0;
      width: 100%;
      z-index: 100;
      font-size: 0.8rem;
      border-top: 2px solid var(--secondary-gold);
    }
    
    @media (min-width: 992px) {
      .footer {
        margin-left: 250px;
        width: calc(100% - 250px);
      }
    }
    
    @media (max-width: 991.98px) {
      .footer {
        margin-left: 0;
        width: 100%;
      }
    }
    
    .copyright-text {
      font-weight: 600;
    }
    
    .copyright-text i {
      color: var(--secondary-gold);
    }
    
    .powered-by {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      color: white;
    }
    
    .powered-by img {
      height: 18px;
      margin-left: 6px;
      filter: brightness(0) invert(1);
    }
    
    .powered-by-link {
      display: flex;
      align-items: center;
      text-decoration: none;
      color: var(--secondary-gold);
      transition: opacity 0.3s ease;
    }
    
    .powered-by-link:hover {
      opacity: 0.8;
      color: white;
    }
    
    /* Support badge */
    .support-badge {
      background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
      color: var(--dark-blue);
      font-weight: 600;
      padding: 0.5rem 1rem;
      border: 1px solid var(--dark-blue);
    }
    
    /* Breadcrumbs */
    .breadcrumb-custom .breadcrumb {
      background-color: transparent;
      padding: 0;
      margin: 1rem 1rem 0;
    }
    
    .breadcrumb-custom .breadcrumb-item a {
      color: var(--primary-blue);
      text-decoration: none;
      font-weight: 500;
    }
    
    .breadcrumb-custom .breadcrumb-item a:hover {
      color: var(--secondary-gold);
    }
    
    .breadcrumb-custom .breadcrumb-item.active {
      color: var(--dark-blue);
      font-weight: 600;
    }
    
    .breadcrumb-item + .breadcrumb-item::before {
      color: var(--secondary-gold);
    }
    
    /* Form elements */
    .form-label {
      font-weight: 600;
      color: var(--dark-blue);
    }
    
    .form-label i {
      color: var(--secondary-gold);
    }
    
    .form-control, .form-select {
      font-size: 0.9rem;
      border: 1px solid #ced4da;
      border-radius: 0.375rem;
    }
    
    .form-control:focus, .form-select:focus {
      border-color: var(--secondary-gold);
      box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
    }
    
    /* Action buttons */
    .btn-action {
      padding: 0.5rem 1rem;
      border-radius: 0.25rem;
      font-weight: 600;
      transition: all 0.3s;
      font-size: 0.85rem;
    }
    
    .btn-primary {
      background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
      border-color: var(--secondary-gold);
      color: white;
    }
    
    .btn-primary:hover {
      background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
      border-color: var(--dark-blue);
      color: var(--dark-blue);
    }
    
    .btn-success {
      background: linear-gradient(135deg, #28a745, #218838);
      border: none;
      color: white;
    }
    
    .btn-success:hover {
      background: linear-gradient(135deg, #218838, #1e7e34);
    }
    
    .btn-danger {
      background: linear-gradient(135deg, #dc3545, #c82333);
      border: none;
      color: white;
    }
    
    .btn-danger:hover {
      background: linear-gradient(135deg, #c82333, #bd2130);
    }
    
    .btn-warning {
      background: linear-gradient(135deg, #ffc107, #e0a800);
      border: none;
      color: var(--dark-blue);
    }
    
    .btn-warning:hover {
      background: linear-gradient(135deg, #e0a800, #c69500);
    }
    
    .btn-secondary {
      background: linear-gradient(135deg, #6c757d, #545b62);
      border: none;
      color: white;
    }
    
    .btn-secondary:hover {
      background: linear-gradient(135deg, #545b62, #3d4247);
    }
    
    /* Alert styles */
    .alert {
      padding: 0.75rem 1rem;
      border-radius: 0.25rem;
      margin: 1rem;
    }
    
    .alert-success {
      background-color: #d4edda;
      border-color: #c3e6cb;
      color: #155724;
    }
    
    .alert-danger {
      background-color: #f8d7da;
      border-color: #f5c6cb;
      color: #721c24;
    }
    
    .alert-warning {
      background-color: #fff3cd;
      border-color: #ffeaa7;
      color: #856404;
    }
    
    .alert-info {
      background-color: #d1ecf1;
      border-color: #bee5eb;
      color: #0c5460;
    }
    
    /* Info card */
    .info-card {
      background: linear-gradient(135deg, var(--light-gold) 0%, #ffffff 100%);
      border-left: 4px solid var(--secondary-gold);
      padding: 1rem;
      margin-bottom: 1.5rem;
      border-radius: 0 0.5rem 0.5rem 0;
      border: 1px solid rgba(255, 215, 0, 0.3);
    }
    
    /* Select2 Customization */
    .select2-container--bootstrap-5 .select2-selection {
      border: 1px solid #ced4da;
      font-size: 0.9rem;
    }
    
    .select2-container--bootstrap-5 .select2-selection--single {
      height: calc(2.25rem + 2px);
    }
    
    .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
      line-height: 2.25rem;
    }
    
    .select2-container--bootstrap-5 .select2-dropdown {
      border-color: var(--secondary-gold);
    }
    
    .select2-container--bootstrap-5 .select2-results__option--selected {
      background-color: var(--light-gold);
      color: var(--dark-blue);
    }
    
    .select2-container--bootstrap-5 .select2-results__option--highlighted {
      background-color: var(--primary-blue);
      color: white;
    }
    
    /* Responsive */
    @media (max-width: 768px) {
      .row {
        flex-direction: column;
      }
      
      .btn {
        width: 100%;
        margin-bottom: 0.5rem;
      }
      
      .pin-display-large {
        font-size: 1.25rem;
        letter-spacing: 2px;
        padding: 0.75rem 1rem;
      }
      
      .btn-group {
        flex-direction: column;
        gap: 0.5rem;
      }
      
      .btn-group .btn {
        border-radius: 0.25rem !important;
        margin: 0;
      }
    }
  </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" style="color: white;"></i>
      </button>
      <a class="navbar-brand d-none d-lg-block" href="#">
        <img src="coll_logo.png" alt="Henzy Royal International School" height="35" style="border-radius: 4px;">
        HENZY ROYAL INT'L SCHOOL
      </a>
      <div class="ms-auto d-flex align-items-center">
        <div class="admin-info me-3">
          <span class="admin-name"><?php echo htmlspecialchars($adminName ?? 'Admin'); ?></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-light">
          <i class="fas fa-sign-out-alt"></i> Logout
        </a>
      </div>
    </div>
  </nav>

  <!-- Sidebar -->
  <nav id="sidebar" class="sidebar">
    <div class="position-sticky pt-3">
      <div class="sidebar-logo d-none d-lg-block">
        <div class="logo-text">
          H.R.<span>I.S</span>
        </div>
        <div class="logo-tagline">
          THE PRIDE OF EXCELLENCE
        </div>
        <hr style="border-color: var(--secondary-gold); opacity: 0.3;">
        <p class="text-white small px-2">
          <i class="fas fa-map-marker-alt" style="color: var(--secondary-gold);"></i><br>
          <?php echo $schoolAddress; ?>
        </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 Dashboard
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="edit_scores_subject.php">
            <i class="fas fa-fw fa-edit"></i>
            Edit Subject Scores
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="download_broadsheet.php">
            <i class="fas fa-fw fa-file-pdf"></i>
            Result Broadsheet
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="list_uploaded_results.php">
            <i class="fas fa-fw fa-list"></i>
            Uploaded Results
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="edit_comments_attendance.php">
            <i class="fas fa-fw fa-comments"></i>
            Attendance & Comments
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="edit_skills.php">
            <i class="fas fa-fw fa-chart-bar"></i>
            Psychomotor Skills
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="find_student_pin.php">
            <i class="fas fa-fw fa-search"></i>
            Find Student's PIN
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="pin_user.php">
            <i class="fas fa-fw fa-check-circle"></i>
            Confirm PIN Usage
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="edit_pin.php">
            <i class="fas fa-fw fa-edit"></i>
            Edit PIN
          </a>
        </li>
      </ul>
    </div>
  </nav>

  <!-- Main Content -->
  <main class="main-content">
    <!-- Welcome Banner -->
    <div class="welcome-banner">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h4 class="mb-1"><i class="fas fa-crown me-2" style="color: var(--secondary-gold);"></i>Edit PIN Information</h4>
          <p class="mb-0 small">Henzy Royal International School - Admin Dashboard</p>
        </div>
        <div class="d-none d-sm-inline-block">
          <span class="badge support-badge p-1">
            <i class="fas fa-edit me-1"></i> PIN Management
          </span>
        </div>
      </div>
    </div>

    <!-- Breadcrumbs -->
    <div class="breadcrumb-custom">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="main.php">Admin Dashboard</a></li>
          <li class="breadcrumb-item"><a href="find_student_pin.php">Find Student PIN</a></li>
          <li class="breadcrumb-item active">Edit PIN</li>
        </ol>
      </nav>
    </div>

    <?php if ($error_message): ?>
      <div class="alert alert-danger">
        <i class="fas fa-exclamation-circle me-2"></i> <?php echo htmlspecialchars($error_message); ?>
      </div>
    <?php endif; ?>
    
    <?php if ($success_message): ?>
      <div class="alert alert-success">
        <i class="fas fa-check-circle me-2"></i> <?php echo htmlspecialchars($success_message); ?>
      </div>
    <?php endif; ?>
    
    <?php if ($warning_message): ?>
      <div class="alert alert-warning">
        <i class="fas fa-exclamation-triangle me-2"></i> <?php echo htmlspecialchars($warning_message); ?>
      </div>
    <?php endif; ?>

    <?php if (empty($pin)): ?>
      <!-- PIN Search Form -->
      <div class="form-container">
        <h5 class="mb-3"><i class="fas fa-search me-2" style="color: var(--secondary-gold);"></i>Search for PIN to Edit</h5>
        <form method="GET" action="">
          <div class="row">
            <div class="col-md-8">
              <div class="form-group mb-2">
                <label for="pin" class="form-label"><i class="fas fa-key me-1"></i>Enter PIN:</label>
                <input type="text" class="form-control" id="pin" name="pin" 
                       placeholder="Enter PIN code to edit" required>
              </div>
            </div>
            <div class="col-md-4">
              <button type="submit" class="btn btn-primary btn-action w-100 mt-4">
                <i class="fas fa-search me-1"></i> Search PIN
              </button>
            </div>
          </div>
        </form>
      </div>
    <?php elseif ($pinInfo): ?>
      <!-- Edit PIN Form -->
      <div class="form-container">
        <form method="POST" action="" onsubmit="return confirm('Are you sure you want to update this PIN?')">
          <input type="hidden" name="original_pin" value="<?php echo htmlspecialchars($pinInfo['pin']); ?>">
          
          <div class="text-center mb-4">
            <h5>Editing PIN</h5>
            <div class="pin-display-large"><?php echo htmlspecialchars($pinInfo['pin']); ?></div>
          </div>
          
          <div class="row">
            <div class="col-md-6 mb-3">
              <label for="pin" class="form-label"><i class="fas fa-key me-1"></i>PIN Code *</label>
              <input type="text" class="form-control" id="pin" name="pin" 
                     value="<?php echo htmlspecialchars($pinInfo['pin']); ?>" 
                     placeholder="Enter PIN code" required 
                     pattern="[A-Za-z0-9-]+" title="PIN can only contain letters, numbers, and hyphens">
              <small class="text-muted">Letters, numbers, and hyphens only</small>
            </div>
            
            <div class="col-md-6 mb-3">
              <label for="serial" class="form-label"><i class="fas fa-barcode me-1"></i>Serial Number</label>
              <input type="text" class="form-control" id="serial" name="serial" 
                     value="<?php echo isset($pinInfo['Serial']) ? htmlspecialchars($pinInfo['Serial']) : ''; ?>" 
                     placeholder="Enter serial number">
            </div>
          </div>
          
          <div class="row">
            <div class="col-md-6 mb-3">
              <label for="batch_id" class="form-label"><i class="fas fa-layer-group me-1"></i>Batch ID</label>
              <select class="form-select" id="batch_id" name="batch_id">
                <option value="">-- Select Batch ID --</option>
                <?php foreach ($batch_ids as $batch_item): ?>
                  <option value="<?php echo htmlspecialchars($batch_item['batch_id']); ?>" 
                    <?php echo ($batch_item['batch_id'] == ($pinInfo['batch_id'] ?? '')) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($batch_item['batch_id']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="col-md-6 mb-3">
              <label for="batch" class="form-label"><i class="fas fa-tag me-1"></i>Batch</label>
              <select class="form-select" id="batch" name="batch">
                <option value="">-- Select Batch --</option>
                <?php foreach ($batches as $batch_item): ?>
                  <option value="<?php echo htmlspecialchars($batch_item['batch']); ?>" 
                    <?php echo ($batch_item['batch'] == ($pinInfo['batch'] ?? '')) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($batch_item['batch']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="row">
            <div class="col-md-4 mb-3">
              <label for="year" class="form-label"><i class="fas fa-calendar me-1"></i>Year</label>
              <select class="form-select" id="year" name="year">
                <option value="">-- Select Year --</option>
                <?php foreach ($years as $year_item): ?>
                  <option value="<?php echo htmlspecialchars($year_item['year']); ?>" 
                    <?php echo ($year_item['year'] == ($pinInfo['year'] ?? '')) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($year_item['year']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="col-md-4 mb-3">
              <label for="term" class="form-label"><i class="fas fa-calendar-alt me-1"></i>Term</label>
              <select class="form-select" id="term" name="term">
                <option value="">-- Select Term --</option>
                <?php foreach ($terms as $term_item): ?>
                  <option value="<?php echo htmlspecialchars($term_item['term']); ?>" 
                    <?php echo ($term_item['term'] == ($pinInfo['term'] ?? '')) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($term_item['term']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="col-md-4 mb-3">
              <label for="class" class="form-label"><i class="fas fa-building me-1"></i>Class</label>
              <select class="form-select" id="class" name="class">
                <option value="">-- Select Class --</option>
                <?php foreach ($classes as $class_item): ?>
                  <option value="<?php echo htmlspecialchars($class_item['class']); ?>" 
                    <?php echo ($class_item['class'] == ($pinInfo['class'] ?? '')) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($class_item['class']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="row">
            <div class="col-md-6 mb-3">
              <label for="reg_no" class="form-label"><i class="fas fa-user-graduate me-1"></i>Assigned Student (Reg No)</label>
              <select class="form-select" id="reg_no" name="reg_no">
                <option value="">-- Unassigned / Not Used --</option>
                <?php foreach ($students as $student): ?>
                  <option value="<?php echo htmlspecialchars($student['reg_no']); ?>" 
                    <?php echo ($student['reg_no'] == ($pinInfo['reg_no'] ?? '')) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($student['name'] . ' (' . $student['reg_no'] . ' - ' . $student['class'] . ')'); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="col-md-3 mb-3">
              <label for="used_count" class="form-label"><i class="fas fa-chart-line me-1"></i>Used Count</label>
              <input type="number" class="form-control" id="used_count" name="used_count" 
                     value="<?php echo intval($pinInfo['used_count'] ?? 0); ?>" 
                     min="0" max="100" step="1">
            </div>
            
            <div class="col-md-3 mb-3">
              <label class="form-label"><i class="fas fa-info-circle me-1"></i>Status</label>
              <div class="pt-2">
                <?php if (!empty($pinInfo['reg_no'])): ?>
                  <span class="badge-status badge-used">Used (<?php echo intval($pinInfo['used_count'] ?? 0); ?> times)</span>
                <?php else: ?>
                  <span class="badge-status badge-unused">Unused</span>
                <?php endif; ?>
              </div>
            </div>
          </div>
          
          <div class="row">
            <div class="col-md-6 mb-3">
              <label for="dt_stamp_start" class="form-label"><i class="fas fa-clock me-1"></i>Valid From Date</label>
              <input type="datetime-local" class="form-control" id="dt_stamp_start" name="dt_stamp_start" 
                     value="<?php echo $pinInfo['dt_stamp_start'] ? date('Y-m-d\TH:i', strtotime($pinInfo['dt_stamp_start'])) : ''; ?>">
            </div>
            
            <div class="col-md-6 mb-3">
              <label for="dt_stamp_end" class="form-label"><i class="fas fa-clock me-1"></i>Valid Until Date</label>
              <input type="datetime-local" class="form-control" id="dt_stamp_end" name="dt_stamp_end" 
                     value="<?php echo $pinInfo['dt_stamp_end'] ? date('Y-m-d\TH:i', strtotime($pinInfo['dt_stamp_end'])) : ''; ?>">
            </div>
          </div>
          
          <div class="row mt-4">
            <div class="col-md-6">
              <button type="submit" name="update_pin" class="btn btn-success btn-action w-100">
                <i class="fas fa-save me-1"></i> Update PIN
              </button>
            </div>
            <div class="col-md-6">
              <a href="find_student_pin.php" class="btn btn-secondary btn-action w-100">
                <i class="fas fa-arrow-left me-1"></i> Back to Search
              </a>
            </div>
          </div>
        </form>
        
        <hr class="my-4">
        
        <!-- Danger Zone -->
        <h6 class="text-danger mb-3"><i class="fas fa-exclamation-triangle me-2"></i>Danger Zone</h6>
        <div class="row">
          <div class="col-md-6">
            <form method="POST" action="" onsubmit="return confirm('Are you sure you want to reset this PIN? It will be marked as unused.')">
              <input type="hidden" name="pin" value="<?php echo htmlspecialchars($pinInfo['pin']); ?>">
              <button type="submit" name="reset_pin" class="btn btn-warning btn-action w-100">
                <i class="fas fa-undo me-1"></i> Reset PIN (Mark as Unused)
              </button>
            </form>
          </div>
          <div class="col-md-6">
            <a href="?delete=1&pin=<?php echo urlencode($pinInfo['pin']); ?>" 
               class="btn btn-danger btn-action w-100"
               onclick="return confirm('⚠️ WARNING: Are you sure you want to permanently delete this PIN?\n\nThis action cannot be undone!')">
              <i class="fas fa-trash-alt me-1"></i> Delete PIN Permanently
            </a>
          </div>
        </div>
      </div>
    <?php endif; ?>
  </main>

  <!-- Footer -->
  <footer class="footer">
    <div class="container-fluid">
      <div class="row align-items-center">
        <div class="col-md-6">
          <span class="copyright-text">
            <i class="fas fa-copyright me-1"></i> <?php echo date("Y"); ?> Henzy Royal International School
          </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 Coders</span>
              <img src="datalogo.png" alt="DataSwift Logo">
            </a>
          </div>
        </div>
      </div>
    </div>
  </footer>

  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  
  <!-- Bootstrap 5 JS Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  
  <!-- Select2 JS -->
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.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');
      document.querySelector('.footer').classList.toggle('active');
    });
    
    // Close sidebar when clicking outside on mobile
    document.addEventListener('click', function(event) {
      const sidebar = document.getElementById('sidebar');
      const sidebarToggle = document.getElementById('sidebarToggle');
      
      if (window.innerWidth < 992 && 
          !sidebar.contains(event.target) && 
          !sidebarToggle.contains(event.target) && 
          sidebar.classList.contains('active')) {
        sidebar.classList.remove('active');
        document.querySelector('.main-content').classList.remove('active');
        document.querySelector('.footer').classList.remove('active');
      }
    });
    
    // Initialize Select2 for better dropdowns
    $(document).ready(function() {
      $('#reg_no').select2({
        theme: 'bootstrap-5',
        placeholder: 'Search for a student...',
        allowClear: true,
        width: '100%'
      });
      
      $('#batch_id').select2({
        theme: 'bootstrap-5',
        placeholder: 'Select or type batch ID',
        allowClear: true,
        tags: true,
        width: '100%'
      });
      
      $('#batch').select2({
        theme: 'bootstrap-5',
        placeholder: 'Select or type batch',
        allowClear: true,
        tags: true,
        width: '100%'
      });
      
      $('#year, #term, #class').select2({
        theme: 'bootstrap-5',
        placeholder: 'Select option',
        allowClear: true,
        width: '100%'
      });
    });
    
    // Auto-hide alerts after 5 seconds
    setTimeout(() => {
      const alerts = document.querySelectorAll('.alert');
      alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => {
          alert.remove();
        }, 500);
      });
    }, 5000);
    
    // Format PIN input
    document.getElementById('pin')?.addEventListener('input', function(e) {
      // Convert to uppercase and remove spaces
      this.value = this.value.replace(/\s/g, '').toUpperCase();
    });
  </script>
</body>
</html>