<?php
if (!file_exists('data')) mkdir('data', 0777, true);
if (!file_exists('uploads')) mkdir('uploads', 0777, true);

include 'functions.php';

$categories = loadCategories();
$selectedCategory = $_POST['category'] ?? $_GET['category'] ?? (array_keys($categories)[0] ?? null);
$data = $selectedCategory ? loadData($selectedCategory) : [];

// নতুন ক্যাটাগরি যোগ
if (isset($_POST['create_category'])) {
    $name = trim($_POST['new_category']);
    $fields = array_map('trim', explode(',', $_POST['fields']));
    $slug = slugify($name);

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

// নতুন ডাটা যুক্ত
if (isset($_POST['add_data'])) {
    $imgPath = '';
    if (!empty($_FILES['image']['name'])) {
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $imgPath = 'uploads/' . time() . '_' . rand(1000,9999) . '.' . $ext;
        move_uploaded_file($_FILES['image']['tmp_name'], $imgPath);
    }

    $entry = [];
    foreach ($categories[$selectedCategory]['fields'] as $field) {
        $key = slugify($field);
        $entry[$key] = $_POST[$key] ?? '';
    }

    $entry['imageUrl'] = $imgPath;
    $entry['status'] = 'published';

    $data[] = $entry;
    saveData($selectedCategory, $data);

    header("Location: ?category=$selectedCategory");
    exit;
}

// Publish/Unpublish/Delete
if (isset($_GET['action']) && isset($_GET['index'])) {
    $index = (int)$_GET['index'];
    $action = $_GET['action'];

    if ($action === 'delete') {
        if (!empty($data[$index]['imageUrl']) && file_exists($data[$index]['imageUrl'])) {
            unlink($data[$index]['imageUrl']);
        }
        array_splice($data, $index, 1);
    } elseif ($action === 'toggle') {
        $data[$index]['status'] = ($data[$index]['status'] === 'published') ? 'unpublished' : 'published';
    }

    saveData($selectedCategory, $data);
    header("Location: ?category=$selectedCategory");
    exit;
}
?>
