<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();

$course = isset($_GET['course']) ? (int)$_GET['course'] : 0;
$region = isset($_GET['region']) ? trim($_GET['region']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';

$where = [];
$params = [];

if ($course > 0) {
    $where[] = 't.course_id = ?';
    $params[] = $course;
}
if ($region !== '') {
    $where[] = 't.region = ?';
    $params[] = $region;
}
if ($status !== '') {
    $where[] = 't.is_active = ?';
    $params[] = ($status === 'active' ? 1 : 0);
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$templates = $db->getAll(
    "SELECT t.*, c.title AS course_title, u.username AS creator_username
     FROM agreement_templates t
     LEFT JOIN courses c ON t.course_id = c.id
     LEFT JOIN users u ON t.created_by = u.id
     $whereSql
     ORDER BY t.sort_order ASC, t.id DESC",
    $params
);

$courses = $db->getAll("SELECT id, title FROM courses ORDER BY title");

$pageTitle = 'Agreement Templates';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Agreement Templates</h1>
    <p class="text-muted mb-0">Manage reusable training agreement templates used during enrollment.</p>
  </div>
  <div>
    <a href="agreement_templates_edit.php" class="btn btn-primary">
      <i class="fas fa-plus me-2"></i>New Template
    </a>
  </div>
</div>

<div class="card mb-4">
  <div class="card-header">
    <form method="get" class="row g-3">
      <div class="col-sm-4">
        <label class="form-label">Course</label>
        <select name="course" class="form-select">
          <option value="">All</option>
          <?php foreach ($courses as $c): ?>
            <option value="<?php echo (int)$c['id']; ?>" <?php echo $course === (int)$c['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['title']); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Region</label>
        <select name="region" class="form-select">
          <option value="">All</option>
          <?php foreach (['global','usa','europe','africa'] as $r): ?>
            <option value="<?php echo $r; ?>" <?php echo $region === $r ? 'selected' : ''; ?>><?php echo strtoupper($r); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="">All</option>
          <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
          <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
        </select>
      </div>
      <div class="col-sm-2 d-flex align-items-end">
        <button class="btn btn-primary w-100" type="submit">Filter</button>
      </div>
    </form>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped table-hover mb-0">
        <thead>
          <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Course Scope</th>
            <th>Region</th>
            <th>Cohort Type</th>
            <th>Status</th>
            <th>Updated</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$templates): ?>
            <tr><td colspan="7" class="text-center text-muted py-4">No templates found.</td></tr>
          <?php else: foreach ($templates as $t): ?>
            <tr>
              <td><?php echo (int)$t['id']; ?></td>
              <td>
                <strong><?php echo htmlspecialchars($t['title']); ?></strong><br>
                <small class="text-muted"><?php echo htmlspecialchars($t['description'] ?? ''); ?></small>
              </td>
              <td><?php echo $t['course_id'] ? htmlspecialchars($t['course_title'] ?? '') : '<span class="text-muted">All courses</span>'; ?></td>
              <td><?php echo htmlspecialchars(strtoupper($t['region'])); ?></td>
              <td><?php echo $t['cohort_type'] ? htmlspecialchars($t['cohort_type']) : '<span class="text-muted">All</span>'; ?></td>
              <td>
                <span class="badge bg-<?php echo $t['is_active'] ? 'success' : 'secondary'; ?>">
                  <?php echo $t['is_active'] ? 'Active' : 'Inactive'; ?>
                </span>
              </td>
              <td><?php echo htmlspecialchars($t['updated_at']); ?></td>
              <td class="text-nowrap">
                <a href="agreement_templates_edit.php?id=<?php echo (int)$t['id']; ?>" class="btn btn-sm btn-outline-primary">
                  <i class="fas fa-edit"></i>
                </a>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
