<?php
require_once 'db.php';
session_start();

if (!isset($_SESSION['logged_in_user'])) {
    http_response_code(403);
    echo "Not authorized";
    exit;
}

$loggedInUser = $_SESSION['logged_in_user'];

// Validate inputs
$slot = isset($_POST['slot']) ? intval($_POST['slot']) : 0;
$programID = isset($_POST['program_id']) ? trim($_POST['program_id']) : '';

if ($slot < 1 || $slot > 10 || $programID === '') {
    http_response_code(400);
    echo "Invalid data";
    exit;
}

// Save to correct column: program_1, program_2, etc.
$column = "program_$slot";

$stmt = $pdo->prepare("UPDATE users SET $column = ? WHERE user_id = ?");
$success = $stmt->execute([$programID, $loggedInUser]);

if ($success) {
    echo "✅ Saved successfully";
} else {
    http_response_code(500);
    echo "❌ Failed to save";
}
