<?php
// public/trainings/index.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();

// Access: admin, hr, trainer can manage; employees can only view list
$canManage = in_array($user['role'], ['admin','hr','trainer'], true);

global $pdo;

$q = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;

$params = [];
$where = '';
if ($q !== '') {
    $where = "WHERE t.title LIKE :q_title OR u.name LIKE :q_name";
    $params[':q_title'] = "%$q%";
    $params[':q_name'] = "%$q%";
  }

// If trainer, show only trainings assigned to them
if ($user['role'] === 'trainer') {
  $where .= ($where ? " AND " : "WHERE ")."t.trainer_id = :tid";
  $params[':tid'] = (int)$user['id'];
}

$sqlCount = "SELECT COUNT(*) AS c
             FROM training t
             LEFT JOIN users u ON u.id = t.trainer_id
             $where";
$stmt = $pdo->prepare($sqlCount);
$stmt->execute($params);
$total = (int)$stmt->fetch()['c'];
$pages = max(1, (int)ceil($total / $perPage));

$sql = "SELECT t.id, t.title, t.schedule,t.date_from,t.date_to, t.created_at,t.traineename, u.name AS trainer_id
        FROM training t
        LEFT JOIN users u ON u.id = t.trainer_id
        $where
        ORDER BY t.schedule DESC, t.id DESC
        LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

render_header('Trainings', 'trainings');
$flash = get_flash();
if ($flash): ?>
  <div class="alert alert-<?= htmlspecialchars($flash['type']) ?>"><?= htmlspecialchars($flash['message']) ?></div>
<?php endif; ?>

<div class="card">
  <div class="card-header d-flex align-items-center">
    <form class="form-inline ml-auto" method="get">
      <div class="input-group">
        <input class="form-control" name="q" placeholder="Search title/trainer" value="<?= htmlspecialchars($q) ?>">
        <div class="input-group-append">
          <button class="btn btn-outline-secondary"><i class="fas fa-search"></i></button>
        </div>
      </div>
    </form>
    <?php if ($canManage): ?>
      <a href="create.php" class="btn btn-primary ml-2"><i class="fas fa-plus"></i> New Training</a>
    <?php endif; ?>
  </div>

  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped mb-0">
        <thead>
          <tr>
            <th style="width:70px;">ID</th>
            <th>Title</th>
			 <th>Trainee</th>
            <th style="width:160px;">Start From Date - Stop Date</th>
            <th>Trainer</th>
            <th style="width:220px;">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="5" class="text-center text-muted p-4">No trainings found.</td></tr>
          <?php else: foreach ($rows as $r): ?>
            <tr>
              <td><?= (int)$r['id'] ?></td>
              <td><?= htmlspecialchars($r['title']) ?></td>
			   <td><?= htmlspecialchars($r['traineename']) ?></td>
              <td><?= htmlspecialchars($r['date_from'] ?: '—') ?> <?= htmlspecialchars($r['date_to'] ?: '—') ?></td>
              <td><?= htmlspecialchars($r['trainer_id'] ?: 'Unassigned') ?></td>
              <td class="data-actions">
                <a class="btn btn-sm btn-outline-info" style="font-size:17px;" href="view.php?id=<?= (int)$r['id'] ?>"><i class="fas fa-eye"></i> Enroll Participants and View</a>
                <?php if ($canManage): ?>
                  <!-- <a class="btn btn-sm btn-outline-primary" href="edit.php?id=<?= (int)$r['id'] ?>"><i class="fas fa-edit"></i> Edit</a> -->
                  <form method="post" action="delete.php" class="d-inline" onsubmit="return confirm('Delete this training?');">
                    <?= csrf_field(); ?>
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i> Delete</button>
                  </form>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <?php if ($pages > 1): ?>
  <div class="card-footer">
    <ul class="pagination mb-0">
      <?php for ($i=1; $i <= $pages; $i++): ?>
        <li class="page-item <?= $i===$page?'active':'' ?>">
          <a class="page-link" href="?<?= http_build_query(['q'=>$q,'page'=>$i]) ?>"><?= $i ?></a>
        </li>
      <?php endfor; ?>
    </ul>
  </div>
  <?php endif; ?>
</div>

<?php render_footer();
