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

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

$db = Database::getInstance();
$errors = [];
$success = false;
$assessment = null;

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

if ($id > 0) {
    $assessment = $db->get(
        "SELECT a.*, c.title AS course_title
         FROM assessments a
         LEFT JOIN courses c ON a.course_id = c.id
         WHERE a.id = ?",
        [$id]
    );
    if (!$assessment) {
        $_SESSION['flash']['danger'] = 'Assessment not found.';
        header('Location: assessments.php');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title        = trim($_POST['title'] ?? '');
    $description  = trim($_POST['description'] ?? '');
    $courseId     = (int)($_POST['course_id'] ?? 0);
    $type         = trim($_POST['assessment_type'] ?? 'quiz');
    $status       = trim($_POST['status'] ?? 'draft');
    $passingScore = (int)($_POST['passing_score'] ?? 70);
    $timeLimit    = (int)($_POST['time_limit'] ?? 0);
    $maxAttempts  = (int)($_POST['max_attempts'] ?? 3);

    if ($title === '') {
        $errors[] = 'Title is required.';
    }
    if ($description === '') {
        $errors[] = 'Description is required.';
    }
    if ($courseId <= 0) {
        $errors[] = 'Please select a course.';
    }
    if (!in_array($type, ['quiz','assignment','exam','survey'], true)) {
        $errors[] = 'Invalid assessment type.';
    }
    if (!in_array($status, ['published','draft','archived'], true)) {
        $errors[] = 'Invalid status.';
    }
    if ($passingScore < 0 || $passingScore > 100) {
        $errors[] = 'Passing score must be between 0 and 100.';
    }
    if ($timeLimit < 0) {
        $errors[] = 'Time limit must be 0 or greater.';
    }
    if ($maxAttempts < 1) {
        $errors[] = 'Max attempts must be at least 1.';
    }

    if (empty($errors)) {
        try {
            $assessmentData = [
                'title' => $title,
                'description' => $description,
                'course_id' => $courseId,
                'assessment_type' => $type,
                'status' => $status,
                'passing_score' => $passingScore,
                'time_limit' => $timeLimit,
                'max_attempts' => $maxAttempts,
                'created_by' => $_SESSION['user_id'],
                'updated_at' => formatDate(),
            ];

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

if (!$assessment && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    $assessment = [
        'title' => '',
        'description' => '',
        'course_id' => 0,
        'assessment_type' => 'quiz',
        'status' => 'draft',
        'passing_score' => 70,
        'time_limit' => 0,
        'max_attempts' => 3,
    ];
}

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

$pageTitle = $id > 0 ? 'Edit Assessment' : 'Add Assessment';
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"><?php echo $id > 0 ? 'Update assessment details' : 'Create a new assessment'; ?></p>
  </div>
  <div>
    <a href="assessments.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Assessments
    </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="row mb-3">
        <div class="col-md-8">
          <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'] ?? ($assessment['title'] ?? '')); ?>">
        </div>
        <div class="col-md-4">
          <label for="assessment_type" class="form-label">Type</label>
          <select name="assessment_type" id="assessment_type" class="form-select" required>
            <?php foreach (['quiz','assignment','exam','survey'] as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php echo (($_POST['assessment_type'] ?? ($assessment['assessment_type'] ?? '')) === $opt ? 'selected' : ''); ?>><?php echo ucfirst($opt); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="row mb-3">
        <div class="col-md-6">
          <label for="course_id" class="form-label">Course</label>
          <select name="course_id" id="course_id" class="form-select" required>
            <option value="">Select Course</option>
            <?php foreach ($courses as $c): ?>
              <option value="<?php echo (int)$c['id']; ?>" <?php echo (($_POST['course_id'] ?? ($assessment['course_id'] ?? 0)) === $c['id'] ? 'selected' : ''); ?>><?php echo htmlspecialchars($c['title']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label for="status" class="form-label">Status</label>
          <select name="status" id="status" class="form-select" required>
            <?php foreach (['published','draft','archived'] as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php echo (($_POST['status'] ?? ($assessment['status'] ?? '')) === $opt ? 'selected' : ''); ?>><?php echo ucfirst($opt); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="row mb-3">
        <div class="col-md-4">
          <label for="passing_score" class="form-label">Passing Score (%)</label>
          <input type="number" name="passing_score" id="passing_score" class="form-control" min="0" max="100" required value="<?php echo htmlspecialchars($_POST['passing_score'] ?? ($assessment['passing_score'] ?? 70)); ?>">
        </div>
        <div class="col-md-4">
          <label for="time_limit" class="form-label">Time Limit (minutes, 0 = unlimited)</label>
          <input type="number" name="time_limit" id="time_limit" class="form-control" min="0" value="<?php echo htmlspecialchars($_POST['time_limit'] ?? ($assessment['time_limit'] ?? 0)); ?>">
        </div>
        <div class="col-md-4">
          <label for="max_attempts" class="form-label">Max Attempts</label>
          <input type="number" name="max_attempts" id="max_attempts" class="form-control" min="1" required value="<?php echo htmlspecialchars($_POST['max_attempts'] ?? ($assessment['max_attempts'] ?? 3)); ?>">
        </div>
      </div>

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

      <div class="d-flex justify-content-end gap-2">
        <a href="assessments.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' : 'Create'; ?>
        </button>
      </div>
    </form>
  </div>
</div>

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