<?php
/**
 * Admin — FAQs Manager
 * Path: admin/faqs.php
 */
require_once 'layout-header.php';

$msg_success = '';
$msg_error   = '';
$action      = isset($_GET['action']) ? $_GET['action'] : 'list';
$edit_id     = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$conn) {
    echo "<main class='flex-1 p-6'><div class='p-4 bg-red-950/40 border border-red-800 text-red-200 text-sm rounded-xl'>ডাটাবেজ কানেক্টেড নেই!</div></main>";
    require_once 'layout-footer.php';
    exit;
}

$prefix = DB_PREFIX;

if ($action === 'delete' && $edit_id > 0) {
    $stmt = $conn->prepare("DELETE FROM `{$prefix}faqs` WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute() ? $msg_success = 'FAQ মুছে ফেলা হয়েছে।' : $msg_error = $conn->error;
    $stmt->close();
    $action = 'list';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action'])) {
    $question   = trim($_POST['question'] ?? '');
    $answer     = trim($_POST['answer'] ?? '');
    $sort_order = intval($_POST['sort_order'] ?? 0);
    $faq_id     = intval($_POST['faq_id'] ?? 0);

    if (empty($question) || empty($answer)) {
        $msg_error = 'প্রশ্ন ও উত্তর বাধ্যতামূলক।';
    } else {
        if ($_POST['form_action'] === 'edit_faq' && $faq_id > 0) {
            $stmt = $conn->prepare("UPDATE `{$prefix}faqs` SET question=?, answer=?, sort_order=? WHERE id=?");
            $stmt->bind_param("ssii", $question, $answer, $sort_order, $faq_id);
        } else {
            $stmt = $conn->prepare("INSERT INTO `{$prefix}faqs` (question, answer, sort_order) VALUES (?,?,?)");
            $stmt->bind_param("ssi", $question, $answer, $sort_order);
        }
        $stmt->execute() ? $msg_success = 'FAQ সফলভাবে সেভ হয়েছে!' : $msg_error = $conn->error;
        $stmt->close();
        $action = 'list';
    }
}
?>

<main class="flex-1 p-6 md:p-8 space-y-6">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-slate-800/80 pb-5">
        <div>
            <h1 class="text-2xl font-black text-white uppercase tracking-wider">FAQs Manager</h1>
            <p class="text-xs text-slate-400 mt-1">সাইটের প্রশ্নোত্তর সেকশন ম্যানেজ করুন</p>
        </div>
        <?php if ($action === 'list'): ?>
        <a href="?action=add" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-plus-circle mr-2"></i> Add FAQ
        </a>
        <?php else: ?>
        <a href="faqs.php" class="bg-slate-800 text-slate-300 px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-arrow-left mr-2"></i> Back
        </a>
        <?php endif; ?>
    </div>

    <?php if ($msg_success): ?>
    <div class="p-4 bg-emerald-950/40 border border-emerald-800 text-emerald-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-circle-check mr-3"></i> <?php echo $msg_success; ?>
    </div>
    <?php endif; ?>
    <?php if ($msg_error): ?>
    <div class="p-4 bg-red-950/40 border border-red-800 text-red-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-triangle-exclamation mr-3"></i> <?php echo $msg_error; ?>
    </div>
    <?php endif; ?>

    <?php if ($action === 'add' || $action === 'edit'):
        $form_action = 'add_faq';
        $val = ['question'=>'','answer'=>'','sort_order'=>0];
        if ($action === 'edit' && $edit_id > 0) {
            $form_action = 'edit_faq';
            $stmt = $conn->prepare("SELECT * FROM `{$prefix}faqs` WHERE id = ?");
            $stmt->bind_param("i", $edit_id);
            $stmt->execute();
            if ($row = $stmt->get_result()->fetch_assoc()) $val = $row;
            $stmt->close();
        }
    ?>
    <form method="post" action="" class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 space-y-5 max-w-3xl">
        <input type="hidden" name="form_action" value="<?php echo $form_action; ?>">
        <?php if ($action === 'edit'): ?><input type="hidden" name="faq_id" value="<?php echo $edit_id; ?>"><?php endif; ?>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Question *</label>
            <input type="text" name="question" value="<?php echo htmlspecialchars($val['question']); ?>" required
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100 focus:ring-2 focus:ring-sky-500">
        </div>
        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Answer *</label>
            <textarea name="answer" rows="5" required
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100 focus:ring-2 focus:ring-sky-500"><?php echo htmlspecialchars($val['answer']); ?></textarea>
        </div>
        <div class="w-32">
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Sort Order</label>
            <input type="number" name="sort_order" value="<?php echo (int)$val['sort_order']; ?>" min="0"
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
        </div>
        <button type="submit" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-8 py-3.5 rounded-xl text-xs uppercase">
            <i class="fa-solid fa-floppy-disk mr-2"></i> Save FAQ
        </button>
    </form>

    <?php else:
        $result = $conn->query("SELECT * FROM `{$prefix}faqs` ORDER BY sort_order ASC, id ASC");
    ?>
    <div class="space-y-3">
        <?php if ($result && $result->num_rows > 0):
            while ($row = $result->fetch_assoc()): ?>
        <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-5 hover:border-sky-500/20 transition-all group">
            <div class="flex items-start justify-between gap-4">
                <div class="flex-1 space-y-2">
                    <div class="flex items-center gap-2">
                        <span class="text-[10px] font-bold text-slate-600 bg-slate-800 px-2 py-0.5 rounded">#<?php echo (int)$row['sort_order']; ?></span>
                        <h3 class="font-bold text-white text-sm"><?php echo htmlspecialchars($row['question']); ?></h3>
                    </div>
                    <p class="text-xs text-slate-400 leading-relaxed pl-1 border-l-2 border-sky-500/30 ml-1">
                        <?php echo htmlspecialchars(mb_substr($row['answer'], 0, 200)); ?><?php echo mb_strlen($row['answer']) > 200 ? '...' : ''; ?>
                    </p>
                </div>
                <div class="flex gap-2 flex-shrink-0 opacity-60 group-hover:opacity-100 transition-opacity">
                    <a href="?action=edit&id=<?php echo $row['id']; ?>" class="p-2 bg-slate-800 hover:bg-sky-500 hover:text-slate-950 text-sky-400 rounded-lg text-xs"><i class="fa-solid fa-pen"></i></a>
                    <a href="?action=delete&id=<?php echo $row['id']; ?>" onclick="return confirm('মুছে ফেলবেন?');" class="p-2 bg-slate-800 hover:bg-red-500 hover:text-white text-red-400 rounded-lg text-xs"><i class="fa-solid fa-trash"></i></a>
                </div>
            </div>
        </div>
        <?php endwhile; else: ?>
        <div class="text-center py-16 text-slate-500">
            <i class="fa-solid fa-circle-question text-3xl mb-3 block opacity-30"></i>
            <p class="text-sm">কোনো FAQ নেই। Add FAQ ক্লিক করুন।</p>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

</main>

<?php require_once 'layout-footer.php'; ?>
