<?php
/**
 * blog_logic.php - এডিটর সেটআপ আলাদা ফাইলে রেখে আপডেট (সব ফিচারসহ)
 */

// আপলোড ফোল্ডার তৈরি
if (!file_exists('uploads')) {
    mkdir('uploads', 0777, true);
}

// আলাদা ফাইল থেকে এডিটর লজিক এবং ইমেজ হ্যান্ডলার কল করা
include('editor_setup.php');

// ডাটাবেস টেবিল চেক (ব্লগ এবং ক্যাটাগরি টেবিল)
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS blog_categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

mysqli_query($conn, "CREATE TABLE IF NOT EXISTS blogs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content LONGTEXT NOT NULL,
    category_id INT,
    author VARCHAR(100),
    featured_image VARCHAR(255),
    status ENUM('Published', 'Draft') DEFAULT 'Published',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

// --- ১. ক্যাটাগরি লজিক ---

// ক্যাটাগরি সেভ/আপডেট
if (isset($_POST['save_category'])) {
    $cat_name = mysqli_real_escape_string($conn, $_POST['cat_name']);
    $cat_id = $_POST['cat_id'] ?? '';

    if (!empty($cat_id)) {
        mysqli_query($conn, "UPDATE blog_categories SET name='$cat_name' WHERE id=$cat_id");
    } else {
        mysqli_query($conn, "INSERT INTO blog_categories (name) VALUES ('$cat_name')");
    }
    echo "<script>window.location.href='admin.php?view=blogs';</script>";
    exit();
}

// ক্যাটাগরি ডিলিট
if (isset($_GET['delete_category'])) {
    $del_cat_id = (int)$_GET['delete_category'];
    mysqli_query($conn, "DELETE FROM blog_categories WHERE id = $del_cat_id");
    echo "<script>window.location.href='admin.php?view=blogs';</script>";
    exit();
}

// --- ২. ব্লগ পোস্ট লজিক ---

// পোস্ট ডিলিট লজিক
if (isset($_GET['delete_blog'])) {
    $del_id = (int)$_GET['delete_blog'];
    mysqli_query($conn, "DELETE FROM blogs WHERE id = $del_id");
    echo "<script>window.location.href='admin.php?view=blogs';</script>";
}

// পোস্ট সেভ বা আপডেট লজিক
if (isset($_POST['save_blog'])) {
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $content = mysqli_real_escape_string($conn, $_POST['content']); 
    $category_id = (int)$_POST['category_id'];
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $author = $_SESSION['admin_user'] ?? 'Admin';
    $blog_id = $_POST['blog_id'] ?? '';
    
    $featured_image = mysqli_real_escape_string($conn, $_POST['featured_image_url']);
    if (isset($_FILES['featured_image_file']) && $_FILES['featured_image_file']['error'] == 0) {
        $ext = pathinfo($_FILES['featured_image_file']['name'], PATHINFO_EXTENSION);
        $filename = 'featured_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['featured_image_file']['tmp_name'], 'uploads/' . $filename);
        $featured_image = 'uploads/' . $filename;
    }

    if (!empty($blog_id)) {
        $query = "UPDATE blogs SET title='$title', content='$content', category_id='$category_id', featured_image='$featured_image', status='$status' WHERE id=$blog_id";
    } else {
        $query = "INSERT INTO blogs (title, content, category_id, featured_image, author, status) VALUES ('$title', '$content', '$category_id', '$featured_image', '$author', '$status')";
    }

    if (mysqli_query($conn, $query)) {
        echo "<script>window.location.href='admin.php?view=blogs';</script>";
        exit();
    }
}

// ক্যাটাগরি লিস্ট সংগ্রহ (সাথে পোস্ট সংখ্যা)
$categories_res = mysqli_query($conn, "SELECT c.*, (SELECT COUNT(*) FROM blogs b WHERE b.category_id = c.id) as total_posts FROM blog_categories c ORDER BY c.name ASC");
$all_categories = [];
while($row = mysqli_fetch_assoc($categories_res)) $all_categories[] = $row;

// সার্চ ও ফিল্টার হ্যান্ডলিং
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$filter_status = isset($_GET['filter_status']) ? mysqli_real_escape_string($conn, $_GET['filter_status']) : '';
$filter_cat = isset($_GET['filter_cat']) ? (int)$_GET['filter_cat'] : '';

$where_clauses = [];
if ($search) $where_clauses[] = "(title LIKE '%$search%' OR content LIKE '%$search%')";
if ($filter_status) $where_clauses[] = "status = '$filter_status'";
if ($filter_cat) $where_clauses[] = "category_id = $filter_cat";

$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(" AND ", $where_clauses) : "";

$blogs_res = mysqli_query($conn, "SELECT b.*, c.name as category_display_name 
                                  FROM blogs b 
                                  LEFT JOIN blog_categories c ON b.category_id = c.id 
                                  $where_sql ORDER BY b.id DESC");
$total_rows = mysqli_num_rows($blogs_res);

// স্ট্যাটিস্টিক্স
$total_posts = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as count FROM blogs"))['count'];
$published_posts = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as count FROM blogs WHERE status='Published'"))['count'];
$draft_posts = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as count FROM blogs WHERE status='Draft'"))['count'];
?>

<!-- ড্যাশবোর্ড উইজেটস -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 25px;">
    <div style="background: linear-gradient(135deg, #4e73df, #224abe); padding: 20px; border-radius: 12px; color: white; box-shadow: 0 4px 10px rgba(78,115,223,0.2);">
        <div style="font-size: 14px; opacity: 0.8; font-weight: 500;">মোট পোস্ট</div>
        <div style="font-size: 26px; font-weight: 800; margin-top: 5px;"><?php echo $total_posts; ?>টি</div>
    </div>
    <div style="background: linear-gradient(135deg, #1cc88a, #13855c); padding: 20px; border-radius: 12px; color: white; box-shadow: 0 4px 10px rgba(28,200,138,0.2);">
        <div style="font-size: 14px; opacity: 0.8; font-weight: 500;">পাবলিশড</div>
        <div style="font-size: 26px; font-weight: 800; margin-top: 5px;"><?php echo $published_posts; ?>টি</div>
    </div>
    <div style="background: linear-gradient(135deg, #f6c23e, #dda20a); padding: 20px; border-radius: 12px; color: white; box-shadow: 0 4px 10px rgba(246,194,62,0.2);">
        <div style="font-size: 14px; opacity: 0.8; font-weight: 500;">ড্রাফট</div>
        <div style="font-size: 26px; font-weight: 800; margin-top: 5px;"><?php echo $draft_posts; ?>টি</div>
    </div>
</div>

<div style="display: flex; gap: 20px; align-items: flex-start; flex-wrap: wrap;">
    
    <!-- ক্যাটাগরি লিস্ট সেকশন - নির্দিষ্ট প্রস্থ -->
    <div style="flex: 0 0 auto; width: 150px; min-width: 100px; background: white; padding: 15px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
        <div style="margin-bottom: 15px;">
            <h4 style="margin:0; color:#333; font-size: 14px;"><i class="fas fa-tags" style="color:#1cc88a;"></i> ক্যাটাগরি</h4>
            <button onclick="openCatModal()" style="background:#1cc88a; color:white; border:none; padding:4px 8px; border-radius:6px; cursor:pointer; font-size:10px; margin-top: 8px; width: 100%;"><i class="fas fa-plus"></i> নতুন</button>
        </div>
        <div style="max-height: 400px; overflow-y: auto;">
            <table style="width:100%; border-collapse: collapse; font-size: 12px;">
                <?php foreach($all_categories as $cat): ?>
                <tr style="border-bottom: 1px solid #eee;">
                    <td style="padding: 8px 0;">
                        <span style="font-weight: 600; display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"><?php echo htmlspecialchars($cat['name']); ?></span>
                        <div style="font-size: 10px; color: #888;"><?php echo $cat['total_posts']; ?>টি পোস্ট</div>
                    </td>
                    <td style="padding: 8px 0; text-align: right; white-space: nowrap;">
                        <button onclick='editCat(<?php echo json_encode($cat); ?>)' style="color:#4e73df; border:none; background:none; cursor:pointer; font-size: 11px;"><i class="fas fa-edit"></i></button>
                        <a href="admin.php?view=blogs&delete_category=<?php echo $cat['id']; ?>" onclick="return confirm('নিশ্চিত?')" style="color:#e74a3b; font-size: 11px; margin-left: 3px;"><i class="fas fa-trash"></i></a>
                    </td>
                </tr>
                <?php endforeach; if(empty($all_categories)) echo "<tr><td colspan='2' style='text-align:center; padding:10px; color:#aaa;'>নেই</td></tr>"; ?>
            </table>
        </div>
    </div>

    <!-- ব্লগ পোস্ট টেবিল সেকশন -->
    <div style="flex: 1; min-width: 400px; background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 15px;">
            <h3 style="margin: 0; display: flex; align-items: center; gap: 10px; color: #333;">
                <i class="fas fa-newspaper" style="color: #4e73df;"></i> ব্লগ ও নোটিশ কন্ট্রোল
            </h3>
            <button onclick="openBlogModal()" class="btn btn-primary" style="background: #4e73df; color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px;">
                <i class="fas fa-plus-circle"></i> নতুন পোস্ট লিখুন
            </button>
        </div>

        <!-- সার্চ ও ফিল্টার ফর্ম -->
        <form method="GET" action="admin.php" style="background: #f8f9fc; padding: 15px; border-radius: 8px; margin-bottom: 20px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
            <input type="hidden" name="view" value="blogs">
            <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="খুঁজুন..." style="flex: 1; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
            
            <select name="filter_cat" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                <option value="">সকল ক্যাটাগরি</option>
                <?php foreach($all_categories as $cat): ?>
                    <option value="<?php echo $cat['id']; ?>" <?php echo $filter_cat == $cat['id'] ? 'selected' : ''; ?>><?php echo $cat['name']; ?></option>
                <?php endforeach; ?>
            </select>

            <select name="filter_status" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                <option value="">স্ট্যাটাস</option>
                <option value="Published" <?php echo $filter_status == 'Published' ? 'selected' : ''; ?>>Published</option>
                <option value="Draft" <?php echo $filter_status == 'Draft' ? 'selected' : ''; ?>>Draft</option>
            </select>

            <button type="submit" style="background: #333; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer;">ফিল্টার</button>
            <?php if($search || $filter_status || $filter_cat): ?>
                <a href="admin.php?view=blogs" style="color: #e74a3b; text-decoration: none; font-size: 14px; font-weight: 600;">রিসেট</a>
            <?php endif; ?>
        </form>

        <div style="overflow-x: auto;">
            <table style="width: 100%; border-collapse: collapse; min-width: 600px;">
                <thead>
                    <tr style="background: #f8f9fc; border-bottom: 2px solid #e3e6f0;">
                        <th style="padding: 15px; text-align: left; width: 60px;">ক্রম</th>
                        <th style="padding: 15px; text-align: left;">টাইটেল ও বিস্তারিত</th>
                        <th style="padding: 15px; text-align: left; width: 100px;">স্ট্যাটাস</th>
                        <th style="padding: 15px; text-align: center; width: 100px;">অ্যাকশন</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $counter = $total_rows;
                    if ($total_rows > 0): 
                        while ($blog = mysqli_fetch_assoc($blogs_res)): 
                            // HTML ট্যাগ রিমুভ করে মাত্র ৫০ অক্ষরে সীমাবদ্ধ করা হয়েছে
                            $plainText = strip_tags($blog['content']);
                            $excerpt = mb_strimwidth($plainText, 0, 50, "...", "UTF-8");
                    ?>
                    <tr style="border-bottom: 1px solid #eee;">
                        <td style="padding: 15px; font-weight: bold; color: #666;"><?php echo $counter--; ?></td>
                        <td style="padding: 15px;">
                            <div style="font-weight: 700; color: #333; font-size: 15px; margin-bottom: 3px;"><?php echo htmlspecialchars($blog['title']); ?></div>
                            <!-- এখানে এক্সার্প্ট ডিসপ্লে হচ্ছে -->
                            <div style="font-size: 12px; color: #777; margin-bottom: 5px; line-height: 1.4; max-width: 400px;"><?php echo $excerpt; ?></div>
                            <span style="font-size: 11px; background: #e8f0fe; padding: 2px 8px; border-radius: 4px; color: #4e73df; font-weight: 600;"><i class="fas fa-tag"></i> <?php echo htmlspecialchars($blog['category_display_name'] ?: 'Uncategorized'); ?></span>
                        </td>
                        <td style="padding: 15px;">
                            <span style="padding: 4px 8px; border-radius: 20px; font-size: 10px; font-weight: bold; background: <?php echo $blog['status'] == 'Published' ? '#d1f7e8' : '#fff3cd'; ?>; color: <?php echo $blog['status'] == 'Published' ? '#0f5132' : '#856404'; ?>;">
                                <?php echo $blog['status']; ?>
                            </span>
                        </td>
                        <td style="padding: 15px; text-align: center;">
                            <button onclick='editBlog(<?php echo json_encode($blog); ?>)' style="color: #4e73df; border: none; background: none; cursor:pointer;"><i class="fas fa-edit"></i></button>
                            <a href="admin.php?view=blogs&delete_blog=<?php echo $blog['id']; ?>" style="color: #e74a3b; margin-left:10px;" onclick="return confirm('পোস্টটি মুছতে চান?')"><i class="fas fa-trash"></i></a>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                        <tr><td colspan="4" style="padding: 30px; text-align: center; color: #aaa;">কোনো পোস্ট পাওয়া যায়নি</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ক্যাটাগরি মোডাল -->
<div id="catModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1100; justify-content:center; align-items:center;">
    <div style="background:white; padding:25px; border-radius:12px; width:350px;">
        <h4 id="cat_modal_title" style="margin-top:0;">নতুন ক্যাটাগরি</h4>
        <form action="admin.php?view=blogs" method="POST">
            <input type="hidden" name="cat_id" id="cat_id">
            <div style="margin-bottom:15px;">
                <label style="display:block; margin-bottom:5px;">নাম:</label>
                <input type="text" name="cat_name" id="cat_name" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; box-sizing: border-box;">
            </div>
            <div style="text-align: right;">
                <button type="button" onclick="document.getElementById('catModal').style.display='none'" style="background:#eee; border:none; padding:8px 15px; border-radius:6px; cursor:pointer;">বাতিল</button>
                <button type="submit" name="save_category" style="background:#1cc88a; color:white; border:none; padding:8px 20px; border-radius:6px; cursor:pointer;">সংরক্ষণ</button>
            </div>
        </form>
    </div>
</div>

<!-- ব্লগ এডিট/অ্যাড মোডাল -->
<div id="blogModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.6); z-index:1000; justify-content:center; align-items:center; backdrop-filter: blur(4px);">
    <div style="background:white; padding:25px; border-radius:12px; width:95%; max-width: 900px; max-height: 95vh; overflow-y: auto; position: relative;">
        <span onclick="document.getElementById('blogModal').style.display='none'" style="position:absolute; right:20px; top:15px; cursor:pointer; font-size:24px;">&times;</span>
        <h4 id="blog_modal_title" style="margin-top:0; color:#4e73df;">নতুন পোস্ট তৈরি করুন</h4>
        <form action="admin.php?view=blogs" method="POST" enctype="multipart/form-data" style="margin-top:20px;">
            <input type="hidden" name="blog_id" id="blog_id">
            
            <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 15px; margin-bottom:15px;">
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600;">শিরোনাম:</label>
                    <input type="text" name="title" id="blog_title" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; box-sizing: border-box;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600;">ক্যাটাগরি:</label>
                    <select name="category_id" id="blog_category_id" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;">
                        <option value="">সিলেক্ট করুন</option>
                        <?php foreach($all_categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>"><?php echo $cat['name']; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom:15px; background: #f9f9f9; padding: 15px; border-radius: 8px;">
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600;">ইমেজ (আপলোড):</label>
                    <input type="file" name="featured_image_file" accept="image/*">
                </div>
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600;">ইমেজ URL:</label>
                    <input type="text" name="featured_image_url" id="blog_featured_image_url" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:6px; box-sizing: border-box;">
                </div>
            </div>

            <div style="margin-bottom:15px;">
                <label style="font-weight:600; display: block; margin-bottom: 10px;">বিস্তারিত:</label>
                <textarea name="content" id="blog_content" style="width:100%; height:400px;"></textarea>
            </div>

            <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 20px;">
                <select name="status" id="blog_status" style="width:150px; padding:10px; border:1px solid #ddd; border-radius:6px;">
                    <option value="Published">Published</option>
                    <option value="Draft">Draft</option>
                </select>
                <div>
                    <button type="button" onclick="document.getElementById('blogModal').style.display='none'" style="background:#eee; margin-right: 10px; border:none; padding:10px 20px; border-radius:6px; cursor:pointer;">বাতিল</button>
                    <button type="submit" name="save_blog" style="background:#4e73df; color:white; border:none; padding: 10px 30px; border-radius:6px; cursor:pointer; font-weight:bold;">সংরক্ষণ</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
// ক্যাটাগরি মোডাল লজিক
function openCatModal() {
    document.getElementById('cat_id').value = '';
    document.getElementById('cat_name').value = '';
    document.getElementById('cat_modal_title').innerText = 'নতুন ক্যাটাগরি';
    document.getElementById('catModal').style.display = 'flex';
}
function editCat(data) {
    document.getElementById('cat_id').value = data.id;
    document.getElementById('cat_name').value = data.name;
    document.getElementById('cat_modal_title').innerText = 'ক্যাটাগরি আপডেট';
    document.getElementById('catModal').style.display = 'flex';
}

// ব্লগ পোস্ট মোডাল লজিক
function openBlogModal() {
    document.getElementById('blog_id').value = '';
    document.getElementById('blog_title').value = '';
    document.getElementById('blog_category_id').value = '';
    document.getElementById('blog_featured_image_url').value = '';
    document.getElementById('blog_status').value = 'Published';
    document.getElementById('blog_modal_title').innerText = 'নতুন পোস্ট তৈরি করুন';
    if (tinymce.get('blog_content')) tinymce.get('blog_content').setContent('');
    document.getElementById('blogModal').style.display = 'flex';
}

function editBlog(data) {
    document.getElementById('blog_id').value = data.id;
    document.getElementById('blog_title').value = data.title;
    document.getElementById('blog_category_id').value = data.category_id; 
    document.getElementById('blog_featured_image_url').value = data.featured_image || '';
    document.getElementById('blog_status').value = data.status;
    document.getElementById('blog_modal_title').innerText = 'পোস্ট আপডেট করুন';
    if (tinymce.get('blog_content')) tinymce.get('blog_content').setContent(data.content);
    document.getElementById('blogModal').style.display = 'flex';
}
</script>