<?php
// ফোল্ডার এবং ফাইল চেক
if (!file_exists('data')) mkdir('data', 0777, true);

// ক্যাটাগরি লোড
$categoriesFile = 'data/categories.json';
if (!file_exists($categoriesFile)) {
    file_put_contents($categoriesFile, json_encode([], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}
$categories = json_decode(file_get_contents($categoriesFile), true);

// ইউটিলিটি ফাংশন
function slugify($text) {
    return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '_', $text)));
}

function saveCategories($categories) {
    global $categoriesFile;
    file_put_contents($categoriesFile, json_encode($categories, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}

function saveData($category, $data) {
    $file = "data/{$category}.json";
    file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}

function loadData($category) {
    $file = "data/{$category}.json";
    if (!file_exists($file)) return [];
    return json_decode(file_get_contents($file), true);
}

// ক্যাটাগরি তৈরি
if (isset($_POST['create_category'])) {
    $newCat = slugify($_POST['category_name']);
    $fields = array_map('trim', explode(',', $_POST['category_fields']));

    if ($newCat && !isset($categories[$newCat])) {
        $categories[$newCat] = $fields;
        saveCategories($categories);
        saveData($newCat, []);
    }
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// ক্যাটাগরি এডিট
if (isset($_POST['edit_category'])) {
    $oldCat = $_POST['old_category'];
    $newCat = slugify($_POST['new_category']);
    $fields = array_map('trim', explode(',', $_POST['new_fields']));

    if ($oldCat !== $newCat) {
        rename("data/{$oldCat}.json", "data/{$newCat}.json");
        unset($categories[$oldCat]);
    }
    $categories[$newCat] = $fields;
    saveCategories($categories);
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// ক্যাটাগরি ডিলিট
if (isset($_GET['delete_category'])) {
    $cat = $_GET['delete_category'];
    unset($categories[$cat]);
    saveCategories($categories);
    if (file_exists("data/{$cat}.json")) unlink("data/{$cat}.json");
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// ডাটা যুক্ত
if (isset($_POST['add_data'])) {
    $category = $_POST['data_category'];
    $data = loadData($category);
    $entry = [];

    foreach ($categories[$category] as $field) {
        $key = slugify($field);
        $entry[$key] = $_POST[$key] ?? '';
    }
    $entry['status'] = 'published';
    $data[] = $entry;
    saveData($category, $data);
    header("Location: ".$_SERVER['PHP_SELF']."?category=$category");
    exit;
}

// ডাটা টগল / ডিলিট / এডিট
if (isset($_GET['action']) && isset($_GET['category']) && isset($_GET['index'])) {
    $category = $_GET['category'];
    $data = loadData($category);
    $index = (int)$_GET['index'];

    if ($_GET['action'] === 'toggle') {
        $data[$index]['status'] = ($data[$index]['status'] === 'published') ? 'unpublished' : 'published';
    } elseif ($_GET['action'] === 'delete') {
        array_splice($data, $index, 1);
    } elseif ($_GET['action'] === 'edit') {
        // এখানে Edit করা যাবে
        if ($_POST['edit_data']) {
            foreach ($categories[$category] as $field) {
                $key = slugify($field);
                $data[$index][$key] = $_POST[$key] ?? '';
            }
            saveData($category, $data);
            header("Location: ".$_SERVER['PHP_SELF']."?category=$category");
            exit;
        }
    }

    saveData($category, $data);
    header("Location: ".$_SERVER['PHP_SELF']."?category=$category");
    exit;
}

// ডাটা এক্সপোর্ট
if (isset($_GET['export']) && isset($_GET['category'])) {
    $category = $_GET['category'];
    $data = loadData($category);
    $type = $_GET['export'];

    if ($type === 'json') {
        header('Content-Disposition: attachment; filename="'.$category.'.json"');
        header('Content-Type: application/json');
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    } elseif ($type === 'csv') {
        header('Content-Disposition: attachment; filename="'.$category.'.csv"');
        header('Content-Type: text/csv');
        $output = fopen('php://output', 'w');
        if (!empty($data)) {
            fputcsv($output, array_keys($data[0]));
            foreach ($data as $row) {
                fputcsv($output, $row);
            }
        }
        fclose($output);
        exit;
    }
}

// ক্যাটাগরি সিলেক্ট
$selectedCategory = $_GET['category'] ?? array_keys($categories)[0] ?? null;
$selectedData = $selectedCategory ? loadData($selectedCategory) : [];
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <title>অ্যাডমিন প্যানেল</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f4f7fc;
            padding: 30px;
        }
        .container {
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        h1 {
            font-size: 36px;
            text-align: center;
            color: #5c6bc0;
        }
        table th {
            background-color: #3f51b5;
            color: white;
        }
        table td, th {
            text-align: center;
        }
        .btn {
            min-width: 100px;
        }
    </style>
</head>
<body>

<div class="container">
    <h1>অ্যাডমিন প্যানেল</h1>

    <!-- ক্যাটাগরি তৈরি -->
    <h4>নতুন ক্যাটাগরি তৈরি করুন</h4>
    <form method="POST" class="row g-3">
        <div class="col-md-6">
            <input type="text" name="category_name" class="form-control" placeholder="ক্যাটাগরির নাম" required>
        </div>
        <div class="col-md-6">
            <input type="text" name="category_fields" class="form-control" placeholder="কমা দিয়ে ফিল্ড দিন" required>
        </div>
        <div class="col-md-12">
            <button type="submit" name="create_category" class="btn btn-primary w-100">ক্যাটাগরি তৈরি করুন</button>
        </div>
    </form>

    <hr>

    <!-- ক্যাটাগরি সিলেক্ট এবং ডিলিট -->
    <?php if (!empty($categories)): ?>
        <form method="GET" class="mb-3">
            <select name="category" class="form-select" onchange="this.form.submit()">
                <?php foreach ($categories as $cat => $fields): ?>
                    <option value="<?= $cat ?>" <?= $selectedCategory === $cat ? 'selected' : '' ?>><?= ucfirst(str_replace('_', ' ', $cat)) ?></option>
                <?php endforeach; ?>
            </select>
        </form>

        <div class="mb-3">
            <a href="?delete_category=<?= $selectedCategory ?>" class="btn btn-danger w-100" onclick="return confirm('ডিলিট করবেন?')">ক্যাটাগরি ডিলিট</a>
        </div>
    <?php endif; ?>

    <!-- ডাটা যুক্ত -->
    <?php if ($selectedCategory): ?>
        <h4>ডাটা যুক্ত করুন</h4>
        <form method="POST" class="row g-3">
            <input type="hidden" name="data_category" value="<?= $selectedCategory ?>">

            <?php foreach ($categories[$selectedCategory] as $field): ?>
                <div class="col-md-6">
                    <input type="text" name="<?= slugify($field) ?>" class="form-control" placeholder="<?= $field ?>" required>
                </div>
            <?php endforeach; ?>

            <div class="col-md-12">
                <button type="submit" name="add_data" class="btn btn-success w-100">ডাটা যুক্ত করুন</button>
            </div>
        </form>

        <hr>

        <!-- ডাটা টেবিল -->
        <h4>ডাটা তালিকা</h4>
        <table class="table table-striped">
            <thead>
                <tr>
                    <?php foreach ($categories[$selectedCategory] as $field): ?>
                        <th><?= ucfirst($field) ?></th>
                    <?php endforeach; ?>
                    <th>অ্যাকশন</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($selectedData as $index => $entry): ?>
                    <tr>
                        <?php foreach ($categories[$selectedCategory] as $field): ?>
                            <td><?= $entry[slugify($field)] ?></td>
                        <?php endforeach; ?>
                        <td>
                            <a href="?category=<?= $selectedCategory ?>&action=edit&index=<?= $index ?>" class="btn btn-warning">এডিট</a>
                            <a href="?category=<?= $selectedCategory ?>&action=toggle&index=<?= $index ?>" class="btn btn-info"><?= $entry['status'] === 'published' ? 'পাবলিশড' : 'আনপাবলিশড' ?></a>
                            <a href="?category=<?= $selectedCategory ?>&action=delete&index=<?= $index ?>" class="btn btn-danger" onclick="return confirm('আপনি কি এই ডাটা ডিলিট করতে চান?')">ডিলিট</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
