<?php
// public/trainings/unenroll.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;

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

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

// Permission check for trainer
$stmt = $pdo->prepare("SELECT e.training_id, t.trainer_id FROM enrollments e JOIN trainings t ON t.id=e.training_id WHERE e.id=?");
$stmt->execute([$enrollment_id]);
$row = $stmt->fetch();
if (!$row) { set_flash('warning','Enrollment not found.'); header('Location: /ldp/public/trainings/index.php'); exit; }
if (current_user()['role']==='trainer' && (int)$row['trainer_id'] !== (int)current_user()['id']) {
  http_response_code(403); exit('Forbidden');
}

$pdo->prepare("DELETE FROM enrollments WHERE id=?")->execute([$enrollment_id]);
set_flash('success','Participant removed.');
header('Location: /ldp/public/trainings/view.php?id='.$training_id);
exit;
