<?php
session_start();
if (!isset($_SESSION['id_admin'])) {
    header('Location: login_admin.php');
    exit;
}

include 'includes/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['aktiviti_id']) && isset($_POST['kehadiran'])) {
    $aktiviti_id = (int) $_POST['aktiviti_id'];
    $kehadiran_data = $_POST['kehadiran'];

    foreach ($kehadiran_data as $penyertaan_id => $status) {
        $penyertaan_id = (int) $penyertaan_id;
        $status = mysqli_real_escape_string($conn, $status);

        $update_sql = "
            UPDATE penyertaan 
            SET status_kehadiran = '$status' 
            WHERE id = $penyertaan_id AND aktiviti_id = $aktiviti_id
        ";
        mysqli_query($conn, $update_sql) or die("SQL Error: " . mysqli_error($conn));
    }

    $_SESSION['msg'] = "Kehadiran pelajar telah berjaya disimpan!";
    $_SESSION['msg_type'] = "success"; // success, danger, warning
    header("Location: pengurusan_kehadiran.php?aktiviti_id=$aktiviti_id");
    exit;
} else {
    $_SESSION['msg'] = "Tiada data kehadiran untuk disimpan.";
    $_SESSION['msg_type'] = "warning";
    header("Location: pengurusan_kehadiran.php");
    exit;
}
