<?php
session_start();

$config_paths = ['config.php', 'Config.php', '../config.php', '../Config.php'];
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        break;
    }
}
if (!isset($conn) && isset($con)) $conn = $con;

$admin_user = $_SESSION['admin_user'] ?? '';
$admin_pass = $_SESSION['admin_pass'] ?? '';

if (empty($admin_user) || empty($admin_pass)) {
    header("Location: admin_login.php");
    exit;
}

$has_permission = false;
$md5_pass_sess = md5($admin_pass);

// Admin Check
$admin_stmt = $conn->prepare("SELECT id FROM admin WHERE username=? AND (password=? OR password=?) LIMIT 1");
if ($admin_stmt) {
    $admin_stmt->bind_param("sss", $admin_user, $admin_pass, $md5_pass_sess);
    $admin_stmt->execute();
    if ($admin_stmt->get_result()->num_rows > 0) {
        $has_permission = true;
    }
    $admin_stmt->close();
}

// Moderator Check (extra_json verify)
if (!$has_permission) {
    $mod_stmt = $conn->prepare("SELECT extra_json FROM modarator_permissions WHERE username=? AND (password=? OR password=?) LIMIT 1");
    if ($mod_stmt) {
        $mod_stmt->bind_param("sss", $admin_user, $admin_pass, $md5_pass_sess);
        $mod_stmt->execute();
        $mod_res = $mod_stmt->get_result();
        if ($mod_res->num_rows > 0) {
            $mod_data = $mod_res->fetch_assoc();
            $extra_json = json_decode($mod_data['extra_json'], true);
            if (isset($extra_json['match_category_permissions']) && $extra_json['match_category_permissions'] === 'Yes') {
                $has_permission = true;
            }
        }
        $mod_stmt->close();
    }
}

// If no permission, block view immediately
if (!$has_permission) {
    die('<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>অ্যাক্সেস বাতিল</title></head><body style="margin:0;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;background:#f2f2f7;font-family:sans-serif;"><svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="#ff3b30" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg><h2 style="color:#ff3b30;margin:20px 0 10px;">অ্যাক্সেস বাতিল!</h2><p style="color:#8e8e93;margin-bottom:20px;">Match Category পারমিশন দেওয়া হয়নি।</p><button onclick="window.location.href=\'index.php\'" style="background:#007aff;color:#fff;border:none;padding:12px 24px;border-radius:10px;font-size:15px;cursor:pointer;box-shadow: 0 4px 10px rgba(0, 122, 255, 0.2);">ড্যাশবোর্ডে ফিরে যান</button></body></html>');
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>ক্যাটেগরি ম্যানেজার</title>
    <style>
        :root {
            --bg-color: #f2f2f7; 
            --surface: #ffffff;
            --surface-hover: #f9f9fb;
            --primary: #007aff; 
            --primary-hover: #0056b3;
            --danger: #ff3b30;
            --danger-bg: rgba(255, 59, 48, 0.1);
            --success: #34c759;
            --text-main: #1c1c1e;
            --text-muted: #8e8e93;
            --border-color: rgba(0, 0, 0, 0.1);
            --radius-md: 14px;
            --radius-lg: 20px;
            --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.04);
            --shadow-md: 0 8px 24px rgba(0, 0, 0, 0.08);
            --transition: all 0.25s cubic-bezier(0.25, 0.8, 0.25, 1);
        }
        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: var(--bg-color); color: var(--text-main); min-height: 100vh; display: flex; justify-content: center; }
        .app-container { width: 100%; max-width: 1000px; padding: 30px 24px; display: flex; flex-direction: column; margin: 0 auto; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
        .header h1 { font-size: 32px; font-weight: 700; color: var(--text-main); }
        .back-link { color: var(--primary); text-decoration: none; font-size: 14px; display: inline-block; margin-top: 6px; font-weight: 500; }
        .btn-add { background: var(--primary); border: none; border-radius: 30px; padding: 10px 20px; color: #fff; font-weight: 600; font-size: 15px; cursor: pointer; transition: var(--transition); display: flex; align-items: center; gap: 6px; box-shadow: 0 4px 10px rgba(0, 122, 255, 0.2); }
        .btn-add:hover { background: var(--primary-hover); transform: translateY(-2px); box-shadow: 0 6px 15px rgba(0, 122, 255, 0.3); }
        .search-wrapper { background: var(--surface); border-radius: var(--radius-md); padding: 4px 16px; display: flex; align-items: center; border: 1px solid var(--border-color); margin-bottom: 24px; box-shadow: var(--shadow-sm); }
        .search-wrapper input { background: transparent; border: none; outline: none; color: var(--text-main); font-size: 16px; padding: 14px 12px; width: 100%; }
        .category-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px; }
        .category-card { background: var(--surface); border-radius: var(--radius-lg); padding: 16px; display: flex; align-items: center; gap: 16px; border: 1px solid var(--border-color); box-shadow: var(--shadow-sm); }
        .cat-img { width: 60px; height: 60px; border-radius: var(--radius-md); background: rgba(0,0,0,0.03); flex-shrink: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; }
        .cat-img img { width: 100%; height: 100%; object-fit: cover; }
        .cat-info { flex: 1; overflow: hidden; }
        .cat-info .title { font-size: 17px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .cat-actions button { background: rgba(0,0,0,0.04); border: none; border-radius: 50%; width: 40px; height: 40px; cursor: pointer; color: var(--text-main); margin-left: 5px; }
        .state-container { grid-column: 1 / -1; text-align: center; padding: 60px 20px; color: var(--text-muted); }
        .modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.4); z-index: 999; display: none; align-items: center; justify-content: center; padding: 20px; }
        .modal-overlay.show { display: flex; }
        .modal-sheet { background: var(--surface); border-radius: 24px; width: 100%; max-width: 460px; padding: 30px; border: 1px solid var(--border-color); }
        .modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; font-size: 22px; font-weight: 700; }
        .close-btn { background: none; border: none; cursor: pointer; }
        .edit-field { margin-bottom: 20px; }
        .edit-field label { display: block; font-size: 13px; font-weight: 600; color: var(--text-muted); margin-bottom: 8px; }
        .edit-field input { width: 100%; padding: 14px 16px; background: #f2f2f7; border: 1px solid var(--border-color); border-radius: var(--radius-md); font-size: 16px; }
        .modal-actions { display: flex; gap: 12px; margin-top: 30px; }
        .modal-actions button { flex: 1; padding: 14px; border: none; border-radius: var(--radius-md); font-size: 16px; font-weight: 600; cursor: pointer; }
        .btn-save { background: var(--success); color: #fff; }
        .btn-cancel { background: #e5e5ea; color: var(--text-main); }
        .toast-message { position: fixed; bottom: 30px; left: 50%; transform: translate(-50%, 20px); background: #fff; padding: 14px 24px; border-radius: 30px; font-weight: 600; border: 1px solid var(--border-color); opacity: 0; visibility: hidden; transition: 0.3s; z-index: 9999; box-shadow: var(--shadow-md); }
        .toast-message.show { opacity: 1; visibility: visible; transform: translate(-50%, 0); }
    </style>
</head>
<body>

<div class="app-container">
    <div class="header">
        <div>
            <h1>ক্যাটেগরি</h1>
            <a href="index.php" class="back-link">&larr; ড্যাশবোর্ডে ফিরে যান</a>
        </div>
        <button class="btn-add" id="btnAddCategory" onclick="openAddModal()">যোগ করুন</button>
    </div>

    <div class="search-wrapper">
        <input type="text" id="searchInput" placeholder="ক্যাটেগরি সার্চ করুন..." autocomplete="off">
    </div>

    <div class="category-list" id="categoryList">
        <div class="state-container">ডাটা লোড হচ্ছে...</div>
    </div>
</div>

<div class="modal-overlay" id="categoryModal">
    <div class="modal-sheet">
        <div class="modal-header">
            <span id="modalTitle">ক্যাটেগরি যোগ করুন</span>
            <button class="close-btn" onclick="closeModal()">X</button>
        </div>
        <div class="edit-field">
            <label>শিরোনাম</label>
            <input type="text" id="editTitle" placeholder="ক্যাটেগরির নাম লিখুন">
        </div>
        <div class="edit-field">
            <label>ইমেজ লিংক (URL)</label>
            <input type="url" id="editImage" placeholder="https://example.com/image.jpg">
        </div>
        <div class="modal-actions">
            <button class="btn-cancel" onclick="closeModal()">বাতিল</button>
            <button class="btn-save" onclick="saveCategory()">সংরক্ষণ করুন</button>
        </div>
    </div>
</div>

<div class="toast-message" id="toastMessage">Message</div>

<script>
// রিকোয়েস্টের জন্য ইউজারনেম এবং পাসওয়ার্ড পাস করা হচ্ছে
const AUTH_USER = "<?php echo addslashes($admin_user); ?>";
const AUTH_PASS = "<?php echo addslashes($admin_pass); ?>";
const API_URL = 'category_api.php'; 

let editingId = null;
let currentSearch = '';
let categoryData = []; 

const categoryListEl = document.getElementById('categoryList');
const searchInput = document.getElementById('searchInput');
const modalOverlay = document.getElementById('categoryModal');
const modalTitle = document.getElementById('modalTitle');
const editTitle = document.getElementById('editTitle');
const editImage = document.getElementById('editImage');

async function loadCategories() {
    categoryListEl.innerHTML = `<div class="state-container">ডাটা চেক করা হচ্ছে...</div>`;
    
    // JS Request এ Username ও Password যুক্ত করা হয়েছে 
    const formData = new URLSearchParams();
    formData.append('username', AUTH_USER);
    formData.append('password', AUTH_PASS);
    formData.append('action', 'list');
    formData.append('search', currentSearch);
    
    try {
        const res = await fetch(API_URL, { method: 'POST', body: formData.toString(), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        const data = await res.json();
        
        if (res.ok && data.status === 'success') {
            categoryData = data.categories || [];
            renderCategories();
        } else {
            categoryListEl.innerHTML = `<div class="state-container" style="color:red;">${data.message || 'পারমিশন নেই'}</div>`;
        }
    } catch(e) {
        categoryListEl.innerHTML = `<div class="state-container" style="color:red;">সার্ভার এরর!</div>`;
    }
}

function renderCategories() {
    if (categoryData.length === 0) {
        categoryListEl.innerHTML = `<div class="state-container">খুঁজে পাওয়া যায়নি</div>`;
        return;
    }
    let html = '';
    categoryData.forEach((cat) => {
        html += `
            <div class="category-card">
                <div class="cat-img"><img src="${cat.image_link}" onerror="this.style.display='none'"></div>
                <div class="cat-info"><div class="title">${cat.title}</div></div>
                <div class="cat-actions">
                    <button onclick="openEditModal(${cat.id})">✎</button>
                    <button onclick="deleteCategory(${cat.id})">🗑</button>
                </div>
            </div>`;
    });
    categoryListEl.innerHTML = html;
}

function openAddModal() {
    editingId = null; modalTitle.textContent = 'ক্যাটেগরি যোগ করুন';
    editTitle.value = ''; editImage.value = ''; modalOverlay.classList.add('show');
}

function openEditModal(id) {
    const cat = categoryData.find(c => c.id === id);
    if (!cat) return;
    editingId = id; modalTitle.textContent = 'ক্যাটেগরি এডিট করুন';
    editTitle.value = cat.title; editImage.value = cat.image_link || '';
    modalOverlay.classList.add('show');
}

function closeModal() { modalOverlay.classList.remove('show'); editingId = null; }

async function saveCategory() {
    const title = editTitle.value.trim();
    const image_link = editImage.value.trim();
    if (!title) { showToast('শিরোনাম লিখুন'); return; }

    const formData = new URLSearchParams();
    formData.append('username', AUTH_USER);
    formData.append('password', AUTH_PASS);
    formData.append('action', editingId ? 'update' : 'add');
    formData.append('title', title);
    formData.append('image_link', image_link);
    if (editingId) formData.append('id', editingId);

    try {
        const res = await fetch(API_URL, { method: 'POST', body: formData.toString(), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        const data = await res.json();
        if (data.status === 'success') { showToast('সফলভাবে সেভ হয়েছে!'); closeModal(); loadCategories(); }
        else { showToast('ব্যর্থ: ' + data.message); }
    } catch(e) { showToast('এরর!'); }
}

async function deleteCategory(id) {
    if (!confirm('ডিলিট করতে চান?')) return;
    const formData = new URLSearchParams();
    formData.append('username', AUTH_USER);
    formData.append('password', AUTH_PASS);
    formData.append('action', 'delete');
    formData.append('id', id);
    
    try {
        const res = await fetch(API_URL, { method: 'POST', body: formData.toString(), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        const data = await res.json();
        if (data.status === 'success') { showToast('ডিলিট হয়েছে!'); loadCategories(); }
        else { showToast('ব্যর্থ!'); }
    } catch(e) { showToast('এরর!'); }
}

let toastTimeout;
function showToast(msg) {
    const el = document.getElementById('toastMessage');
    el.textContent = msg; el.classList.add('show');
    clearTimeout(toastTimeout);
    toastTimeout = setTimeout(() => el.classList.remove('show'), 3000);
}

searchInput.addEventListener('input', function() {
    currentSearch = this.value.trim();
    clearTimeout(window.searchTimeout);
    window.searchTimeout = setTimeout(loadCategories, 400);
});

loadCategories();
</script>
</body>
</html>
