<?php
try {
    require_once('source/session.php');
    require_once('source/error.php');
    require_once('source/dbconfig.php');
    require_once('source/dbconfig4.php'); // Add central settings
    require_once('source/function.php');
    require_once('source/restrict_admin.php');
    session_start();

    // Get current branch settings from central database
    $branchCode = getCurrentBranchCode();
    $branchSettings = getSchoolSettings($branchCode);

    if ($branchSettings) {
        $schoolName = $branchSettings['branch_name'];
        $schoolAddress = $branchSettings['branch_address'];
        $schoolShortName = $branchSettings['branch_short_name'];
        $schoolMotto = $branchSettings['school_motto'];
        $schoolLogo = $branchSettings['school_logo_path'];
        $schoolPhone = $branchSettings['contact_phone'];
        $schoolEmail = $branchSettings['contact_email'];
        $footerText = $branchSettings['footer_text'];
        $footerCopyright = $branchSettings['footer_copyright'];
    } else {
        // Fallback values if no branch settings found
        $schoolName = "Henzy Royal International School";
        $schoolAddress = "No 17 Amadi Street, Amakohia, Uratta Owerri Imo State Nigeria";
        $schoolShortName = "HRIS";
        $schoolMotto = "THE PRIDE OF EXCELLENCE";
        $schoolLogo = "coll_logo.png";
        $schoolPhone = "+234 803 292 9756";
        $schoolEmail = "support@hris.com.ng";
        $footerText = "THE PRIDE OF EXCELLENCE";
        $footerCopyright = "Copyright © Henzy Royal International School";
    }

    // Get system-wide settings
    $supportPhone = getSystemSetting('support_phone') ?: $schoolPhone;
    $supportEmail = getSystemSetting('support_email') ?: $schoolEmail;
    $developerName = getSystemSetting('developer_name') ?: 'DataSwift Coders';
    $developerWebsite = getSystemSetting('developer_website') ?: 'https://dataswift.com.ng';

    // 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'];
        }
    }

    // Fetch dynamic options for class, term, and year from the database
    $classes = sql($DBH, "SELECT DISTINCT class FROM skills ORDER BY class", [], "rows");
    $terms = sql($DBH, "SELECT DISTINCT term FROM skills ORDER BY term", [], "rows");
    $years = sql($DBH, "SELECT DISTINCT year FROM skills ORDER BY year DESC", [], "rows");
    
    // Fetch teachers for filtering
    $teachers = sql($DBH, "SELECT DISTINCT teacher_no FROM skills ORDER BY teacher_no", [], "rows");

    // Initialize variables
    $class = $_POST['class'] ?? '';
    $term = $_POST['term'] ?? '';
    $year = $_POST['year'] ?? '';
    $teacher_no = $_POST['teacher_no'] ?? '';
    $page_title = '';
    $total_results_count = 0;
    $skills_results = [];

    // Get all branches for branch switcher
    $allBranches = getAllBranches();

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Extract search data from the form
        $class = strip_tags($_POST['class'] ?? '');
        $term = strip_tags($_POST['term'] ?? '');
        $year = strip_tags($_POST['year'] ?? '');
        $teacher_no = strip_tags($_POST['teacher_no'] ?? '');

        // Build WHERE conditions dynamically
        $whereConditions = [];
        $params = [];
        
        if (!empty($class)) {
            $whereConditions[] = "class = ?";
            $params[] = $class;
        }
        
        if (!empty($term)) {
            $whereConditions[] = "term = ?";
            $params[] = $term;
        }
        
        if (!empty($year)) {
            $whereConditions[] = "year = ?";
            $params[] = $year;
        }
        
        if (!empty($teacher_no)) {
            $whereConditions[] = "teacher_no = ?";
            $params[] = $teacher_no;
        }
        
        // Only execute query if we have at least one filter
        if (!empty($whereConditions)) {
            $whereClause = "WHERE " . implode(" AND ", $whereConditions);
            
            // Retrieve skills records from the database based on the search criteria
            $skills_results = sql($DBH, 
                "SELECT id, name, registration_no, class, subclass, year, term, teacher_no,
                        Creativity, Fluency, Honesty, Leadership, 
                        Neatness, Politeness, Punctuality, SelfControl, 
                        SenseOfResponsibility, Sociability, 
                        created_at, updated_at
                 FROM skills 
                 $whereClause 
                 ORDER BY name, registration_no",
                $params, 
                "rows"
            );

            // Set page title
            $page_title = "Psychomotor Skills Management";

            // Count of total records
            $total_results_count = count($skills_results);

            // Handle form submissions for saving all fields
            if (isset($_POST['save_all'])) {
                $ids = $_POST['id'];
                $creativity_values = $_POST['creativity'];
                $fluency_values = $_POST['fluency'];
                $honesty_values = $_POST['honesty'];
                $leadership_values = $_POST['leadership'];
                $neatness_values = $_POST['neatness'];
                $politeness_values = $_POST['politeness'];
                $punctuality_values = $_POST['punctuality'];
                $selfcontrol_values = $_POST['selfcontrol'];
                $senseofresponsibility_values = $_POST['senseofresponsibility'];
                $sociability_values = $_POST['sociability'];

                $success_count = 0;
                $error_messages = [];
                
                foreach ($ids as $index => $id) {
                    $creativity = intval($creativity_values[$index]);
                    $fluency = intval($fluency_values[$index]);
                    $honesty = intval($honesty_values[$index]);
                    $leadership = intval($leadership_values[$index]);
                    $neatness = intval($neatness_values[$index]);
                    $politeness = intval($politeness_values[$index]);
                    $punctuality = intval($punctuality_values[$index]);
                    $selfcontrol = intval($selfcontrol_values[$index]);
                    $senseofresponsibility = intval($senseofresponsibility_values[$index]);
                    $sociability = intval($sociability_values[$index]);
                    
                    // Validate ratings (1-5)
                    $ratings = [
                        $creativity, $fluency, $honesty, $leadership,
                        $neatness, $politeness, $punctuality, $selfcontrol,
                        $senseofresponsibility, $sociability
                    ];
                    
                    $valid_ratings = true;
                    foreach ($ratings as $rating) {
                        if ($rating < 1 || $rating > 5) {
                            $valid_ratings = false;
                            break;
                        }
                    }
                    
                    if ($valid_ratings) {
                        $update_query = "UPDATE skills SET 
                                        Creativity = ?, 
                                        Fluency = ?, 
                                        Honesty = ?, 
                                        Leadership = ?, 
                                        Neatness = ?, 
                                        Politeness = ?, 
                                        Punctuality = ?, 
                                        SelfControl = ?, 
                                        SenseOfResponsibility = ?, 
                                        Sociability = ?,
                                        updated_at = NOW()
                                        WHERE id = ?";
                        
                        $stmt = $DBH->prepare($update_query);
                        if ($stmt->execute([
                            $creativity, $fluency, $honesty, $leadership,
                            $neatness, $politeness, $punctuality, $selfcontrol,
                            $senseofresponsibility, $sociability, $id
                        ])) {
                            $success_count++;
                        } else {
                            $error_messages[] = "Failed to update record ID: $id";
                        }
                    } else {
                        $error_messages[] = "Invalid rating values for record ID: $id (must be 1-5)";
                    }
                }

                if ($success_count > 0 && empty($error_messages)) {
                    $success_message = "Successfully updated $success_count skills records";
                    
                    // Refresh the results
                    $skills_results = sql($DBH, 
                        "SELECT id, name, registration_no, class, subclass, year, term, teacher_no,
                                Creativity, Fluency, Honesty, Leadership, 
                                Neatness, Politeness, Punctuality, SelfControl, 
                                SenseOfResponsibility, Sociability, 
                                created_at, updated_at
                         FROM skills 
                         $whereClause 
                         ORDER BY name, registration_no",
                        $params, 
                        "rows"
                    );
                } elseif (!empty($error_messages)) {
                    $error_message = implode("<br>", $error_messages);
                }
            }

            // Handle form submissions for deleting a record
            if (isset($_POST['delete']) && isset($_POST['delete_id'])) {
                $delete_id = strip_tags($_POST['delete_id']);
                
                // Get student name for confirmation message
                $student_info = sql($DBH, 
                    "SELECT name FROM skills WHERE id = ?", 
                    [$delete_id], 
                    "row"
                );
                
                $delete_query = "DELETE FROM skills WHERE id = ?";
                $stmt = $DBH->prepare($delete_query);
                
                if ($stmt->execute([$delete_id])) {
                    $success_message = "Successfully deleted skills record for: " . ($student_info['name'] ?? 'Unknown Student');
                    
                    // Refresh the results
                    $skills_results = sql($DBH, 
                        "SELECT id, name, registration_no, class, subclass, year, term, teacher_no,
                                Creativity, Fluency, Honesty, Leadership, 
                                Neatness, Politeness, Punctuality, SelfControl, 
                                SenseOfResponsibility, Sociability, 
                                created_at, updated_at
                         FROM skills 
                         $whereClause 
                         ORDER BY name, registration_no",
                        $params, 
                        "rows"
                    );
                    $total_results_count = count($skills_results);
                } else {
                    $error_message = "Failed to delete record";
                }
            }
        }
    }
} catch (PDOException $e) {
    $error_message = "Database Error: " . $e->getMessage();
}
?>

<!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>Psychomotor Skills - <?php echo $schoolName; ?></title>
  <link rel="icon" type="image/png" href="../<?php echo $schoolLogo; ?>">
  
  <!-- 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">
  
  <!-- 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;
      --skills-color: #4caf50;       /* Green for skills */
      --skills-dark: #2e7d32;         /* Dark Green */
      --skills-light: #c8e6c9;        /* Light Green */
    }
    
    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;
    }
    
    /* Branch Badge */
    .branch-badge {
      background: var(--secondary-gold);
      color: var(--dark-blue);
      padding: 0.25rem 0.75rem;
      border-radius: 20px;
      font-size: 0.75rem;
      font-weight: 600;
      display: inline-block;
    }
    
    /* 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(--skills-color), var(--skills-dark));
      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);
    }
    
    /* Branch Switcher */
    .branch-switcher {
      background: rgba(255,255,255,0.1);
      padding: 0.25rem 0.5rem;
      border-radius: 4px;
      margin-left: 1rem;
    }
    
    .branch-switcher select {
      background: white;
      border: 1px solid var(--secondary-gold);
      border-radius: 4px;
      padding: 0.25rem;
      font-size: 0.8rem;
    }
    
    /* Form Styles */
    .form-container {
      background-color: white;
      border-radius: 0.5rem;
      padding: 1rem;
      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);
    }
    
    /* Table Styles */
    .table-container {
      background-color: white;
      border-radius: 0.5rem;
      padding: 1rem;
      margin: 1rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(26, 75, 140, 0.1);
      overflow-x: auto;
      border: 1px solid rgba(255, 215, 0, 0.2);
    }
    
    .skills-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 0.85rem;
    }
    
    .skills-table th,
    .skills-table td {
      padding: 0.75rem;
      border: 1px solid #dee2e6;
      text-align: center;
      vertical-align: middle;
    }
    
    .skills-table th {
      background: linear-gradient(135deg, var(--skills-color), var(--skills-dark));
      color: white;
      font-weight: 600;
      position: sticky;
      top: 0;
      z-index: 10;
    }
    
    .skills-table th i {
      color: var(--secondary-gold);
    }
    
    .skills-table input,
    .skills-table select {
      width: 100%;
      padding: 0.5rem;
      border: 1px solid #ced4da;
      border-radius: 0.25rem;
      font-size: 0.85rem;
      text-align: center;
    }
    
    .skills-table input:focus,
    .skills-table select:focus {
      border-color: var(--secondary-gold);
      box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
      outline: none;
    }
    
    .skills-table .student-name {
      text-align: left;
      font-weight: 600;
      background-color: var(--skills-light);
      position: sticky;
      left: 0;
      z-index: 5;
      min-width: 180px;
    }
    
    .skills-table .skill-col {
      background-color: #f1f8e9;
      min-width: 70px;
    }
    
    .skills-table .skill-col:hover {
      background-color: #e8f5e9;
    }
    
    .skills-table .registration-col {
      background-color: var(--light-gold);
      min-width: 120px;
    }
    
    .skills-table tr:nth-child(even) {
      background-color: #f9f9f9;
    }
    
    .skills-table tr:hover {
      background-color: var(--light-gold);
    }
    
    /* 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);
    }
    
    /* Action buttons */
    .action-buttons {
      display: flex;
      gap: 0.5rem;
      justify-content: center;
    }
    
    .btn-sm {
      padding: 0.25rem 0.5rem;
      font-size: 0.8rem;
      border-radius: 0.25rem;
    }
    
    .btn-edit {
      background: linear-gradient(135deg, #28a745, #218838);
      color: white;
      border: none;
    }
    
    .btn-edit:hover {
      background: linear-gradient(135deg, #218838, #1e7e34);
      transform: translateY(-2px);
    }
    
    .btn-delete {
      background: linear-gradient(135deg, #dc3545, #c82333);
      color: white;
      border: none;
    }
    
    .btn-delete:hover {
      background: linear-gradient(135deg, #c82333, #bd2130);
      transform: translateY(-2px);
    }
    
    .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, var(--skills-color), var(--skills-dark));
      border: none;
    }
    
    .btn-success:hover {
      background: linear-gradient(135deg, var(--skills-dark), #1b5e20);
    }
    
    .btn-secondary {
      background: linear-gradient(135deg, #6c757d, #545b62);
      border: none;
    }
    
    .btn-secondary:hover {
      background: linear-gradient(135deg, #545b62, #3d4247);
    }
    
    .btn-action {
      padding: 0.5rem 1rem;
      border-radius: 0.25rem;
      font-weight: 600;
      transition: all 0.3s;
      font-size: 0.85rem;
    }
    
    /* 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-info {
      background-color: var(--light-gold);
      border-color: var(--secondary-gold);
      color: var(--dark-blue);
    }
    
    /* Info cards */
    .info-card {
      background: linear-gradient(135deg, var(--skills-light) 0%, #ffffff 100%);
      border-left: 4px solid var(--skills-color);
      padding: 0.75rem;
      margin-bottom: 0.5rem;
      border-radius: 0 0.25rem 0.25rem 0;
      color: var(--dark-blue);
    }
    
    .info-card i {
      color: var(--skills-dark);
    }
    
    /* Form elements */
    .form-select, .form-label {
      font-size: 0.85rem;
    }
    
    .form-select:focus {
      border-color: var(--secondary-gold);
      box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
    }
    
    .form-label i {
      color: var(--secondary-gold);
    }
    
    /* Empty state */
    .empty-state {
      text-align: center;
      padding: 2rem;
      color: #6c757d;
    }
    
    .empty-state i {
      font-size: 3rem;
      margin-bottom: 1rem;
      color: var(--skills-color);
    }
    
    .empty-state h5 {
      color: var(--dark-blue);
    }
    
    /* Skills stats */
    .skills-stats {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 1rem;
      margin-bottom: 1rem;
    }
    
    .stat-card {
      background: linear-gradient(135deg, var(--skills-light) 0%, #ffffff 100%);
      padding: 0.75rem;
      border-radius: 0.5rem;
      text-align: center;
      border: 1px solid var(--skills-color);
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .stat-value {
      font-size: 1.8rem;
      font-weight: bold;
      color: var(--skills-dark);
      line-height: 1.2;
    }
    
    .stat-label {
      font-size: 0.8rem;
      color: var(--dark-blue);
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    
    /* Skill rating colors */
    .rating-5 { background-color: #2e7d32; color: white; }
    .rating-4 { background-color: #4caf50; color: white; }
    .rating-3 { background-color: #8bc34a; color: white; }
    .rating-2 { background-color: #ffb74d; color: #333; }
    .rating-1 { background-color: #ff8a65; color: #333; }
    
    select option.rating-5 { background-color: #2e7d32; color: white; }
    select option.rating-4 { background-color: #4caf50; color: white; }
    select option.rating-3 { background-color: #8bc34a; color: white; }
    select option.rating-2 { background-color: #ffb74d; color: #333; }
    select option.rating-1 { background-color: #ff8a65; color: #333; }
    
    /* Rating guide */
    .rating-guide {
      display: flex;
      justify-content: space-around;
      margin-top: 1rem;
      padding: 1rem;
      background: linear-gradient(135deg, #f5f5f5, #ffffff);
      border-radius: 0.5rem;
      border: 1px solid var(--skills-color);
      flex-wrap: wrap;
      gap: 0.5rem;
    }
    
    .rating-item {
      text-align: center;
      padding: 0.5rem;
      min-width: 100px;
    }
    
    .rating-circle {
      width: 35px;
      height: 35px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto 0.5rem;
      font-size: 1rem;
      font-weight: bold;
      border: 2px solid var(--secondary-gold);
    }
    
    .rating-label {
      font-size: 0.8rem;
      font-weight: 600;
      color: var(--dark-blue);
    }
    
    /* Code style */
    code {
      background-color: var(--skills-light);
      color: var(--skills-dark);
      padding: 0.2rem 0.4rem;
      border-radius: 0.25rem;
      font-weight: 600;
    }
    
    /* Page heading */
    .text-gray-800 {
      color: var(--dark-blue);
      font-weight: 700;
    }
    
    /* Responsive */
    @media (max-width: 768px) {
      .row {
        flex-direction: column;
      }
      
      .btn-primary {
        width: 100%;
        margin-top: 0.5rem;
      }
      
      .skills-stats {
        grid-template-columns: repeat(2, 1fr);
        gap: 0.5rem;
      }
      
      .rating-guide {
        flex-direction: column;
        align-items: center;
      }
      
      .rating-item {
        width: 100%;
      }
      
      .skills-table th, .skills-table td {
        font-size: 0.8rem;
        padding: 0.5rem;
      }
    }
  </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="../<?php echo $schoolLogo; ?>" alt="<?php echo $schoolName; ?>" height="35" style="border-radius: 4px;" onerror="this.src='coll_logo.png';">
        <?php echo $schoolShortName ?: substr($schoolName, 0, 20); ?>
      </a>
      
      <!-- Branch Switcher (visible on desktop) -->
      <?php if (count($allBranches) > 1): ?>
      <div class="d-none d-lg-block branch-switcher">
        <form method="get" class="d-flex align-items-center">
          <span class="text-white me-2 small">Branch:</span>
          <select name="branch" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
            <option value="" style="color: #333;">Select</option>
            <?php foreach ($allBranches as $branch): ?>
            <option value="<?php echo $branch['branch_code']; ?>" style="color: #333;" 
                    <?php echo ($branchCode == $branch['branch_code']) ? 'selected' : ''; ?>>
              <?php echo $branch['branch_code']; ?> - <?php echo substr($branch['branch_name'], 0, 10); ?>
            </option>
            <?php endforeach; ?>
          </select>
        </form>
      </div>
      <?php endif; ?>
      
      <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>
          <?php if ($branchCode): ?>
          <span class="branch-badge ms-2"><?php echo strtoupper($branchCode); ?></span>
          <?php endif; ?>
          <i class="fas fa-user-circle admin-icon ms-2"></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">
          <?php 
            $words = explode(' ', $schoolName);
            $initials = '';
            foreach ($words as $word) {
                if (!empty($word)) $initials .= strtoupper(substr($word, 0, 1));
            }
            echo substr($initials, 0, 2) . '.<span>' . (isset($initials[2]) ? substr($initials, 2, 1) : 'S') . '</span>';
          ?>
        </div>
        <div class="logo-tagline">
          <?php echo $schoolMotto; ?>
        </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<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <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<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <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<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <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<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <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<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <i class="fas fa-fw fa-comments"></i>
            Attendance & Comments
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="edit_skills.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <i class="fas fa-fw fa-chart-bar"></i>
            Psychomotor Skills
          </a>
        </li>
        <li class="nav-item mt-3">
          <a class="nav-link" href="portal_settings.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <i class="fas fa-fw fa-cog" style="color: var(--secondary-gold);"></i>
            <span style="color: var(--secondary-gold);">Portal Settings</span>
          </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>Psychomotor Skills Management</h4>
          <p class="mb-0 small"><?php echo $schoolName; ?> - Admin Dashboard</p>
        </div>
        <div class="d-none d-sm-inline-block">
          <span class="badge support-badge p-1">
            <i class="fas fa-brain me-1"></i> Skills Assessment System
          </span>
        </div>
      </div>
    </div>

    <!-- Mobile Branch Switcher (visible only on mobile) -->
    <?php if (count($allBranches) > 1): ?>
    <div class="d-lg-none mb-3 mx-3">
      <div class="card">
        <div class="card-body py-2">
          <form method="get" class="d-flex align-items-center">
            <label class="me-2 mb-0"><i class="fas fa-school"></i></label>
            <select name="branch" class="form-select form-select-sm" onchange="this.form.submit()">
              <option value="">Select Branch</option>
              <?php foreach ($allBranches as $branch): ?>
              <option value="<?php echo $branch['branch_code']; ?>" 
                      <?php echo ($branchCode == $branch['branch_code']) ? 'selected' : ''; ?>>
                <?php echo $branch['branch_name']; ?> (<?php echo $branch['branch_code']; ?>)
              </option>
              <?php endforeach; ?>
            </select>
          </form>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Breadcrumbs -->
    <div class="breadcrumb-custom">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="main.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">Admin Dashboard</a></li>
          <li class="breadcrumb-item active">Psychomotor Skills</li>
        </ol>
      </nav>
    </div>

    <!-- Search Form -->
    <div class="form-container">
      <form method="POST" action="">
        <?php if ($branchCode): ?>
        <input type="hidden" name="branch" value="<?php echo $branchCode; ?>">
        <?php endif; ?>
        
        <div class="row align-items-end">
          <div class="col-md-3">
            <div class="form-group mb-2">
              <label for="class" class="form-label"><i class="fas fa-building me-1"></i>Class:</label>
              <select id="class" name="class" class="form-select form-select-sm">
                <option value="">All Classes</option>
                <?php foreach ($classes as $classOption): ?>
                  <option value="<?php echo htmlspecialchars($classOption['class']); ?>" 
                    <?php echo ($classOption['class'] === $class) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($classOption['class']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="col-md-2">
            <div class="form-group mb-2">
              <label for="term" class="form-label"><i class="fas fa-calendar-alt me-1"></i>Term:</label>
              <select id="term" name="term" class="form-select form-select-sm">
                <option value="">All Terms</option>
                <?php foreach ($terms as $termOption): ?>
                  <option value="<?php echo htmlspecialchars($termOption['term']); ?>" 
                    <?php echo ($termOption['term'] === $term) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($termOption['term']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="col-md-2">
            <div class="form-group mb-2">
              <label for="year" class="form-label"><i class="fas fa-calendar me-1"></i>Academic Year:</label>
              <select id="year" name="year" class="form-select form-select-sm">
                <option value="">All Years</option>
                <?php foreach ($years as $yearOption): ?>
                  <option value="<?php echo htmlspecialchars($yearOption['year']); ?>" 
                    <?php echo ($yearOption['year'] === $year) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($yearOption['year']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="col-md-3">
            <div class="form-group mb-2">
              <label for="teacher_no" class="form-label"><i class="fas fa-chalkboard-teacher me-1"></i>Teacher:</label>
              <select id="teacher_no" name="teacher_no" class="form-select form-select-sm">
                <option value="">All Teachers</option>
                <?php foreach ($teachers as $teacherOption): ?>
                  <option value="<?php echo htmlspecialchars($teacherOption['teacher_no']); ?>" 
                    <?php echo ($teacherOption['teacher_no'] === $teacher_no) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($teacherOption['teacher_no']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="col-md-2">
            <button type="submit" class="btn btn-success btn-sm w-100">
              <i class="fas fa-search me-1"></i> Search Records
            </button>
          </div>
        </div>
      </form>
    </div>

    <?php if (isset($error_message)): ?>
      <div class="alert alert-danger">
        <i class="fas fa-exclamation-circle me-2"></i> <?php echo $error_message; ?>
      </div>
    <?php endif; ?>

    <?php if (isset($success_message)): ?>
      <div class="alert alert-success">
        <i class="fas fa-check-circle me-2"></i> <?php echo $success_message; ?>
      </div>
    <?php endif; ?>

    <?php if (!empty($page_title) && (!empty($class) || !empty($term) || !empty($year) || !empty($teacher_no))): ?>
      <div class="form-container">
        <div class="row">
          <div class="col-md-8">
            <div class="info-card">
              <h6 class="mb-1"><i class="fas fa-edit me-2"></i>Modifying Psychomotor Skills For:</h6>
              <p class="mb-0">
                <?php 
                $filters = [];
                if (!empty($class)) $filters[] = "<strong>Class:</strong> " . htmlspecialchars($class);
                if (!empty($term)) $filters[] = "<strong>Term:</strong> " . htmlspecialchars($term);
                if (!empty($year)) $filters[] = "<strong>Year:</strong> " . htmlspecialchars($year);
                if (!empty($teacher_no)) $filters[] = "<strong>Teacher:</strong> " . htmlspecialchars($teacher_no);
                echo implode(" | ", $filters);
                ?>
                <?php if ($branchCode): ?>
                <span class="branch-badge ms-2"><?php echo strtoupper($branchCode); ?></span>
                <?php endif; ?>
              </p>
            </div>
          </div>
          <div class="col-md-4">
            <div class="info-card">
              <h6 class="mb-1"><i class="fas fa-users me-2"></i>Total Records: <?php echo $total_results_count; ?></h6>
              <p class="mb-0 small">Number of skills records found</p>
            </div>
          </div>
        </div>
        
        <?php if (!empty($skills_results)): 
          // Calculate skills statistics
          $average_ratings = [
            'Creativity' => 0,
            'Fluency' => 0,
            'Honesty' => 0,
            'Leadership' => 0,
            'Neatness' => 0,
            'Politeness' => 0,
            'Punctuality' => 0,
            'SelfControl' => 0,
            'SenseOfResponsibility' => 0,
            'Sociability' => 0
          ];
          
          foreach ($skills_results as $record) {
            foreach ($average_ratings as $skill => $value) {
              $average_ratings[$skill] += intval($record[$skill]);
            }
          }
          
          foreach ($average_ratings as $skill => $value) {
            $average_ratings[$skill] = $total_results_count > 0 ? round($value / $total_results_count, 1) : 0;
          }
        ?>
          <div class="skills-stats">
            <?php foreach ($average_ratings as $skill => $avg): ?>
              <div class="stat-card">
                <div class="stat-value"><?php echo $avg; ?></div>
                <div class="stat-label"><?php echo htmlspecialchars($skill); ?></div>
              </div>
            <?php endforeach; ?>
          </div>
          
          <!-- Rating Guide -->
          <div class="rating-guide">
            <div class="rating-item">
              <div class="rating-circle rating-5">5</div>
              <div class="rating-label">Excellent</div>
            </div>
            <div class="rating-item">
              <div class="rating-circle rating-4">4</div>
              <div class="rating-label">Very Good</div>
            </div>
            <div class="rating-item">
              <div class="rating-circle rating-3">3</div>
              <div class="rating-label">Good</div>
            </div>
            <div class="rating-item">
              <div class="rating-circle rating-2">2</div>
              <div class="rating-label">Fair</div>
            </div>
            <div class="rating-item">
              <div class="rating-circle rating-1">1</div>
              <div class="rating-label">Poor</div>
            </div>
          </div>
        <?php endif; ?>
      </div>
    <?php endif; ?>

    <?php if (!empty($skills_results)): ?>
      <div class="table-container">
        <form method="POST" id="skillsForm">
          <?php if ($branchCode): ?>
          <input type="hidden" name="branch" value="<?php echo $branchCode; ?>">
          <?php endif; ?>
          <input type="hidden" name="class" value="<?php echo htmlspecialchars($class); ?>">
          <input type="hidden" name="term" value="<?php echo htmlspecialchars($term); ?>">
          <input type="hidden" name="year" value="<?php echo htmlspecialchars($year); ?>">
          <input type="hidden" name="teacher_no" value="<?php echo htmlspecialchars($teacher_no); ?>">
          
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0">
              <i class="fas fa-list me-2" style="color: var(--secondary-gold);"></i>
              Student Psychomotor Skills Assessment
              <small class="text-muted">(<?php echo $total_results_count; ?> records)</small>
              <?php if ($branchCode): ?>
              <span class="branch-badge ms-2"><?php echo strtoupper($branchCode); ?></span>
              <?php endif; ?>
            </h5>
            <div>
              <button type="submit" name="save_all" class="btn btn-success btn-sm" onclick="return validateForm()">
                <i class="fas fa-save me-1"></i> Save All Changes
              </button>
              <a href="main.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>" class="btn btn-primary btn-sm ms-2">
                <i class="fas fa-arrow-left me-1"></i> Back to Dashboard
              </a>
            </div>
          </div>
          
          <div class="table-responsive">
            <table class="skills-table">
              <thead>
                <tr>
                  <th width="4%">S/N</th>
                  <th class="student-name"><i class="fas fa-user me-1"></i>Student Name</th>
                  <th class="registration-col"><i class="fas fa-id-card me-1"></i>Reg No</th>
                  <th class="skill-col"><i class="fas fa-building me-1"></i>Class</th>
                  <th class="skill-col"><i class="fas fa-calendar-alt me-1"></i>Term</th>
                  <th class="skill-col"><i class="fas fa-calendar me-1"></i>Year</th>
                  <th class="skill-col" title="Creativity"><i class="fas fa-paint-brush me-1"></i>Creat</th>
                  <th class="skill-col" title="Fluency"><i class="fas fa-comment me-1"></i>Fluen</th>
                  <th class="skill-col" title="Honesty"><i class="fas fa-check-circle me-1"></i>Honest</th>
                  <th class="skill-col" title="Leadership"><i class="fas fa-users-cog me-1"></i>Leader</th>
                  <th class="skill-col" title="Neatness"><i class="fas fa-tshirt me-1"></i>Neat</th>
                  <th class="skill-col" title="Politeness"><i class="fas fa-smile me-1"></i>Polite</th>
                  <th class="skill-col" title="Punctuality"><i class="fas fa-clock me-1"></i>Punct</th>
                  <th class="skill-col" title="Self Control"><i class="fas fa-brain me-1"></i>Self Ctrl</th>
                  <th class="skill-col" title="Sense of Responsibility"><i class="fas fa-tasks me-1"></i>Respons</th>
                  <th class="skill-col" title="Sociability"><i class="fas fa-handshake me-1"></i>Social</th>
                  <th width="8%"><i class="fas fa-cog me-1"></i>Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($skills_results as $index => $record): ?>
                  <tr>
                    <td><?php echo $index + 1; ?></td>
                    <td class="student-name"><?php echo htmlspecialchars($record['name']); ?></td>
                    <td class="registration-col"><?php echo htmlspecialchars($record['registration_no']); ?></td>
                    <td class="skill-col"><?php echo htmlspecialchars($record['class']); ?></td>
                    <td class="skill-col"><?php echo htmlspecialchars($record['term']); ?></td>
                    <td class="skill-col"><?php echo htmlspecialchars($record['year']); ?></td>
                    
                    <!-- Skills ratings as dropdowns -->
                    <?php 
                    $skills_fields = [
                        'Creativity', 'Fluency', 'Honesty', 'Leadership',
                        'Neatness', 'Politeness', 'Punctuality', 'SelfControl',
                        'SenseOfResponsibility', 'Sociability'
                    ];
                    
                    foreach ($skills_fields as $field): 
                        $value = htmlspecialchars($record[$field]);
                        $rating_class = "rating-" . $value;
                    ?>
                      <td class="skill-col">
                        <select name="<?php echo strtolower($field); ?>[]" class="form-select form-select-sm <?php echo $rating_class; ?>" 
                                onchange="updateRatingClass(this)">
                          <option value="1" class="rating-1" <?php echo $value == '1' ? 'selected' : ''; ?>>1 - Poor</option>
                          <option value="2" class="rating-2" <?php echo $value == '2' ? 'selected' : ''; ?>>2 - Fair</option>
                          <option value="3" class="rating-3" <?php echo $value == '3' ? 'selected' : ''; ?>>3 - Good</option>
                          <option value="4" class="rating-4" <?php echo $value == '4' ? 'selected' : ''; ?>>4 - Very Good</option>
                          <option value="5" class="rating-5" <?php echo $value == '5' ? 'selected' : ''; ?>>5 - Excellent</option>
                        </select>
                      </td>
                    <?php endforeach; ?>
                    
                    <td>
                      <input type="hidden" name="id[]" value="<?php echo $record['id']; ?>">
                      <div class="action-buttons">
                        <button type="button" class="btn btn-delete btn-sm" 
                                onclick="confirmDelete(<?php echo $record['id']; ?>, '<?php echo addslashes($record['name']); ?>')"
                                title="Delete Record">
                          <i class="fas fa-trash-alt"></i>
                        </button>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          
          <div class="mt-3">
            <button type="submit" name="save_all" class="btn btn-success btn-action" onclick="return validateForm()">
              <i class="fas fa-save me-1"></i> Save All Changes
            </button>
            <button type="button" class="btn btn-secondary btn-action ms-2" onclick="resetForm()">
              <i class="fas fa-undo me-1"></i> Reset Changes
            </button>
            <button type="button" class="btn btn-primary btn-action ms-2" onclick="exportToCSV()">
              <i class="fas fa-download me-1"></i> Export to CSV
            </button>
          </div>
          
          <!-- Hidden delete form -->
          <input type="hidden" name="delete_id" id="delete_id" value="">
          <input type="hidden" name="delete" id="delete" value="">
        </form>
        
        <div class="mt-3">
          <div class="alert alert-info py-2">
            <h6 class="mb-1"><i class="fas fa-info-circle me-1" style="color: var(--secondary-gold);"></i> Instructions</h6>
            <div class="row small">
              <div class="col-md-6">
                <i class="fas fa-check-circle text-success me-1"></i> Use dropdowns to edit skill ratings (1-5 scale)<br>
                <i class="fas fa-star text-warning me-1"></i> 5=Excellent, 4=Very Good, 3=Good, 2=Fair, 1=Poor
              </div>
              <div class="col-md-6">
                <i class="fas fa-save text-success me-1"></i> Click "Save All Changes" to update all records<br>
                <i class="fas fa-trash-alt text-danger me-1"></i> Use delete button to remove individual records
              </div>
            </div>
          </div>
        </div>
      </div>
    <?php elseif ($_SERVER["REQUEST_METHOD"] == "POST" && empty($skills_results)): ?>
      <div class="form-container empty-state">
        <i class="fas fa-search"></i>
        <h5 class="text-muted">No Records Found</h5>
        <p class="mb-0">There are no skills records for the selected criteria.</p>
      </div>
    <?php else: ?>
      <div class="form-container empty-state">
        <i class="fas fa-chart-bar"></i>
        <h5 class="text-muted">Psychomotor Skills Management</h5>
        <p class="mb-0">Select filters to search for and edit psychomotor skills records.</p>
        <p class="small text-muted mt-2">You can filter by class, term, year, or teacher. Leave filters empty to see all records.</p>
      </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 $footerCopyright; ?> <?php echo date("Y"); ?>
            <?php if ($branchCode): ?>
            <span class="branch-badge ms-2"><?php echo strtoupper($branchCode); ?></span>
            <?php endif; ?>
          </span>
        </div>
        <div class="col-md-6">
          <div class="powered-by">
            <a href="<?php echo $developerWebsite; ?>" target="_blank" rel="noopener noreferrer" class="powered-by-link">
              <span>Powered by <?php echo $developerName; ?></span>
              <img src="datalogo.png" alt="<?php echo $developerName; ?> Logo" onerror="this.style.display='none';">
            </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>
  
  <!-- 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');
      }
    });
    
    // Delete confirmation function
    function confirmDelete(id, name) {
      if (confirm(`Are you sure you want to delete the skills record for:\n\n${name}?\n\nThis action cannot be undone!`)) {
        document.getElementById('delete_id').value = id;
        document.getElementById('delete').value = '1';
        
        // Submit the form
        document.getElementById('skillsForm').submit();
      }
    }
    
    // Reset form function
    function resetForm() {
      if (confirm('Are you sure you want to reset all changes?')) {
        location.reload();
      }
    }
    
    // Update rating class on select change
    function updateRatingClass(select) {
      const value = select.value;
      // Remove all rating classes
      select.className = 'form-select form-select-sm';
      // Add appropriate rating class
      if (value >= 1 && value <= 5) {
        select.classList.add('rating-' + value);
      }
    }
    
    // Validate form before submission
    function validateForm() {
      const selects = document.querySelectorAll('select');
      let isValid = true;
      let errorMessages = [];
      
      selects.forEach((select, index) => {
        const value = parseInt(select.value);
        if (value < 1 || value > 5) {
          errorMessages.push(`Row ${Math.floor(index/10) + 1}: Invalid rating value`);
          isValid = false;
        }
      });
      
      if (!isValid) {
        alert('Validation Errors:\n' + errorMessages.join('\n'));
        return false;
      }
      
      return confirm('Are you sure you want to save all changes?');
    }
    
    // Export to CSV function
    function exportToCSV() {
      const table = document.querySelector('.skills-table');
      let csv = [];
      
      // Get headers
      const headers = [];
      table.querySelectorAll('thead th').forEach(header => {
        if (!header.textContent.includes('Actions')) {
          headers.push(header.textContent.replace(/[^\w\s]/gi, '').trim());
        }
      });
      csv.push(headers.join(','));
      
      // Get data rows (skip action column)
      table.querySelectorAll('tbody tr').forEach(row => {
        const rowData = [];
        row.querySelectorAll('td').forEach((cell, index) => {
          // Skip the last column (Actions)
          if (index < row.cells.length - 1) {
            let text = cell.textContent.trim();
            // Handle select values
            const select = cell.querySelector('select');
            if (select) {
              text = select.options[select.selectedIndex].text;
            }
            // Handle CSV formatting
            if (text.includes(',') || text.includes('"') || text.includes('\n')) {
              text = '"' + text.replace(/"/g, '""') + '"';
            }
            rowData.push(text);
          }
        });
        csv.push(rowData.join(','));
      });
      
      // Create and download CSV file
      const csvContent = csv.join('\n');
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      
      link.setAttribute('href', url);
      link.setAttribute('download', `skills_${new Date().toISOString().slice(0,10)}.csv`);
      link.style.visibility = 'hidden';
      
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
    
    // Focus first input field if records exist
    <?php if (!empty($skills_results)): ?>
      document.addEventListener('DOMContentLoaded', function() {
        const firstSelect = document.querySelector('select');
        if (firstSelect) {
          firstSelect.focus();
        }
      });
    <?php endif; ?>
    
    // 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);
    
    // Initialize rating classes on page load
    document.addEventListener('DOMContentLoaded', function() {
      document.querySelectorAll('select').forEach(select => {
        const value = select.value;
        if (value >= 1 && value <= 5) {
          select.classList.add('rating-' + value);
        }
      });
    });
  </script>
</body>
</html>