<?php
// public/materials/upload.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/layout.php';
require_once __DIR__.'/../../includes/flash.php';

require_login();
$user = current_user();

// Only admin/hr/trainer can upload
if (!in_array($user['role'], ['admin','hr','trainer'], true)) {
  set_flash('Access denied','danger');
  header("Location: index.php");
  exit;
}

global $pdo;
$trainings = $pdo->query("SELECT id, title FROM trainings ORDER BY title")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $training_id = (int)($_POST['training_id'] ?? 0);
  $title = trim($_POST['title'] ?? '');
  $type = $_POST['type'] ?? '';
  $uploaded_by = $user['id'];

  $file_path = null;
  $video_url = null;

  if ($type === 'pdf' && !empty($_FILES['material']['name'])) {
    $uploadDir = __DIR__ . '/../../uploads/';
    @mkdir($uploadDir, 0777, true);
    $fileName = time().'_'.basename($_FILES['material']['name']);
    $targetPath = $uploadDir.$fileName;
    if (move_uploaded_file($_FILES['material']['tmp_name'], $targetPath)) {
      $file_path = $fileName;
    }
  } elseif ($type === 'video') {
    $video_url = trim($_POST['video_url'] ?? '');
  }

  $stmt = $pdo->prepare("INSERT INTO materials (training_id,title,type,file_path,video_url,uploaded_by) VALUES (?,?,?,?,?,?)");
  $stmt->execute([$training_id,$title,$type,$file_path,$video_url,$uploaded_by]);

  set_flash('Material uploaded successfully','success');
  header("Location: index.php");
  exit;
}

render_header('Upload Material','materials');
?>

<div class="card card-primary">
  <form method="post" enctype="multipart/form-data">
    <div class="card-body">
      <div class="form-group">
        <label>Training</label>
        <select name="training_id" class="form-control" required>
          <option value="">-- Select Training --</option>
          <?php foreach ($trainings as $t): ?>
            <option value="<?= (int)$t['id'] ?>"><?= htmlspecialchars($t['title']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Material Title</label>
        <input type="text" name="title" class="form-control" required>
      </div>
      <div class="form-group">
        <label>Type</label>
        <select name="type" id="type" class="form-control" onchange="toggleInputs()" required>
          <option value="pdf">PDF</option>
          <option value="video">Video</option>
        </select>
      </div>
      <div class="form-group" id="pdfInput">
        <label>Upload PDF</label>
        <input type="file" name="material" class="form-control-file">
      </div>
      <div class="form-group" id="videoInput" style="display:none;">
        <label>Video URL</label>
        <input type="url" name="video_url" class="form-control" placeholder="https://youtube.com/...">
      </div>
    </div>
    <div class="card-footer">
      <button type="submit" class="btn btn-success">Save</button>
      <a href="index.php" class="btn btn-secondary">Cancel</a>
    </div>
  </form>
</div>

<script>
function toggleInputs() {
  var type = document.getElementById('type').value;
  document.getElementById('pdfInput').style.display = (type === 'pdf') ? 'block' : 'none';
  document.getElementById('videoInput').style.display = (type === 'video') ? 'block' : 'none';
}
</script>

<?php render_footer();
