<?php
/**
 * Action: Bulk-create canteen entitlements for all students in a class for today's session.
 */

if (!defined('DB_HOST')) {
    require_once __DIR__ . '/../../config.php';
}
require_once __DIR__ . '/../../includes/canteen_helpers.php';

function action_bulk_create_canteen_entitlements(array $params): array
{
    if (!canteen_is_active()) {
        return ['success' => false, 'error' => 'Canteen module is not active.'];
    }

    $conn       = getDBConnection();
    $class_name = trim((string) ($params['class_name'] ?? ''));
    $today      = date('Y-m-d');

    if ($class_name === '') {
        return ['success' => false, 'error' => 'class_name is required.'];
    }

    // Find today's active/scheduled sessions
    $sess_stmt = $conn->prepare(
        "SELECT id, session_name FROM canteen_sessions
         WHERE school_id = 1 AND session_date = ? AND status IN ('scheduled','active')
         ORDER BY start_time ASC"
    );
    $sess_stmt->bind_param('s', $today);
    $sess_stmt->execute();
    $sessions = $sess_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $sess_stmt->close();

    if (empty($sessions)) {
        return ['success' => false, 'error' => "No active sessions found for today ({$today})."];
    }

    // Get students in the class
    $stu_stmt = $conn->prepare(
        "SELECT id FROM students WHERE status = 'active' AND class = ?"
    );
    $stu_stmt->bind_param('s', $class_name);
    $stu_stmt->execute();
    $students = $stu_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stu_stmt->close();

    if (empty($students)) {
        return ['success' => false, 'error' => "No active students found in class '{$class_name}'."];
    }

    $created  = 0;
    $skipped  = 0;
    $expires  = $today . ' 23:59:59';

    $ins = $conn->prepare(
        "INSERT IGNORE INTO canteen_entitlements
            (student_id, session_id, qr_token, qr_token_expires_at, status)
         VALUES (?, ?, ?, ?, 'pending')"
    );

    foreach ($sessions as $sess) {
        $session_id = (int) $sess['id'];
        foreach ($students as $stu) {
            $student_id = (int) $stu['id'];
            $token = canteen_generate_session_token($student_id, $session_id);

            $ins->bind_param('iiss', $student_id, $session_id, $token, $expires);
            $ins->execute();
            if ($conn->affected_rows > 0) {
                $created++;
            } else {
                $skipped++;
            }
        }

        // Update session total_enrolled
        $conn->query(
            "UPDATE canteen_sessions SET total_enrolled =
                (SELECT COUNT(*) FROM canteen_entitlements WHERE session_id = {$session_id})
             WHERE id = {$session_id}"
        );
    }
    $ins->close();

    $session_names = implode(', ', array_column($sessions, 'session_name'));
    return [
        'success'       => true,
        'class_name'    => $class_name,
        'sessions'      => $session_names,
        'students_found'=> count($students),
        'created'       => $created,
        'skipped'       => $skipped,
        'message'       => "Created {$created} entitlement(s) for {$class_name} — sessions: {$session_names}. {$skipped} already existed.",
    ];
}
