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

// Initialize variables
$msg = '';
$student_info = [];
$result_data = [];
$reg_no = '';
$term = '';
$examyear = '';
$class = '';

// Get and validate parameters
if(isset($_GET['reg_no'])) {
    $reg_no = $_GET['reg_no'];
    $term = $_GET['term'] ?? '';
    $examyear = $_GET['examyear'] ?? '';
    $class = $_GET['class'] ?? '';
    
    if(empty($reg_no)) {  // Added missing closing parenthesis here
        die("<div class='alert alert-danger'>Error: Admission number cannot be empty</div>");
    }
    
    // Get student info from results table
    $student_info = sql($DBH, "SELECT name, registration_no, class FROM tbl_student_results 
                              WHERE registration_no = ? AND term = ? AND year = ? LIMIT 1", 
                              array($reg_no, $term, $examyear), "row");
    
    // Get all results for this student
    $result_data = sql($DBH, "SELECT * FROM tbl_student_results 
                            WHERE registration_no = ? AND term = ? AND year = ?", 
                            array($reg_no, $term, $examyear), "rows");
    
    if(empty($student_info)) {
        $msg = "<div class='alert alert-danger'>No results found for admission number: $reg_no</div>";
    }
} else {
    $msg = "<div class='alert alert-danger'>No admission number provided</div>";
}

// Process form submission
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($result_data)) {
    $updated = 0;
    
    foreach($_POST['results'] as $result_id => $scores) {
        $test1 = $scores['test1'];
        $test2 = $scores['test2'];
        $project = $scores['project'];
        $exam = $scores['exam'];
        
        // Calculate total
        $total = $test1 + $test2 + $project + $exam;
        
        // Determine grade
        $grade = '';
        if($total <= 39) {
            $grade = 'Poor';
        } elseif($total <= 49) {
            $grade = 'Fair';
        } elseif($total <= 59) {
            $grade = 'Credit';
        } elseif($total <= 69) {
            $grade = 'Good';
        } elseif($total <= 79) {
            $grade = 'Very Good';
        } else {
            $grade = 'Excellent';
        }
        
        // Update the result
        $update = sql($DBH, "UPDATE tbl_student_results SET 
                            test1 = ?, 
                            test2 = ?, 
                            project = ?, 
                            exam = ?, 
                            total = ?,
                            grade = ?
                            WHERE id = ?", 
                            array($test1, $test2, $project, $exam, $total, $grade, $result_id));
        
        if($update) $updated++;
    }
    
    if($updated > 0) {
        // Recalculate positions for the class
        $class = $student_info['class'];
        $rows = sql($DBH, "SELECT id, total FROM tbl_student_results 
                         WHERE class = ? AND term = ? AND year = ?
                         ORDER BY total DESC", 
                         array($class, $term, $examyear), "rows");
        
        $position = 0;
        foreach($rows as $row) {
            $position++;
            sql($DBH, "UPDATE tbl_student_results SET position = ? WHERE id = ?", 
                array($position, $row['id']));
        }
        
        $msg = "<div class='alert alert-success'>$updated results updated successfully!</div>";
        
        // Refresh the data
        $result_data = sql($DBH, "SELECT * FROM tbl_student_results 
                                WHERE registration_no = ? AND term = ? AND year = ?", 
                                array($reg_no, $term, $examyear), "rows");
    } else {
        $msg = "<div class='alert alert-danger'>Failed to update results. Please try again.</div>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>British Learner's College - Edit Results</title>
  <link rel="icon" type="image/png" href="https://bkms.com.ng/portal/coll_admin/sch_logo.jpeg">
  
  <!-- Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  
  <!-- Custom CSS -->
  <style>
    :root {
      --primary-color: #2e7d32;
      --secondary-color: #4caf50;
      --accent-color: #8bc34a;
      --dark-color: #1b5e20;
      --light-color: #f1f8e9;
    }
    
    body {
      font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background-color: var(--light-color);
    }
    
    .card {
      border: none;
      border-radius: 0.5rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
      margin-bottom: 1.5rem;
    }
    
    .card-header {
      background-color: var(--primary-color);
      color: white;
      font-weight: 700;
    }
    
    .btn-primary {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
    }
    
    .btn-primary:hover {
      background-color: var(--dark-color);
      border-color: var(--dark-color);
    }
    
    .student-info {
      background-color: white;
      border-radius: 0.5rem;
      padding: 1.5rem;
      margin-bottom: 1.5rem;
      box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
    }
    
    .result-table th {
      background-color: var(--light-color);
    }
    
    .result-table input {
      max-width: 80px;
      text-align: center;
    }
    
    .support-badge {
      background-color: var(--accent-color);
      color: var(--dark-color);
    }
  </style>
</head>

<body>
  <!-- Top Navigation -->
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <a class="navbar-brand" href="main.php">
        <i class="fas fa-school me-2"></i>BRITISH LEARNER'S COLLEGE
      </a>
      <div class="ms-auto d-flex align-items-center">
        <span class="badge support-badge p-2 me-3">
          <i class="fas fa-phone-alt me-1"></i> Support: 08032929756
        </span>
        <a href="logout.php" class="btn btn-sm btn-outline-danger">
          <i class="fas fa-sign-out-alt"></i> Logout
        </a>
      </div>
    </div>
  </nav>

  <!-- Main Content -->
  <main class="container-fluid py-4">
    <div class="row">
      <div class="col-lg-10 mx-auto">
        <!-- Messages -->
        <?php echo $msg; ?>
        
        <!-- Breadcrumbs -->
        <nav aria-label="breadcrumb" class="mb-4">
          <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="main.php"><i class="fas fa-home"></i> Dashboard</a></li>
            <li class="breadcrumb-item"><a href="upload_results.php">Results Management</a></li>
            <li class="breadcrumb-item active">Edit Results</li>
          </ol>
        </nav>
        
        <?php if(!empty($student_info)) { ?>
        <!-- Student Information -->
        <div class="student-info">
          <div class="row">
            <div class="col-md-12">
              <h3 class="mb-3"><?php echo htmlspecialchars($student_info['name']); ?></h3>
              <div class="row">
                <div class="col-md-4">
                  <p><strong>Admission No:</strong> <?php echo htmlspecialchars($student_info['registration_no']); ?></p>
                  <p><strong>Class:</strong> <?php echo htmlspecialchars($student_info['class']); ?></p>
                </div>
                <div class="col-md-4">
                  <p><strong>Term:</strong> <?php echo htmlspecialchars($term); ?></p>
                  <p><strong>Session:</strong> <?php echo htmlspecialchars($examyear); ?></p>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- Results Form -->
        <div class="card">
          <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-edit me-2"></i>Edit Results</h5>
          </div>
          <div class="card-body">
            <form method="post" action="">
              <div class="table-responsive">
                <table class="table table-bordered result-table">
                  <thead>
                    <tr>
                      <th>Subject</th>
                      <th>Test 1 (20)</th>
                      <th>Test 2 (20)</th>
                      <th>Project (10)</th>
                      <th>Exam (50)</th>
                      <th>Total (100)</th>
                      <th>Grade</th>
                      <th>Position</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php foreach($result_data as $result) { ?>
                    <tr>
                      <td><?php echo htmlspecialchars($result['subject']); ?></td>
                      <td>
                        <input type="number" name="results[<?php echo $result['id']; ?>][test1]" 
                               class="form-control" min="0" max="20" value="<?php echo $result['test1']; ?>" required>
                      </td>
                      <td>
                        <input type="number" name="results[<?php echo $result['id']; ?>][test2]" 
                               class="form-control" min="0" max="20" value="<?php echo $result['test2']; ?>" required>
                      </td>
                      <td>
                        <input type="number" name="results[<?php echo $result['id']; ?>][project]" 
                               class="form-control" min="0" max="10" value="<?php echo $result['project']; ?>" required>
                      </td>
                      <td>
                        <input type="number" name="results[<?php echo $result['id']; ?>][exam]" 
                               class="form-control" min="0" max="50" value="<?php echo $result['exam']; ?>" required>
                      </td>
                      <td class="text-center"><?php echo $result['total']; ?></td>
                      <td class="text-center"><?php echo $result['grade']; ?></td>
                      <td class="text-center"><?php echo $result['position']; ?></td>
                    </tr>
                    <?php } ?>
                  </tbody>
                </table>
              </div>
              
              <div class="text-center mt-4">
                <button type="submit" class="btn btn-primary btn-lg me-3">
                  <i class="fas fa-save me-2"></i>Save Changes
                </button>
                <a href="main_results.php?reg_no=<?php echo $reg_no; ?>&term=<?php echo $term; ?>&class=<?php echo $student_info['class']; ?>&examyear=<?php echo $examyear; ?>" 
                   class="btn btn-outline-secondary btn-lg">
                  <i class="fas fa-eye me-2"></i>View Result
                </a>
              </div>
            </form>
          </div>
        </div>
        <?php } ?>
      </div>
    </div>
  </main>

  <!-- Footer -->
  <footer class="footer py-4 bg-dark text-white">
    <div class="container-fluid">
      <div class="row align-items-center">
        <div class="col-md-6">
          <span class="copyright-text">Copyright &copy; BRITISH LEARNER'S COLLEGE <?php echo date("Y"); ?></span>
        </div>
        <div class="col-md-6 text-md-end">
          <span>Powered by <a href="https://dataswift.com.ng" target="_blank" class="text-white">DataSwift</a></span>
        </div>
      </div>
    </div>
  </footer>

  <!-- Bootstrap 5 JS Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  
  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  
  <!-- Custom Script for automatic calculation -->
  <script>
    $(document).ready(function() {
      // Automatically calculate total when any score changes
      $('input[type="number"]').on('input', function() {
        var row = $(this).closest('tr');
        var test1 = parseFloat(row.find('input[name*="[test1]"]').val()) || 0;
        var test2 = parseFloat(row.find('input[name*="[test2]"]').val()) || 0;
        var project = parseFloat(row.find('input[name*="[project]"]').val()) || 0;
        var exam = parseFloat(row.find('input[name*="[exam]"]').val()) || 0;
        
        var total = test1 + test2 + project + exam;
        row.find('td:eq(5)').text(total.toFixed(1));
        
        // Update grade display
        var grade = '';
        if(total <= 39) {
          grade = 'Poor';
        } else if(total <= 49) {
          grade = 'Fair';
        } else if(total <= 59) {
          grade = 'Credit';
        } else if(total <= 69) {
          grade = 'Good';
        } else if(total <= 79) {
          grade = 'Very Good';
        } else {
          grade = 'Excellent';
        }
        row.find('td:eq(6)').text(grade);
      });
    });
  </script>
</body>
</html>