<?php 
// ক্যাটাগরি ম্যানেজমেন্ট পেজ
include 'header.php'; 

// --- সর্টিং লজিক (এটি আলাদা ফাইল ছাড়া কাজ করবে) ---
if (isset($_POST['order'])) {
    foreach ($_POST['order'] as $index => $id) {
        $id = (int)$id;
        $index = (int)$index;
        $conn->query("UPDATE categories SET cat_order = $index WHERE id = $id");
    }
    exit; // শুধু ডাটা আপডেট করে প্রসেস থামিয়ে দিবে (AJAX এর জন্য)
}

// --- ১. নতুন ক্যাটাগরি তৈরি ---
if(isset($_POST['add_new_category'])) {
    $cat_name = mysqli_real_escape_string($conn, $_POST['new_category_name']);
    $cat_align = mysqli_real_escape_string($conn, $_POST['cat_align']);
    $cat_status = (int)$_POST['cat_status'];
    $access_level = (int)$_POST['access_level'];
    $cat_slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $cat_name)));

    if(!empty($cat_name)) {
        // কলাম চেক (সেফটি)
        $conn->query("ALTER TABLE categories ADD COLUMN IF NOT EXISTS cat_order INT DEFAULT 0");
        
        $chk = $conn->query("SELECT * FROM categories WHERE name = '$cat_name'");
        if($chk->num_rows == 0) {
            $sql = "INSERT INTO categories (name, cat_align, cat_status, cat_slug, access_level) VALUES ('$cat_name', '$cat_align', '$cat_status', '$cat_slug', '$access_level')";
            if($conn->query($sql)) {
                echo "<script>window.location.href='categories.php';</script>"; exit;
            }
        }
    }
}

// --- ২. ক্যাটাগরি আপডেট (এডিট) ---
if(isset($_POST['update_category'])) {
    $cat_id = (int)$_POST['cat_id'];
    $new_name = mysqli_real_escape_string($conn, $_POST['cat_name']);
    $new_align = mysqli_real_escape_string($conn, $_POST['cat_align']);
    $new_status = (int)$_POST['cat_status'];
    $new_access = (int)$_POST['access_level'];
    $new_slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $new_name)));
    
    $sql = "UPDATE categories SET name='$new_name', cat_align='$new_align', cat_status='$new_status', cat_slug='$new_slug', access_level='$new_access' WHERE id=$cat_id";
    if($conn->query($sql)) {
        echo "<script>window.location.href='categories.php';</script>"; exit;
    }
}

// --- ৩. ক্যাটাগরি ডিলিট ---
if(isset($_GET['del_cat_id'])) {
    $id = (int)$_GET['del_cat_id'];
    $conn->query("DELETE FROM categories WHERE id=$id");
    echo "<script>window.location.href='categories.php';</script>"; exit;
}

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$base_url = $protocol . "://" . $_SERVER['HTTP_HOST'] . dirname(dirname($_SERVER['PHP_SELF'])) . "/";
?>

<div class="control-box">
    <h4 style="color:var(--accent); margin-top:0;"><i class="fas fa-folder-plus"></i> CREATE CATEGORY</h4>
    <form action="" method="POST">
        <label>Category Name</label>
        <input type="text" name="new_category_name" placeholder="Name" required>
        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px;">
            <div><label>Position</label><select name="cat_align"><option value="left">Left</option><option value="center" selected>Center</option><option value="right">Right</option></select></div>
            <div><label>Visibility</label><select name="cat_status"><option value="1">Show</option><option value="0">Hide</option></select></div>
            <div><label>Access</label><select name="access_level"><option value="0">Public</option><option value="1">Officer</option></select></div>
        </div>
        <button class="btn" name="add_new_category">ADD CATEGORY</button>
    </form>
</div>

<h4 style="color:#fff; margin:20px 0 10px;"><i class="fas fa-sort-amount-down"></i> MANAGE ORDER (DRAG TO SORT)</h4>
<ul id="cat_sortable" style="padding:0; list-style:none;">
    <?php
    $cat_res = $conn->query("SELECT * FROM categories ORDER BY cat_order ASC");
    while($c = $cat_res->fetch_assoc()) {
        $st_val = $c['cat_status'];
        $acc_val = $c['access_level'];
        $status_text = ($st_val == 1) ? '<b style="color:lime;">Visible</b>' : '<b style="color:orange;">Hidden</b>';
        $access_text = ($acc_val == 1) ? '<span style="background:red; color:white; padding:2px 5px; font-size:9px; border-radius:3px; margin-left:5px;">OFFICER</span>' : '';
        $final_link = $base_url . "index.php?page=" . $c['cat_slug'];
        
        echo '<li class="list-item" id="cat_'.$c['id'].'">
            <div style="display:flex; align-items:center; flex:1;">
                <i class="fas fa-bars" style="margin-right:15px; color:#444; cursor:move;"></i>
                <div>
                    <span>'.$c['name'].' ('.ucfirst($c['cat_align']).') - '.$status_text.' '.$access_text.'</span><br>
                    <small style="color:#555; display:flex; align-items:center; gap:8px;">Link: '.$final_link.' <button onclick="copyLink(\''.$final_link.'\', this)" style="background:none; border:none; color:var(--accent); cursor:pointer;"><i class="fas fa-copy"></i></button></small>
                </div>
            </div>
            <div>
                <a href="#" onclick="editCategory('.$c['id'].', \''.htmlspecialchars($c['name']).'\', \''.$c['cat_align'].'\', \''.$st_val.'\', \''.$acc_val.'\')" style="color:var(--accent); margin-right:15px; text-decoration:none;"><i class="fas fa-edit"></i> Edit</a>
                <a href="?del_cat_id='.$c['id'].'" onclick="return confirm(\'Delete?\')" style="color:red; text-decoration:none;"><i class="fas fa-trash"></i></a>
            </div>
        </li>';
    }
    ?>
</ul>

<!-- EDIT MODAL -->
<div id="editCategoryModal" class="modal">
    <div class="modal-content">
        <h3 style="color:var(--accent); margin-top:0;">EDIT CATEGORY</h3>
        <form action="" method="POST">
            <input type="hidden" name="cat_id" id="edit_cat_id">
            <label>Category Name</label><input type="text" name="cat_name" id="edit_cat_name" required>
            <label>Position</label>
            <select name="cat_align" id="edit_cat_align">
                <option value="left">Left</option><option value="center">Center</option><option value="right">Right</option>
            </select>
            <label>Status</label>
            <select name="cat_status" id="edit_cat_status"><option value="1">Show</option><option value="0">Hide</option></select>
            <label>Access Level</label>
            <select name="access_level" id="edit_access_level"><option value="0">Public</option><option value="1">Officer Only</option></select>
            <button class="btn" name="update_category">UPDATE</button>
        </form>
        <button onclick="$('#editCategoryModal').fadeOut()" class="btn" style="background:#333;">CANCEL</button>
    </div>
</div>

<script>
function editCategory(id, name, align, status, access) {
    $('#edit_cat_id').val(id); $('#edit_cat_name').val(name); $('#edit_cat_align').val(align); $('#edit_cat_status').val(status); $('#edit_access_level').val(access); $('#editCategoryModal').fadeIn();
}

function copyLink(text, btn) {
    const oldIcon = btn.innerHTML;
    navigator.clipboard.writeText(text).then(() => {
        btn.innerHTML = '<i class="fas fa-check" style="color:lime"></i>';
        setTimeout(() => { btn.innerHTML = oldIcon; }, 2000);
    });
}

// সর্টিং স্ক্রিপ্ট (এই ফাইলকেই ডাটা পাঠাবে)
$(function() {
    $("#cat_sortable").sortable({
        handle: '.fa-bars',
        update: function() {
            var order = $(this).sortable('toArray').map(i => i.replace('cat_', ''));
            // নিজের ফাইলকেই (categories.php) পোস্ট রিকোয়েস্ট পাঠানো হচ্ছে
            $.post("categories.php", { order: order });
        }
    });
});
</script>
<?php include 'footer.php'; ?>