<?php
/**
 * Admin — Chatbot Training Manager
 * Path: admin/chatbot.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;
}

if ($action === 'delete' && $edit_id > 0) {
    delete_chatbot_training($edit_id) ? $msg_success = 'ট্রেইনিং এন্ট্রি মুছে ফেলা হয়েছে।' : $msg_error = 'মুছতে সমস্যা হয়েছে।';
    $action = 'list';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action'])) {
    $data = [
        'title'        => trim($_POST['title'] ?? ''),
        'question'     => trim($_POST['question'] ?? ''),
        'answer'       => trim($_POST['answer'] ?? ''),
        'category_tag' => trim($_POST['category_tag'] ?? ''),
        'sort_order'   => intval($_POST['sort_order'] ?? 0),
        'is_active'    => isset($_POST['is_active']) ? 1 : 0,
    ];
    $train_id = intval($_POST['train_id'] ?? 0);

    if (empty($data['title']) || empty($data['question']) || empty($data['answer'])) {
        $msg_error = 'টাইটেল, প্রশ্ন ও উত্তর বাধ্যতামূলক।';
    } else {
        $id = ($_POST['form_action'] === 'edit_training' && $train_id > 0) ? $train_id : 0;
        if (save_chatbot_training($data, $id)) {
            $msg_success = 'চ্যাটবট ট্রেইনিং সেভ হয়েছে!';
            $action = 'list';
        } else {
            $msg_error = 'সেভ করতে সমস্যা হয়েছে।';
        }
    }
}

$grouped = get_chatbot_training_grouped();
$all_training = get_chatbot_training(false);

$title_presets = [
    'প্রডাক্ট সম্পর্কিত প্রশ্ন',
    'সার্ভিস সম্পর্কিত প্রশ্ন',
    'সোলার সম্পর্কিত প্রশ্ন',
    'যোগাযোগ',
    'সাধারণ',
];
?>

<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">Chatbot Training</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 Training
        </a>
        <?php else: ?>
        <a href="chatbot.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_training';
        $val = ['title'=>'','question'=>'','answer'=>'','category_tag'=>'','sort_order'=>0,'is_active'=>1];
        if ($action === 'edit' && $edit_id > 0) {
            $form_action = 'edit_training';
            foreach ($all_training as $t) {
                if ($t['id'] == $edit_id) { $val = $t; break; }
            }
        }
    ?>
    <form method="post" action="" class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 space-y-5 max-w-2xl">
        <input type="hidden" name="form_action" value="<?php echo $form_action; ?>">
        <?php if ($action === 'edit'): ?><input type="hidden" name="train_id" value="<?php echo $edit_id; ?>"><?php endif; ?>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Group Title * <span class="text-slate-600 normal-case">(সাজেশন গ্রুপের নাম)</span></label>
            <input type="text" name="title" list="title-presets" value="<?php echo htmlspecialchars($val['title']); ?>" required
                placeholder="প্রডাক্ট সম্পর্কিত প্রশ্ন"
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            <datalist id="title-presets">
                <?php foreach ($title_presets as $tp): ?>
                <option value="<?php echo htmlspecialchars($tp); ?>">
                <?php endforeach; ?>
            </datalist>
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Suggestion Button Text (Question) *</label>
            <input type="text" name="question" value="<?php echo htmlspecialchars($val['question']); ?>" required
                placeholder="প্যাসেঞ্জার লিফ্টের দাম কত?"
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            <p class="text-[10px] text-slate-500 mt-1">চ্যাটের নিচে এই টেক্সট বাটন হিসেবে দেখাবে</p>
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Bot Answer *</label>
            <textarea name="answer" rows="4" required
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100"><?php echo htmlspecialchars($val['answer']); ?></textarea>
        </div>

        <div class="grid grid-cols-2 gap-4">
            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Category Tag</label>
                <select name="category_tag" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
                    <option value="">— None —</option>
                    <?php foreach (['products','services','contact','solar','general'] as $tag): ?>
                    <option value="<?php echo $tag; ?>" <?php echo ($val['category_tag'] === $tag) ? 'selected' : ''; ?>><?php echo $tag; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <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>
        </div>

        <label class="flex items-center gap-3 cursor-pointer">
            <input type="checkbox" name="is_active" value="1" <?php echo $val['is_active'] ? 'checked' : ''; ?> class="accent-sky-500 w-4 h-4">
            <span class="text-sm font-semibold text-slate-300">Active (সাইটে দেখান)</span>
        </label>

        <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 Training
        </button>
    </form>

    <?php else: ?>
    <!-- Grouped Preview -->
    <?php if (empty($grouped)): ?>
    <div class="text-center py-16 text-slate-500">
        <i class="fa-solid fa-robot text-3xl mb-3 block opacity-30"></i>
        <p class="text-sm">কোনো ট্রেইনিং ডেটা নেই। Add Training ক্লিক করুন।</p>
    </div>
    <?php else: foreach ($grouped as $group_title => $items): ?>
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden">
        <div class="px-5 py-3 border-b border-slate-800/80 bg-slate-950/50 flex items-center justify-between">
            <h2 class="text-xs font-black uppercase text-sky-400 tracking-wider">
                <i class="fa-solid fa-layer-group mr-2"></i><?php echo htmlspecialchars($group_title); ?>
            </h2>
            <span class="text-[10px] text-slate-500 font-bold"><?php echo count($items); ?> items</span>
        </div>
        <div class="divide-y divide-slate-800/80">
            <?php foreach ($items as $item): ?>
            <div class="px-5 py-4 flex items-start justify-between gap-4 hover:bg-slate-800/20 transition-colors group">
                <div class="flex-1 space-y-1">
                    <div class="flex items-center gap-2">
                        <span class="text-xs font-bold text-white bg-slate-800 px-2.5 py-1 rounded-lg">
                            <?php echo htmlspecialchars($item['question']); ?>
                        </span>
                        <?php if (!$item['is_active']): ?>
                        <span class="text-[9px] bg-red-900/50 text-red-400 px-1.5 py-0.5 rounded uppercase font-bold">Inactive</span>
                        <?php endif; ?>
                    </div>
                    <p class="text-[11px] text-slate-400 pl-1"><?php echo htmlspecialchars(mb_substr($item['answer'], 0, 120)); ?>...</p>
                </div>
                <div class="flex gap-2 opacity-60 group-hover:opacity-100 transition-opacity flex-shrink-0">
                    <a href="?action=edit&id=<?php echo $item['id']; ?>" class="p-2 bg-slate-800 hover:bg-sky-500 text-sky-400 hover:text-slate-950 rounded-lg text-xs"><i class="fa-solid fa-pen"></i></a>
                    <a href="?action=delete&id=<?php echo $item['id']; ?>" onclick="return confirm('মুছে ফেলবেন?');" class="p-2 bg-slate-800 hover:bg-red-500 text-red-400 hover:text-white rounded-lg text-xs"><i class="fa-solid fa-trash"></i></a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; endif; ?>
    <?php endif; ?>

</main>

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