<?php require_once '../includes/header.php';

$id = $_GET['id'] ?? null;
if (!$id) { header('Location: tutorials.php'); exit; }

$stmt = $pdo->prepare("SELECT * FROM tutorials WHERE id = :id");
$stmt->execute([':id' => $id]);
$tutorial = $stmt->fetch();
if (!$tutorial) {
    setFlash('danger', 'Tutorial not found.');
    header('Location: tutorials.php');
    exit;
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title       = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $youtube_url = trim($_POST['youtube_url'] ?? '');
    $sort_order  = (int)($_POST['sort_order'] ?? 0);
    $is_active   = isset($_POST['is_active']) ? 1 : 0;

    if ($title === '' || $youtube_url === '') $errors[] = 'Title and URL required.';

    // Thumbnail
    $thumbnail = $tutorial['thumbnail'];
    if (!empty($_FILES['thumbnail']['name'])) {
        $newThumb = uploadFile('thumbnail', ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], '../assets/uploads/');
        if ($newThumb === false) {
            $errors[] = 'Thumbnail upload failed.';
        } else {
            if ($thumbnail) deleteFile('../assets/uploads/' . $thumbnail);
            $thumbnail = $newThumb;
        }
    } elseif (isset($_POST['remove_thumbnail']) && $_POST['remove_thumbnail'] == '1') {
        if ($thumbnail) deleteFile('../assets/uploads/' . $thumbnail);
        $thumbnail = null;
    }

    if (empty($errors)) {
        $upd = $pdo->prepare("UPDATE tutorials SET title=:title, description=:desc, youtube_url=:url, thumbnail=:thumb, sort_order=:sort, is_active=:active WHERE id=:id");
        $upd->execute([
            ':title' => $title, ':desc' => $description, ':url' => $youtube_url,
            ':thumb' => $thumbnail, ':sort' => $sort_order, ':active' => $is_active, ':id' => $id
        ]);
        setFlash('success', 'Tutorial updated.');
        header('Location: tutorials.php');
        exit;
    }
}
?>

<h1 class="h2 mb-4">Edit Tutorial</h1>

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

<div class="card shadow-sm">
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <div class="mb-3">
                <label class="form-label">Title *</label>
                <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($_POST['title'] ?? $tutorial['title']) ?>" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Description</label>
                <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($_POST['description'] ?? $tutorial['description']) ?></textarea>
            </div>
            <div class="mb-3">
                <label class="form-label">YouTube URL *</label>
                <input type="url" name="youtube_url" class="form-control" value="<?= htmlspecialchars($_POST['youtube_url'] ?? $tutorial['youtube_url']) ?>" required>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Thumbnail</label>
                    <?php if ($tutorial['thumbnail']): ?>
                        <div class="mb-2">
                            <img src="../assets/uploads/<?= htmlspecialchars($tutorial['thumbnail']) ?>" width="80" class="rounded">
                            <div class="form-check mt-1">
                                <input class="form-check-input" type="checkbox" name="remove_thumbnail" value="1" id="remove_thumbnail">
                                <label class="form-check-label" for="remove_thumbnail">Remove thumbnail</label>
                            </div>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="thumbnail" class="form-control" accept="image/*">
                    <small class="text-muted">Leave empty to keep current</small>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">Sort Order</label>
                    <input type="number" name="sort_order" class="form-control" value="<?= htmlspecialchars($_POST['sort_order'] ?? $tutorial['sort_order']) ?>">
                </div>
                <div class="col-md-3 mb-3 d-flex align-items-end">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_active" id="is_active" <?= (isset($_POST) ? isset($_POST['is_active']) : $tutorial['is_active']) ? 'checked' : '' ?>>
                        <label class="form-check-label" for="is_active">Active</label>
                    </div>
                </div>
            </div>
            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Update Tutorial</button>
            <a href="tutorials.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>