<?php
// public/trainings/delete.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;
$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) { set_flash('warning','Invalid request.'); header('Location: /ldp/public/trainings/index.php'); exit; }

// Only allow trainer to delete if they own it
$stmt = $pdo->prepare("SELECT trainer_id FROM training WHERE id=?");
$stmt->execute([$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 {
  $pdo->prepare("DELETE FROM training WHERE id=?")->execute([$id]);
  set_flash('success','Training deleted.');
} catch (Throwable $e) {
  set_flash('danger','Unable to delete training.');
}
header('Location: /ldp/public/trainings/index.php');
exit;
