<?php
/**
 * Admin — News & Blogs Manager
 * Path: admin/blogs.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}blogs` WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute() ? $msg_success = 'ব্লগ পোস্ট মুছে ফেলা হয়েছে।' : $msg_error = $conn->error;
    $stmt->close();
    $action = 'list';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action'])) {
    $title         = trim($_POST['title'] ?? '');
    $content       = trim($_POST['content'] ?? '');
    $excerpt       = trim($_POST['excerpt'] ?? '');
    $thumbnail_url = trim($_POST['thumbnail_url'] ?? '');
    $video_url     = trim($_POST['video_url'] ?? '');
    $is_featured   = isset($_POST['is_featured']) ? 1 : 0;
    $blog_id       = intval($_POST['blog_id'] ?? 0);

    if (isset($_FILES['thumb_file']) && $_FILES['thumb_file']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['thumb_file']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','webp','gif'])) {
            $dir = '../uploads/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $fname = time() . '_blog_' . bin2hex(random_bytes(3)) . '.' . $ext;
            if (move_uploaded_file($_FILES['thumb_file']['tmp_name'], $dir . $fname)) {
                $thumbnail_url = 'uploads/' . $fname;
            }
        }
    }

    if (empty($title) || empty($content)) {
        $msg_error = 'টাইটেল ও কন্টেন্ট বাধ্যতামূলক।';
    } else {
        if (empty($excerpt)) $excerpt = mb_substr(strip_tags($content), 0, 200);

        if ($_POST['form_action'] === 'edit_blog' && $blog_id > 0) {
            $stmt = $conn->prepare("UPDATE `{$prefix}blogs` SET title=?, content=?, excerpt=?, thumbnail_url=?, is_featured=?, video_url=? WHERE id=?");
            $stmt->bind_param("ssssisi", $title, $content, $excerpt, $thumbnail_url, $is_featured, $video_url, $blog_id);
        } else {
            $stmt = $conn->prepare("INSERT INTO `{$prefix}blogs` (title, content, excerpt, thumbnail_url, is_featured, video_url) VALUES (?,?,?,?,?,?)");
            $stmt->bind_param("ssssis", $title, $content, $excerpt, $thumbnail_url, $is_featured, $video_url);
        }
        $stmt->execute() ? $msg_success = 'ব্লগ পোস্ট সেভ হয়েছে!' : $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">News & Blogs</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 Post
        </a>
        <?php else: ?>
        <a href="blogs.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_blog';
        $val = ['title'=>'','content'=>'','excerpt'=>'','thumbnail_url'=>'','video_url'=>'','is_featured'=>0];
        if ($action === 'edit' && $edit_id > 0) {
            $form_action = 'edit_blog';
            $stmt = $conn->prepare("SELECT * FROM `{$prefix}blogs` 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="" enctype="multipart/form-data" 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="blog_id" value="<?php echo $edit_id; ?>"><?php endif; ?>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Post Title *</label>
            <input type="text" name="title" value="<?php echo htmlspecialchars($val['title']); ?>" required
                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="block text-xs font-bold uppercase text-slate-400 mb-2">Thumbnail</label>
            <div class="grid grid-cols-2 gap-3">
                <input type="file" name="thumb_file" accept="image/*" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-2 py-2 text-xs text-slate-400">
                <input type="url" name="thumbnail_url" value="<?php echo htmlspecialchars($val['thumbnail_url']); ?>" placeholder="https://..."
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-100">
            </div>
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Excerpt <span class="text-slate-600 normal-case">(optional)</span></label>
            <textarea name="excerpt" rows="2" 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['excerpt']); ?></textarea>
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Content *</label>
            <textarea name="content" rows="8" 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['content']); ?></textarea>
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">YouTube Video URL <span class="text-slate-600 normal-case">(optional)</span></label>
            <input type="url" name="video_url" value="<?php echo htmlspecialchars($val['video_url']); ?>" placeholder="https://youtu.be/..."
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
        </div>

        <label class="flex items-center gap-3 cursor-pointer">
            <input type="checkbox" name="is_featured" value="1" <?php echo $val['is_featured'] ? 'checked' : ''; ?> class="accent-sky-500 w-4 h-4">
            <span class="text-sm font-semibold text-slate-300">Featured Post (হোমপেজে আগে দেখাবে)</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 Post
        </button>
    </form>

    <?php else:
        $result = $conn->query("SELECT * FROM `{$prefix}blogs` ORDER BY is_featured DESC, id DESC");
    ?>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <?php if ($result && $result->num_rows > 0):
            while ($row = $result->fetch_assoc()):
                $thumb = $row['thumbnail_url'];
                if ($thumb && strpos($thumb,'uploads/')===0) $thumb = '../'.$thumb;
        ?>
        <div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden hover:border-sky-500/20 transition-all group">
            <?php if ($thumb): ?>
            <div class="aspect-video bg-slate-950 overflow-hidden">
                <img src="<?php echo htmlspecialchars($thumb); ?>" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" alt="">
            </div>
            <?php endif; ?>
            <div class="p-5 space-y-2">
                <div class="flex items-center gap-2">
                    <?php if ($row['is_featured']): ?>
                    <span class="text-[9px] font-bold uppercase bg-amber-500/20 text-amber-400 px-2 py-0.5 rounded">Featured</span>
                    <?php endif; ?>
                    <span class="text-[10px] text-slate-500"><?php echo date('d M Y', strtotime($row['created_at'])); ?></span>
                </div>
                <h3 class="font-bold text-white text-sm leading-tight"><?php echo htmlspecialchars($row['title']); ?></h3>
                <p class="text-xs text-slate-400 line-clamp-2"><?php echo htmlspecialchars($row['excerpt']); ?></p>
                <div class="flex gap-2 pt-2">
                    <a href="?action=edit&id=<?php echo $row['id']; ?>" class="flex-1 text-center bg-slate-800 hover:bg-sky-500 hover:text-slate-950 text-sky-400 py-2 rounded-lg text-xs font-bold transition-all">
                        <i class="fa-solid fa-pen mr-1"></i> Edit
                    </a>
                    <a href="?action=delete&id=<?php echo $row['id']; ?>" onclick="return confirm('মুছে ফেলবেন?');"
                        class="px-3 bg-slate-800 hover:bg-red-500 text-red-400 hover:text-white py-2 rounded-lg text-xs transition-all">
                        <i class="fa-solid fa-trash"></i>
                    </a>
                </div>
            </div>
        </div>
        <?php endwhile; else: ?>
        <div class="col-span-full text-center py-16 text-slate-500">
            <i class="fa-solid fa-newspaper text-3xl mb-3 block opacity-30"></i>
            <p class="text-sm">কোনো ব্লগ পোস্ট নেই।</p>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

</main>

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