<?php
// student_actions.php
session_start();
require_once "../includes/db.php";

if (!isset($_SESSION['admin'])) {
    header("Location: index.php");
    exit;
}

$action = $_REQUEST['action'] ?? '';

if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    // --- Update student ---
    $id       = intval($_POST['id'] ?? 0);
    $name     = trim($_POST['name'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if ($id > 0 && $name !== '' && $password !== '') {
        $st = $conn->prepare("UPDATE students SET name=?, password=? WHERE id=?");
        $st->bind_param("ssi", $name, $password, $id);
        $st->execute();
        $st->close();
    }

    header("Location: student_created_list.php?msg=updated");
    exit;

} elseif ($action === 'delete') {
    // --- Delete student ---
    $id = intval($_GET['id'] ?? 0);

    if ($id > 0) {
        $st = $conn->prepare("DELETE FROM students WHERE id=?");
        $st->bind_param("i", $id);
        $st->execute();
        $st->close();
    }

    header("Location: student_created_list.php?msg=deleted");
    exit;

} else {
    // --- Invalid action ---
    header("Location: student_created_list.php?msg=invalid");
    exit;
}
