<?php
$db = getDB();

// ---------- Determine action ----------
$action = $_GET['action'] ?? 'list';
if (!in_array($action, ['list', 'create', 'update', 'delete'])) {
    $action = 'list';
}

// ---------- Lesson filter (from query string) ----------
$lesson_id = $_GET['lesson_id'] ?? null;
if ($lesson_id !== null) $lesson_id = intval($lesson_id);

// ---------- Messages ----------
$errors = [];
$success = $_GET['success'] ?? '';

// ---------- Helper: fetch a single flashcard ----------
function getFlashcardById($db, $id): ?array {
    $stmt = $db->prepare("SELECT * FROM flashcards WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

// ---------- Handle DELETE ----------
if ($action === 'delete' && isset($_GET['id'])) {
    $stmt = $db->prepare("DELETE FROM flashcards WHERE id = ?");
    $stmt->bind_param("i", $_GET['id']);
    $stmt->execute();
    $redirect = 'index.php?page=flashcards&success=deleted';
    if ($lesson_id) $redirect .= "&lesson_id=$lesson_id";
    header('Location: ' . $redirect);
    exit;
}

// ---------- Handle CREATE / UPDATE form submission ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($action, ['create', 'update'])) {
    $word           = trim($_POST['word'] ?? '');
    $part_of_speech = trim($_POST['part_of_speech'] ?? '');
    $meaning_en     = trim($_POST['meaning_en'] ?? '');
    $meaning_bn     = trim($_POST['meaning_bn'] ?? '');
    $example        = $_POST['example'] ?? null;
    $synonyms       = $_POST['synonyms'] ?? null;
    $form_lesson_id = intval($_POST['lesson_id'] ?? 0);

    // ---------- Image upload handling ----------
    $image_url = $_POST['existing_image_url'] ?? null; // keep old image if no new upload
    $uploadDir = __DIR__ . '/../uploads/flashcards/';  // server path
    // Dynamically generate the base URL using the current request scheme and host.
    $scheme = (!empty($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http');
    $host   = $_SERVER['HTTP_HOST'];                   // e.g. admin.vocabpanda.com
    $baseImageURL = $scheme . '://' . $host . BASE_URL . 'uploads/flashcards/';

    if (isset($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['image_file'];
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $maxSize = 2 * 1024 * 1024; // 2 MB

        if (!in_array($file['type'], $allowedTypes)) {
            $errors[] = 'Invalid image type. Allowed: JPEG, PNG, GIF, WebP.';
        } elseif ($file['size'] > $maxSize) {
            $errors[] = 'Image size must be less than 2 MB.';
        } else {
            // Generate unique filename
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $newFilename = time() . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
            $destination = $uploadDir . $newFilename;

            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            if (move_uploaded_file($file['tmp_name'], $destination)) {
                $image_url = $baseImageURL . $newFilename; // absolute URL
            } else {
                $errors[] = 'Failed to upload image. Check folder permissions.';
            }
        }
    }

    // Validation
    if ($word === '') {
        $errors[] = 'Word is required.';
    }
    if ($meaning_en === '' && $meaning_bn === '') {
        $errors[] = 'At least one meaning (English or Bangla) is required.';
    }
    if ($form_lesson_id <= 0) {
        $errors[] = 'A lesson must be selected.';
    } else {
        // Check lesson exists
        $check = $db->prepare("SELECT id FROM lessons WHERE id = ?");
        $check->bind_param("i", $form_lesson_id);
        $check->execute();
        if ($check->get_result()->num_rows === 0) {
            $errors[] = 'The selected lesson does not exist.';
        }
    }

    if (empty($errors)) {
        if ($action === 'create') {
            $stmt = $db->prepare("INSERT INTO flashcards (lesson_id, word, part_of_speech, meaning_en, meaning_bn, example, synonyms, image_url) 
                                  VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("isssssss", $form_lesson_id, $word, $part_of_speech, $meaning_en, $meaning_bn, $example, $synonyms, $image_url);
        } elseif ($action === 'update') {
            if (isset($_GET['id'])) {
                $stmt = $db->prepare("UPDATE flashcards SET lesson_id=?, word=?, part_of_speech=?, meaning_en=?, meaning_bn=?, example=?, synonyms=?, image_url=? WHERE id=?");
                $stmt->bind_param("isssssssi", $form_lesson_id, $word, $part_of_speech, $meaning_en, $meaning_bn, $example, $synonyms, $image_url, $_GET['id']);
            } else {
                $errors[] = 'Missing flashcard ID for update.';
            }
        }

        if (isset($stmt)) {
            $stmt->execute();
            $msg = ($action === 'create') ? 'created' : 'updated';
            $redirect = 'index.php?page=flashcards&success=' . $msg;
            if ($lesson_id) $redirect .= "&lesson_id=$lesson_id";
            header('Location: ' . $redirect);
            exit;
        }
    }
}

// ---------- Load existing flashcard for edit ----------
$flashcard = null;
if ($action === 'update' && isset($_GET['id'])) {
    $flashcard = getFlashcardById($db, $_GET['id']);
    if (!$flashcard) {
        echo '<div class="alert alert-danger">Flashcard not found.</div>';
        $action = 'list';
    }
}

// ---------- Success banners ----------
if ($success === 'created') {
    echo '<div class="alert alert-success">Flashcard created successfully.</div>';
} elseif ($success === 'updated') {
    echo '<div class="alert alert-success">Flashcard updated successfully.</div>';
} elseif ($success === 'deleted') {
    echo '<div class="alert alert-success">Flashcard deleted.</div>';
}

// ---------- LIST view ----------
if ($action === 'list'):
    // Fetch lesson name if filtered
    $lessonName = '';
    if ($lesson_id) {
        $lstmt = $db->prepare("SELECT title FROM lessons WHERE id = ?");
        $lstmt->bind_param("i", $lesson_id);
        $lstmt->execute();
        $lres = $lstmt->get_result()->fetch_assoc();
        $lessonName = $lres['title'] ?? '';
    }
?>
    <h3>Flashcards <?= $lesson_id ? 'for lesson: ' . htmlspecialchars($lessonName) . " (ID $lesson_id)" : '' ?></h3>

    <div class="d-flex justify-content-between align-items-center mb-3">
        <form class="d-flex" method="get">
            <input type="hidden" name="page" value="flashcards">
            <?php if ($lesson_id): ?>
                <input type="hidden" name="lesson_id" value="<?= $lesson_id ?>">
            <?php endif; ?>
            <input type="text" name="search" class="form-control me-2" placeholder="Search word..."
                   value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
            <button type="submit" class="btn btn-outline-secondary"><i class="fa fa-search"></i></button>
        </form>
        <a href="?page=flashcards&action=create<?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>" class="btn btn-primary">
            <i class="fa fa-plus me-1"></i> New Flashcard
        </a>
    </div>

    <?php
    // ---------- Pagination & search ----------
    $pageNum = isset($_GET['p']) ? max(1, intval($_GET['p'])) : 1;
    $limit = 50;
    $offset = ($pageNum - 1) * $limit;

    $where = [];
    $params = [];
    $types = '';

    if ($lesson_id) {
        $where[] = "f.lesson_id = ?";
        $params[] = $lesson_id;
        $types .= 'i';
    }
    if (!empty($_GET['search'])) {
        $where[] = "f.word LIKE ?";
        $params[] = "%" . $_GET['search'] . "%";
        $types .= 's';
    }

    $whereSQL = '';
    if (!empty($where)) {
        $whereSQL = 'WHERE ' . implode(' AND ', $where);
    }

    // Count
    $countSQL = "SELECT COUNT(*) FROM flashcards f $whereSQL";
    $stmt = $db->prepare($countSQL);
    if ($params) $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $total = $stmt->get_result()->fetch_row()[0];
    $totalPages = ceil($total / $limit);

    // Fetch flashcards with lesson title
    $sql = "SELECT f.*, l.title AS lesson_title 
            FROM flashcards f 
            JOIN lessons l ON f.lesson_id = l.id 
            $whereSQL 
            ORDER BY f.lesson_id, f.word 
            LIMIT ? OFFSET ?";
    $types .= 'ii';
    $params[] = $limit;
    $params[] = $offset;
    $stmt = $db->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $flashcards = $stmt->get_result();
    ?>

    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead class="table-dark">
                <tr>
                    <th>ID</th>
                    <th>Lesson</th>
                    <th>Word</th>
                    <th>POS</th>
                    <th>Meaning (EN)</th>
                    <th>Meaning (BN)</th>
                    <th>Image</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($flashcards->num_rows > 0): ?>
                <?php while($row = $flashcards->fetch_assoc()): ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['lesson_title']) ?> (<?= $row['lesson_id'] ?>)</td>
                    <td><strong><?= htmlspecialchars($row['word']) ?></strong></td>
                    <td><?= htmlspecialchars($row['part_of_speech'] ?? '') ?></td>
                    <td><?= htmlspecialchars($row['meaning_en']) ?></td>
                    <td><?= htmlspecialchars($row['meaning_bn']) ?></td>
                    <td>
                        <?php if (!empty($row['image_url'])): ?>
                            <img src="<?= htmlspecialchars($row['image_url']) ?>" style="height: 40px;" alt="img">
                        <?php else: ?>
                            —
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="?page=flashcards&action=update&id=<?= $row['id'] ?><?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>" class="btn btn-outline-warning" title="Edit">
                                <i class="fa fa-edit"></i>
                            </a>
                            <a href="?page=flashcards&action=delete&id=<?= $row['id'] ?><?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>"
                               class="btn btn-outline-danger" title="Delete"
                               onclick="return confirm('Delete this flashcard?')">
                                <i class="fa fa-trash"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="8" class="text-center">No flashcards found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <nav>
        <ul class="pagination">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?= $i == $pageNum ? 'active' : '' ?>">
                    <a class="page-link" href="?page=flashcards&p=<?= $i ?>&search=<?= urlencode($_GET['search'] ?? '') ?><?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>">
                        <?= $i ?>
                    </a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
    <?php endif; ?>

<?php
// ---------- CREATE / UPDATE form ----------
else:
    // Build list of lessons for the dropdown
    $lessonList = $db->query("SELECT l.id, l.title, c.title AS course_title FROM lessons l JOIN courses c ON l.course_id = c.id ORDER BY c.sort_order, l.order");
?>
    <h3><?= $action === 'create' ? 'Create New Flashcard' : 'Edit Flashcard' ?></h3>

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

    <form method="post" enctype="multipart/form-data" class="card p-4" style="max-width: 700px;">
        <div class="mb-3">
            <label for="lesson_id" class="form-label">Lesson *</label>
            <select name="lesson_id" id="lesson_id" class="form-select" required>
                <option value="">-- Select a lesson --</option>
                <?php while($l = $lessonList->fetch_assoc()): 
                    $selected = ($flashcard['lesson_id'] ?? $_POST['lesson_id'] ?? $lesson_id ?? '') == $l['id'];
                ?>
                    <option value="<?= $l['id'] ?>" <?= $selected ? 'selected' : '' ?>>
                        <?= htmlspecialchars($l['course_title']) ?> → <?= htmlspecialchars($l['title']) ?> (ID: <?= $l['id'] ?>)
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="mb-3">
            <label for="word" class="form-label">Word *</label>
            <input type="text" name="word" id="word" class="form-control"
                   value="<?= htmlspecialchars($flashcard['word'] ?? $_POST['word'] ?? '') ?>" required>
        </div>

        <div class="mb-3">
            <label for="part_of_speech" class="form-label">Part of speech</label>
            <input type="text" name="part_of_speech" id="part_of_speech" class="form-control" placeholder="e.g. noun, verb"
                   value="<?= htmlspecialchars($flashcard['part_of_speech'] ?? $_POST['part_of_speech'] ?? '') ?>">
        </div>

        <div class="row mb-3">
            <div class="col-md-6">
                <label for="meaning_en" class="form-label">Meaning (English) *</label>
                <input type="text" name="meaning_en" id="meaning_en" class="form-control" required
                       value="<?= htmlspecialchars($flashcard['meaning_en'] ?? $_POST['meaning_en'] ?? '') ?>">
            </div>
            <div class="col-md-6">
                <label for="meaning_bn" class="form-label">Meaning (Bangla) *</label>
                <input type="text" name="meaning_bn" id="meaning_bn" class="form-control" required
                       value="<?= htmlspecialchars($flashcard['meaning_bn'] ?? $_POST['meaning_bn'] ?? '') ?>">
            </div>
        </div>

        <div class="mb-3">
            <label for="example" class="form-label">Example sentence</label>
            <textarea name="example" id="example" class="form-control" rows="2"><?= htmlspecialchars($flashcard['example'] ?? $_POST['example'] ?? '') ?></textarea>
        </div>

        <div class="mb-3">
            <label for="synonyms" class="form-label">Synonyms (comma separated)</label>
            <input type="text" name="synonyms" id="synonyms" class="form-control"
                   value="<?= htmlspecialchars($flashcard['synonyms'] ?? $_POST['synonyms'] ?? '') ?>">
        </div>

        <!-- Image upload field -->
        <div class="mb-3">
            <label for="image_file" class="form-label">Image</label>
            <?php if (!empty($flashcard['image_url'])): ?>
                <div class="mb-2">
                    <img src="<?= htmlspecialchars($flashcard['image_url']) ?>" style="max-height: 120px;" alt="Current image"><br>
                    <small class="text-muted">Current image: <?= htmlspecialchars($flashcard['image_url']) ?></small>
                </div>
            <?php endif; ?>
            <input type="file" name="image_file" id="image_file" class="form-control" accept="image/*">
            <small class="text-muted">Upload a new image (JPEG, PNG, GIF, WebP, max 2MB). Leave empty to keep the current one.</small>
            <input type="hidden" name="existing_image_url" value="<?= htmlspecialchars($flashcard['image_url'] ?? '') ?>">
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-success">
                <i class="fa fa-save me-1"></i> Save
            </button>
            <a href="?page=flashcards<?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
<?php endif; ?>