<?php
/**
 * Canteen Session Setup AJAX endpoint.
 * POST action: create_session | quick_setup | duplicate_yesterday | copy_last_week | update_status
 */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

require_once '../config.php';
require_once '../includes/canteen_helpers.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Not authenticated.']);
    exit;
}
canteen_require_role(['admin', 'headteacher'], true);
canteen_require_active();

$conn   = getDBConnection();
$action = trim((string) ($_POST['action'] ?? ''));

// ── Helpers ───────────────────────────────────────────────────────────────────

/**
 * Generate entitlements for every student in the given classes who has
 * a feeding/canteen/meal fee payment in the current academic year.
 * Returns the count of entitlements created.
 */
function create_entitlements_for_session(mysqli $conn, int $session_id, array $classes, string $session_date): int
{
    if (empty($classes)) return 0;

    $academic_year = getAcademicYear();
    $count         = 0;
    $expires_at    = $session_date . ' 23:59:59';

    // Placeholders for IN clause
    $placeholders = implode(',', array_fill(0, count($classes), '?'));
    $types        = str_repeat('s', count($classes));

    $sql = "SELECT DISTINCT s.id AS student_id
            FROM students s
            JOIN payments p  ON p.student_id = s.id
            JOIN fee_structures fs ON fs.id = p.fee_structure_id
            WHERE s.status = 'active'
              AND s.class IN ($placeholders)
              AND fs.fee_type REGEXP 'feeding|canteen|meal'
              AND fs.academic_year = ?";

    $stmt = $conn->prepare($sql);
    $bind_types  = $types . 's';
    $bind_values = array_merge($classes, [$academic_year]);
    $stmt->bind_param($bind_types, ...$bind_values);
    $stmt->execute();
    $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    foreach ($students as $row) {
        $student_id = (int) $row['student_id'];
        $qr_token   = canteen_generate_session_token($student_id, $session_id);

        $ins = $conn->prepare(
            'INSERT IGNORE INTO canteen_entitlements
             (student_id, session_id, qr_token, qr_token_expires_at)
             VALUES (?, ?, ?, ?)'
        );
        $ins->bind_param('iiss', $student_id, $session_id, $qr_token, $expires_at);
        $ins->execute();
        if ($ins->affected_rows > 0) $count++;
        $ins->close();
    }

    // Update total_enrolled on the session
    $upd = $conn->prepare(
        'UPDATE canteen_sessions SET total_enrolled = ? WHERE id = ?'
    );
    $upd->bind_param('ii', $count, $session_id);
    $upd->execute();
    $upd->close();

    return $count;
}

/**
 * Insert one canteen_session row and generate its entitlements.
 * Returns ['session_id' => int, 'enrolled' => int] or throws on DB error.
 */
function insert_session(
    mysqli $conn,
    string $session_name,
    string $session_date,
    string $start_time,
    string $end_time,
    float  $price,
    array  $classes
): array {
    $classes_json = json_encode(array_values($classes));
    $created_by   = (int) ($_SESSION['user_id'] ?? 0);

    $stmt = $conn->prepare(
        'INSERT INTO canteen_sessions
         (school_id, session_name, session_date, start_time, end_time,
          price_per_meal, classes_enrolled, status, created_by)
         VALUES (1, ?, ?, ?, ?, ?, ?, \'scheduled\', ?)'
    );
    $stmt->bind_param('ssssdsi', $session_name, $session_date, $start_time, $end_time,
                                 $price, $classes_json, $created_by);
    $stmt->execute();
    $session_id = (int) $conn->insert_id;
    $stmt->close();

    $enrolled = create_entitlements_for_session($conn, $session_id, $classes, $session_date);

    return ['session_id' => $session_id, 'enrolled' => $enrolled];
}

// ── Route ─────────────────────────────────────────────────────────────────────

switch ($action) {

    // ── Create single session ─────────────────────────────────────────────────
    case 'create_session': {
        $session_name = trim((string) ($_POST['session_name'] ?? ''));
        $session_date = trim((string) ($_POST['session_date'] ?? ''));
        $start_time   = trim((string) ($_POST['start_time']   ?? ''));
        $end_time     = trim((string) ($_POST['end_time']     ?? ''));
        $price        = (float) ($_POST['price'] ?? 0);
        $classes      = (array)  ($_POST['classes'] ?? []);

        if (!$session_name || !$session_date || empty($classes)) {
            echo json_encode(['success' => false, 'message' => 'Session name, date and at least one class are required.']);
            exit;
        }
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $session_date)) {
            echo json_encode(['success' => false, 'message' => 'Invalid date format.']);
            exit;
        }
        // Sanitise classes
        $classes = array_map('strval', array_filter(array_map('trim', $classes)));

        $result = insert_session($conn, $session_name, $session_date,
                                 $start_time, $end_time, $price, $classes);

        logActivity($conn, (int)$_SESSION['user_id'], 'canteen_session_create',
            "Session: {$session_name} | Date: {$session_date} | Enrolled: {$result['enrolled']}");

        echo json_encode([
            'success'    => true,
            'message'    => "Session created. {$result['enrolled']} student(s) enrolled.",
            'session_id' => $result['session_id'],
            'enrolled'   => $result['enrolled'],
        ]);
        break;
    }

    // ── Quick Setup: Breakfast + Lunch for today, all active classes ──────────
    case 'quick_setup': {
        $today   = date('Y-m-d');
        $classes = [];
        $res     = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");
        while ($row = $res->fetch_assoc()) $classes[] = $row['class_name'];

        if (empty($classes)) {
            echo json_encode(['success' => false, 'message' => 'No active classes found.']);
            exit;
        }

        $sessions = [
            ['Breakfast', '07:00:00', '08:00:00', 5.00],
            ['Lunch',     '12:00:00', '13:00:00', 7.00],
        ];

        $created  = [];
        $skipped  = [];
        foreach ($sessions as [$name, $start, $end, $price]) {
            // Skip if session with same name already exists today
            $chk = $conn->prepare(
                "SELECT id FROM canteen_sessions WHERE session_name=? AND session_date=? AND school_id=1 LIMIT 1"
            );
            $chk->bind_param('ss', $name, $today);
            $chk->execute();
            $exists = $chk->get_result()->fetch_assoc();
            $chk->close();

            if ($exists) { $skipped[] = $name; continue; }

            $result    = insert_session($conn, $name, $today, $start, $end, $price, $classes);
            $created[] = "{$name} ({$result['enrolled']} enrolled)";
        }

        $msg = empty($created)
            ? 'All sessions for today already exist.'
            : 'Created: ' . implode(', ', $created) . (empty($skipped) ? '' : '. Skipped (already exist): ' . implode(', ', $skipped) . '.');

        logActivity($conn, (int)$_SESSION['user_id'], 'canteen_quick_setup', $msg);
        echo json_encode(['success' => true, 'message' => $msg, 'created' => count($created)]);
        break;
    }

    // ── Duplicate yesterday's sessions to today ───────────────────────────────
    case 'duplicate_yesterday': {
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $today     = date('Y-m-d');

        $stmt = $conn->prepare(
            "SELECT session_name, start_time, end_time, price_per_meal, classes_enrolled
             FROM canteen_sessions
             WHERE session_date = ? AND school_id = 1 AND status != 'cancelled'"
        );
        $stmt->bind_param('s', $yesterday);
        $stmt->execute();
        $yesterday_sessions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        if (empty($yesterday_sessions)) {
            echo json_encode(['success' => false, 'message' => 'No sessions found for yesterday.']);
            exit;
        }

        $created = [];
        foreach ($yesterday_sessions as $s) {
            $classes = json_decode($s['classes_enrolled'] ?? '[]', true) ?: [];
            // Skip if already exists today
            $chk = $conn->prepare(
                "SELECT id FROM canteen_sessions WHERE session_name=? AND session_date=? AND school_id=1 LIMIT 1"
            );
            $chk->bind_param('ss', $s['session_name'], $today);
            $chk->execute();
            if ($chk->get_result()->fetch_assoc()) { $chk->close(); continue; }
            $chk->close();

            $result    = insert_session($conn, $s['session_name'], $today,
                                        $s['start_time'] ?? '', $s['end_time'] ?? '',
                                        (float)($s['price_per_meal'] ?? 0), $classes);
            $created[] = $s['session_name'];
        }

        $msg = empty($created) ? 'All sessions already exist for today.' : count($created) . ' session(s) duplicated from yesterday.';
        logActivity($conn, (int)$_SESSION['user_id'], 'canteen_duplicate_sessions', $msg);
        echo json_encode(['success' => true, 'message' => $msg, 'created' => count($created)]);
        break;
    }

    // ── Copy from last week (same weekday) ────────────────────────────────────
    case 'copy_last_week': {
        $last_week = date('Y-m-d', strtotime('-7 days'));
        $today     = date('Y-m-d');

        $stmt = $conn->prepare(
            "SELECT session_name, start_time, end_time, price_per_meal, classes_enrolled
             FROM canteen_sessions
             WHERE session_date = ? AND school_id = 1 AND status != 'cancelled'"
        );
        $stmt->bind_param('s', $last_week);
        $stmt->execute();
        $last_sessions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        if (empty($last_sessions)) {
            echo json_encode(['success' => false, 'message' => 'No sessions found for this day last week.']);
            exit;
        }

        $created = [];
        foreach ($last_sessions as $s) {
            $classes = json_decode($s['classes_enrolled'] ?? '[]', true) ?: [];
            $chk = $conn->prepare(
                "SELECT id FROM canteen_sessions WHERE session_name=? AND session_date=? AND school_id=1 LIMIT 1"
            );
            $chk->bind_param('ss', $s['session_name'], $today);
            $chk->execute();
            if ($chk->get_result()->fetch_assoc()) { $chk->close(); continue; }
            $chk->close();

            $result    = insert_session($conn, $s['session_name'], $today,
                                        $s['start_time'] ?? '', $s['end_time'] ?? '',
                                        (float)($s['price_per_meal'] ?? 0), $classes);
            $created[] = $s['session_name'];
        }

        $msg = empty($created) ? 'All sessions already exist for today.' : count($created) . ' session(s) copied from last week.';
        logActivity($conn, (int)$_SESSION['user_id'], 'canteen_copy_last_week', $msg);
        echo json_encode(['success' => true, 'message' => $msg, 'created' => count($created)]);
        break;
    }

    // ── Update session status ─────────────────────────────────────────────────
    case 'update_status': {
        $session_id = (int) ($_POST['session_id'] ?? 0);
        $new_status = trim((string) ($_POST['status'] ?? ''));
        $allowed    = ['scheduled', 'active', 'closed', 'cancelled'];

        if ($session_id <= 0 || !in_array($new_status, $allowed, true)) {
            echo json_encode(['success' => false, 'message' => 'Invalid session or status.']);
            exit;
        }

        $stmt = $conn->prepare("UPDATE canteen_sessions SET status = ? WHERE id = ? AND school_id = 1");
        $stmt->bind_param('si', $new_status, $session_id);
        $stmt->execute();
        $affected = $stmt->affected_rows;
        $stmt->close();

        if ($affected === 0) {
            echo json_encode(['success' => false, 'message' => 'Session not found.']);
            exit;
        }

        logActivity($conn, (int)$_SESSION['user_id'], 'canteen_session_status',
            "Session #{$session_id} → {$new_status}");
        echo json_encode(['success' => true, 'message' => "Status updated to {$new_status}."]);
        break;
    }

    default:
        echo json_encode(['success' => false, 'message' => 'Unknown action.']);
}
