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

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

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

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

if ($id > 0) {
    $course = $db->get(
        "SELECT c.*, cat.name AS category_name
         FROM courses c
         LEFT JOIN categories cat ON c.category_id = cat.id
         WHERE c.id = ?",
        [$id]
    );
    if (!$course) {
        $_SESSION['flash']['danger'] = 'Course not found.';
        header('Location: courses.php');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title       = trim($_POST['title'] ?? '');
    $slug        = trim($_POST['slug'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $categoryId  = (int)($_POST['category_id'] ?? 0);
    $instructorId= (int)($_POST['instructor_id'] ?? 0);
    $price       = (float)($_POST['price'] ?? 0);
    $currency    = trim($_POST['currency'] ?? 'USD');
    $level       = trim($_POST['level'] ?? 'beginner');
    $status      = trim($_POST['status'] ?? 'draft');

    if ($title === '') {
        $errors[] = 'Title is required.';
    }
    if ($slug === '') {
        $errors[] = 'Slug is required.';
    }
    if ($description === '') {
        $errors[] = 'Description is required.';
    }
    if ($categoryId <= 0) {
        $errors[] = 'Please select a category.';
    }
    if ($instructorId <= 0) {
        $errors[] = 'Please select an instructor.';
    }
    if (!in_array($currency, ['USD','EUR','NGN'], true)) {
        $errors[] = 'Invalid currency.';
    }
    if (!in_array($level, ['beginner','intermediate','advanced'], true)) {
        $errors[] = 'Invalid level.';
    }
    if (!in_array($status, ['published','draft','archived'], true)) {
        $errors[] = 'Invalid status.';
    }

    // Check slug uniqueness
    $existing = $db->get("SELECT id FROM courses WHERE slug = ? AND id != ?", [$slug, $id]);
    if ($existing) {
        $errors[] = 'Slug already exists.';
    }

    if (empty($errors)) {
        try {
            $courseData = [
                'title' => $title,
                'slug' => $slug,
                'description' => $description,
                'category_id' => $categoryId,
                'instructor_id' => $instructorId,
                'price' => $price,
                'currency' => $currency,
                'level' => $level,
                'status' => $status,
                'updated_at' => formatDate(),
            ];

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

if (!$course && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    $course = [
        'title' => '',
        'slug' => '',
        'description' => '',
        'category_id' => 0,
        'instructor_id' => 0,
        'price' => 0,
        'currency' => 'USD',
        'level' => 'beginner',
        'status' => 'draft',
    ];
}

$categories = $db->getAll("SELECT id, name FROM categories ORDER BY name");
$instructors = $db->getAll(
    "SELECT u.id, u.first_name, u.last_name
     FROM users u
     JOIN user_roles ur ON u.id = ur.user_id
     WHERE ur.role = 'instructor' AND u.status = 'active'
     ORDER BY u.last_name, u.first_name"
);

$pageTitle = $id > 0 ? 'Edit Course' : 'Add Course';
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 course details' : 'Create a new course'; ?></p>
  </div>
  <div>
    <a href="courses.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Courses
    </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'] ?? ($course['title'] ?? '')); ?>">
        </div>
        <div class="col-md-4">
          <label for="slug" class="form-label">Slug</label>
          <input type="text" name="slug" id="slug" class="form-control" required value="<?php echo htmlspecialchars($_POST['slug'] ?? ($course['slug'] ?? '')); ?>">
        </div>
      </div>

      <div class="row mb-3">
        <div class="col-md-4">
          <label for="category_id" class="form-label">Category</label>
          <select name="category_id" id="category_id" class="form-select" required>
            <option value="">Select Category</option>
            <?php foreach ($categories as $cat): ?>
              <option value="<?php echo (int)$cat['id']; ?>" <?php echo (($_POST['category_id'] ?? ($course['category_id'] ?? 0)) === $cat['id'] ? 'selected' : ''); ?>><?php echo htmlspecialchars($cat['name']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label for="instructor_id" class="form-label">Instructor</label>
          <select name="instructor_id" id="instructor_id" class="form-select" required>
            <option value="">Select Instructor</option>
            <?php foreach ($instructors as $ins): ?>
              <option value="<?php echo (int)$ins['id']; ?>" <?php echo (($_POST['instructor_id'] ?? ($course['instructor_id'] ?? 0)) === $ins['id'] ? 'selected' : ''); ?>><?php echo htmlspecialchars($ins['first_name'] . ' ' . $ins['last_name']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label for="level" class="form-label">Level</label>
          <select name="level" id="level" class="form-select" required>
            <?php foreach (['beginner','intermediate','advanced'] as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php echo (($_POST['level'] ?? ($course['level'] ?? '')) === $opt ? 'selected' : ''); ?>><?php echo ucfirst($opt); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="row mb-3">
        <div class="col-md-4">
          <label for="price" class="form-label">Price</label>
          <input type="number" name="price" id="price" class="form-control" step="0.01" min="0" value="<?php echo htmlspecialchars($_POST['price'] ?? ($course['price'] ?? 0)); ?>">
        </div>
        <div class="col-md-4">
          <label for="currency" class="form-label">Currency</label>
          <select name="currency" id="currency" class="form-select" required>
            <?php foreach (['USD','EUR','NGN'] as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php echo (($_POST['currency'] ?? ($course['currency'] ?? '')) === $opt ? 'selected' : ''); ?>><?php echo $opt; ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <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'] ?? ($course['status'] ?? '')) === $opt ? 'selected' : ''); ?>><?php echo ucfirst($opt); ?></option>
            <?php endforeach; ?>
          </select>
        </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'] ?? ($course['description'] ?? '')); ?></textarea>
      </div>

      <div class="d-flex justify-content-end gap-2">
        <a href="courses.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'; ?>
