<?php
session_start();

$admin_password = '!S0ngw3av3r1!';
$success = "";
$error = "";
$log = [];

// Admin password gate
if (!isset($_SESSION['is_admin'])) {
    if (!isset($_POST['admin_pass']) || $_POST['admin_pass'] !== $admin_password) {
        echo '<form method="post">
                <label>Enter Admin Password:</label><br>
                <input type="password" name="admin_pass" required>
                <input type="submit" value="Login">
              </form>';
        exit;
    } else {
        $_SESSION['is_admin'] = true;
    }
}

$conn = new mysqli("localhost", "tandddri_admin", "!S0ngw3av3r1!", "tandddri_Students");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get valid sections
$section_result = $conn->query("SELECT label FROM class_sections WHERE is_active = 1 ORDER BY label ASC");
$valid_sections = [];
while ($row = $section_result->fetch_assoc()) {
    $valid_sections[] = $row['label'];
}

// File uploaded?
if (isset($_FILES['csv']) && $_FILES['csv']['error'] === 0) {
    $filename = $_FILES['csv']['tmp_name'];
    if (($handle = fopen($filename, 'r')) !== false) {
        $header = fgetcsv($handle);
        while (($data = fgetcsv($handle)) !== false) {
            $row = array_combine($header, $data);
            $name = trim($row['name']);
            $email = trim($row['email']);
            $ssn_last4 = trim($row['ssn_last4']);
            $class_section = trim($row['class_section']);

            if (!$name || !$email || !$ssn_last4 || !$class_section) {
                $log[] = "❌ Skipped missing fields for: $email";
                continue;
            }

            if (!in_array($class_section, $valid_sections)) {
                $log[] = "❌ Invalid class section '$class_section' for: $email";
                continue;
            }

            $parts = explode(" ", $name);
            $firstInitial = strtolower(substr($parts[0], 0, 1));
            $lastName = strtolower(end($parts));
            $plainPassword = $firstInitial . $lastName . $ssn_last4;
            $hashedPassword = password_hash($plainPassword, PASSWORD_DEFAULT);

            $check = $conn->prepare("SELECT id FROM Students WHERE email = ?");
            $check->bind_param("s", $email);
            $check->execute();
            $check->store_result();
            if ($check->num_rows > 0) {
                $log[] = "⚠️ Duplicate skipped: $email";
                continue;
            }
            $check->close();

            $stmt = $conn->prepare("INSERT INTO Students (email, password, name, class_section) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $email, $hashedPassword, $name, $class_section);
            if ($stmt->execute()) {
                $log[] = "✅ Inserted: $name <$email> into $class_section";
            } else {
                $log[] = "❌ Error inserting $email: " . $stmt->error;
            }
            $stmt->close();
        }
        fclose($handle);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Bulk Upload Students</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background: #f5f5f5;
      padding: 20px;
    }
    .container {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      max-width: 600px;
      margin: auto;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    h2 {
      text-align: center;
    }
    input[type=file], input[type=submit] {
      display: block;
      margin: 15px auto;
    }
    pre {
      background: #eee;
      padding: 10px;
      border-radius: 5px;
      overflow-x: auto;
    }
  </style>
</head>
<body>
  <div class="container">
    <h2>Bulk Upload Students</h2>
    <form method="post" enctype="multipart/form-data">
      <input type="file" name="csv" accept=".csv" required>
      <input type="submit" value="Upload CSV">
    </form>

    <?php if (!empty($log)): ?>
      <h3>Upload Log:</h3>
      <pre><?php echo implode("\n", $log); ?></pre>
    <?php endif; ?>
  </div>
</body>
</html>


