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

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

$db = Database::getInstance();
$errors = [];

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$template = null;

if ($id > 0) {
    $template = $db->get("SELECT * FROM agreement_templates WHERE id = ?", [$id]);
    if (!$template) {
        $_SESSION['flash']['danger'] = 'Template not found.';
        header('Location: agreement_templates.php');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title       = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $body        = trim($_POST['body'] ?? '');
    $courseId    = (int)($_POST['course_id'] ?? 0);
    $region      = trim($_POST['region'] ?? 'global');
    $cohortType  = trim($_POST['cohort_type'] ?? '');
    $isActive    = isset($_POST['is_active']) ? 1 : 0;
    $sortOrder   = (int)($_POST['sort_order'] ?? 0);

    if ($title === '') {
        $errors[] = 'Title is required.';
    }
    if ($body === '') {
        $errors[] = 'Agreement body is required.';
    }
    if (!in_array($region, ['usa','europe','africa','global'], true)) {
        $errors[] = 'Invalid region.';
    }

    if (empty($errors)) {
        $data = [
            'title' => $title,
            'description' => $description,
            'body' => $body,
            'course_id' => $courseId > 0 ? $courseId : null,
            'region' => $region,
            'cohort_type' => $cohortType !== '' ? $cohortType : null,
            'is_active' => $isActive,
            'sort_order' => $sortOrder,
            'updated_at' => formatDate(),
        ];

        try {
            if ($id > 0) {
                $db->update('agreement_templates', $data, 'id = ?', [$id]);
                $_SESSION['flash']['success'] = 'Template updated successfully.';
            } else {
                $data['created_by'] = getCurrentUserId();
                $data['created_at'] = formatDate();
                $db->insert('agreement_templates', $data);
                $_SESSION['flash']['success'] = 'Template created successfully.';
            }
            header('Location: agreement_templates.php');
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (!$template && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    $template = [
        'title' => '',
        'description' => '',
        'body' => '',
        'course_id' => null,
        'region' => 'global',
        'cohort_type' => null,
        'is_active' => 1,
        'sort_order' => 0,
    ];
}

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

$pageTitle = $id > 0 ? 'Edit Agreement Template' : 'New Agreement Template';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0"><?php echo htmlspecialchars($pageTitle); ?></h1>
    <p class="text-muted mb-0">Define the text and scope of this training agreement template.</p>
  </div>
  <div>
    <a href="agreement_templates.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Templates
    </a>
  </div>
</div>

<?php if (!empty($errors)): ?>
  <div class="alert alert-danger">
    <ul class="mb-0">
      <?php foreach ($errors as $error): ?>
        <li><?php echo htmlspecialchars($error); ?></li>
      <?php endforeach; ?>
    </ul>
  </div>
<?php endif; ?>

<div class="card">
  <div class="card-body">
    <form method="post" action="">
      <div class="mb-3">
        <label for="title" class="form-label">Title</label>
        <input type="text" name="title" id="title" class="form-control" required value="<?php echo htmlspecialchars($_POST['title'] ?? ($template['title'] ?? '')); ?>">
      </div>

      <div class="mb-3">
        <label for="description" class="form-label">Description (optional)</label>
        <textarea name="description" id="description" class="form-control" rows="2"><?php echo htmlspecialchars($_POST['description'] ?? ($template['description'] ?? '')); ?></textarea>
      </div>

      <div class="row mb-3">
        <div class="col-md-6">
          <label for="course_id" class="form-label">Course Scope</label>
          <select name="course_id" id="course_id" class="form-select">
            <option value="">All courses</option>
            <?php foreach ($courses as $c): ?>
              <option value="<?php echo (int)$c['id']; ?>" <?php echo ((int)($_POST['course_id'] ?? ($template['course_id'] ?? 0)) === (int)$c['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['title']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label for="region" class="form-label">Region</label>
          <select name="region" id="region" class="form-select" required>
            <?php foreach (['global','usa','europe','africa'] as $r): ?>
              <option value="<?php echo $r; ?>" <?php echo (($_POST['region'] ?? ($template['region'] ?? 'global')) === $r) ? 'selected' : ''; ?>><?php echo strtoupper($r); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label for="sort_order" class="form-label">Sort Order</label>
          <input type="number" name="sort_order" id="sort_order" class="form-control" value="<?php echo htmlspecialchars((string)($_POST['sort_order'] ?? ($template['sort_order'] ?? 0))); ?>">
        </div>
      </div>

      <div class="mb-3">
        <label for="cohort_type" class="form-label">Cohort Type (optional)</label>
        <input type="text" name="cohort_type" id="cohort_type" class="form-control" value="<?php echo htmlspecialchars($_POST['cohort_type'] ?? ($template['cohort_type'] ?? '')); ?>" placeholder="e.g. evening, weekend, bootcamp">
        <small class="text-muted">If set, this template will only apply to cohorts whose <code>cohort_type</code> matches this value.</small>
      </div>

      <div class="mb-3 form-check">
        <input type="checkbox" name="is_active" id="is_active" class="form-check-input" <?php echo (($_POST['is_active'] ?? ($template['is_active'] ?? 1)) ? 'checked' : ''); ?>>
        <label for="is_active" class="form-check-label">Active</label>
      </div>

      <div class="mb-3">
        <label for="body" class="form-label">Agreement Body</label>
        <textarea name="body" id="body" class="form-control" rows="12" required><?php echo htmlspecialchars($_POST['body'] ?? ($template['body'] ?? '')); ?></textarea>
        <small class="text-muted d-block mt-1">
          You can use placeholders that will be replaced at signing time:
          <code>{{APP_NAME}}</code>, <code>{{STUDENT_NAME}}</code>, <code>{{COURSE_TITLE}}</code>,
          <code>{{COHORT_TITLE}}</code>, <code>{{COHORT_START}}</code>, <code>{{COHORT_END}}</code>, <code>{{COHORT_TYPE}}</code>.
        </small>
      </div>

      <div class="d-flex justify-content-end gap-2">
        <a href="agreement_templates.php" class="btn btn-outline-secondary">Cancel</a>
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-save me-2"></i><?php echo $id > 0 ? 'Update Template' : 'Create Template'; ?>
        </button>
      </div>
    </form>
  </div>
</div>

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