<?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');
    $startDateRaw = trim($_POST['start_date'] ?? '');
    $endDateRaw   = trim($_POST['end_date'] ?? '');

    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','GHS'], 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.';
    }

    $startDate = null;
    $endDate = null;

    if ($startDateRaw !== '') {
        $ts = strtotime($startDateRaw);
        if ($ts === false) {
            $errors[] = 'Invalid start date.';
        } else {
            $startDate = date('Y-m-d', $ts);
        }
    }

    if ($endDateRaw !== '') {
        $ts = strtotime($endDateRaw);
        if ($ts === false) {
            $errors[] = 'Invalid end date.';
        } else {
            $endDate = date('Y-m-d', $ts);
        }
    }

    if ($startDate !== null && $endDate !== null && $endDate < $startDate) {
        $errors[] = 'End date cannot be before start date.';
    }

    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,
                'start_date' => $startDate,
                'end_date' => $endDate,
                'updated_at' => formatDate(),
            ];

            if ($id > 0) {
                $db->update('courses', $courseData, 'id = ?', [$id]);
                $courseId = $id;
                $_SESSION['flash']['success'] = 'Course updated successfully.';
            } else {
                $courseData['created_at'] = formatDate();
                $courseId = $db->insert('courses', $courseData);
                $_SESSION['flash']['success'] = 'Course created successfully.';
            }

            if (!empty($_FILES['thumbnail']['name']) && !empty($courseId)) {
                $uploadDir = __DIR__ . '/../uploads/courses/' . $courseId;
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                $ext = pathinfo($_FILES['thumbnail']['name'], PATHINFO_EXTENSION);
                $filename = 'thumbnail_' . time() . '.' . $ext;
                $target = $uploadDir . '/' . $filename;
                if (move_uploaded_file($_FILES['thumbnail']['tmp_name'], $target)) {
                    $relPath = 'uploads/courses/' . $courseId . '/' . $filename;
                    $db->update('courses', ['thumbnail' => $relPath], 'id = ?', [$courseId]);
                }
            }

            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',
        'start_date' => null,
        'end_date' => null,
    ];
}

$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="" enctype="multipart/form-data">
      <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="start_date" class="form-label">Start Date</label>
          <input type="date" name="start_date" id="start_date" class="form-control" value="<?php echo htmlspecialchars($_POST['start_date'] ?? ($course['start_date'] ?? '')); ?>">
        </div>
        <div class="col-md-4">
          <label for="end_date" class="form-label">End Date</label>
          <input type="date" name="end_date" id="end_date" class="form-control" value="<?php echo htmlspecialchars($_POST['end_date'] ?? ($course['end_date'] ?? '')); ?>">
        </div>
      </div>

      <div class="mb-3">
        <label for="thumbnail" class="form-label">Cover Image</label>
        <input type="file" name="thumbnail" id="thumbnail" class="form-control">
        <?php if (!empty($course['thumbnail'])): ?>
          <?php
            $thumb = $course['thumbnail'];
            $thumbPath = __DIR__ . '/../' . ltrim($thumb, '/');
            $baseUrl = defined('APP_URL') ? rtrim(APP_URL, '/') : '';
            $thumbSrc = (stripos($thumb, 'http') === 0 || strpos($thumb, '/') === 0) ? $thumb : $baseUrl . '/' . ltrim($thumb, '/');
          ?>
          <?php if (file_exists($thumbPath)): ?>
            <img src="<?php echo htmlspecialchars($thumbSrc); ?>" class="img-fluid mt-2" style="max-width: 160px;">
          <?php endif; ?>
        <?php endif; ?>
      </div>

      <div class="row mb-3">
        <div class="col-md-4">
          <label class="form-label">Registration Date</label>
          <?php
            $regRaw = $course['created_at'] ?? null;
            $regDate = $regRaw ? date('Y-m-d', strtotime($regRaw)) : date('Y-m-d');
          ?>
          <input type="text" class="form-control" value="<?php echo htmlspecialchars($regDate); ?>" readonly>
        </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','GHS'] 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'; ?>
