<?php
// public/trainings/enroll.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/flash.php';

require_role('admin','hr','trainer');
verify_csrf();
global $pdo;

$training_id = (int)($_POST['training_id'] ?? 0);
$user_id     = (int)($_POST['user_id'] ?? 0);

if ($training_id <= 0 || $user_id <= 0) {
  set_flash('warning','Invalid request.');
  header('Location: /ldp/public/trainings/index.php'); exit;
}

// Permission: trainers can only manage their own training
$stmt = $pdo->prepare("SELECT trainer_id FROM training WHERE id=?");
$stmt->execute([$training_id]);
$tr = $stmt->fetch();
if (!$tr) { set_flash('warning','Training not found.'); header("Location: /ldp/public/trainings/index.php"); exit; }
if (current_user()['role']==='trainer' && (int)$tr['trainer_id'] !== (int)current_user()['id']) {
  http_response_code(403); exit('Forbidden');
}

try {
  $stmt = $pdo->prepare("INSERT INTO enrollment (training_id, user_id, status) VALUES (?,?, 'enrolled')");
  $stmt->execute([$training_id, $user_id]);
  set_flash('success','Employee enrolled.');
} catch (Throwable $e) {
  // Duplicate enrollment throws error due to UNIQUE KEY
  set_flash('warning','Employee is already enrolled or cannot be added.');
}
header("Location: /ldp/public/trainings/view.php?id=".$training_id);
exit;
