<?php
require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../includes/admin-functions.php';

// Provera da li je korisnik prijavljen kao admin
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Obrada forme
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validacija obaveznih polja
    $required_fields = ['name'];
    
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = ucfirst($field) . ' je obavezno polje.';
        }
    }
    
    // Ako nema grešaka, dodaj kategoriju
    if (empty($errors)) {
        $name = trim($_POST['name']);
        $slug = !empty($_POST['slug']) ? create_slug($_POST['slug']) : create_slug($name);
        
        // Provera da li slug već postoji
        $slug_exists = get_row("SELECT id FROM categories WHERE slug = ?", [$slug]);
        if ($slug_exists) {
            $slug = $slug . '-' . time();
        }
        
        // Priprema podataka
        $parent_id = !empty($_POST['parent_id']) ? intval($_POST['parent_id']) : null;
        $description = !empty($_POST['description']) ? trim($_POST['description']) : '';
        $seo_content = !empty($_POST['seo_content']) ? trim($_POST['seo_content']) : '';
        $meta_title = !empty($_POST['meta_title']) ? trim($_POST['meta_title']) : '';
        $meta_description = !empty($_POST['meta_description']) ? trim($_POST['meta_description']) : '';
        
        try {
            $conn->beginTransaction();
            
            // Upload slike kategorije
            $image_name = null;
            if (!empty($_FILES['image']['name']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $upload_dir = UPLOADS_PATH . '/categories';
                
                // Kreiraj direktorijum ako ne postoji
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }
                
                $tmp_name = $_FILES['image']['tmp_name'];
                $extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
                $image_name = uniqid() . '.' . $extension;
                
                if (!move_uploaded_file($tmp_name, $upload_dir . '/' . $image_name)) {
                    throw new Exception('Greška prilikom upload-a slike.');
                }
            }
            
            // Dodavanje kategorije
            $stmt = $conn->prepare("
                INSERT INTO categories (
                    name, slug, parent_id, description, seo_content, meta_title, meta_description, image
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $name, $slug, $parent_id, $description, $seo_content, $meta_title, $meta_description, $image_name
            ]);
            
            $category_id = $conn->lastInsertId();
            
            $conn->commit();
            
            // Preusmeravanje na edit stranicu
            $_SESSION['success_message'] = 'Kategorija je uspešno dodata.';
            header('Location: /admin/categories/edit.php?id=' . $category_id);
            exit;
        } catch (Exception $e) {
            $conn->rollBack();
            $errors[] = 'Došlo je do greške: ' . $e->getMessage();
        }
    }
}

// Dohvatanje svih kategorija za roditeljski select
$all_categories = get_rows("SELECT id, name, parent_id FROM categories ORDER BY name ASC");

// Formiranje hijerarhije kategorija
$categories_hierarchy = [];
foreach ($all_categories as $cat) {
    if (empty($cat['parent_id'])) {
        $cat['level'] = 0;
        $categories_hierarchy[] = $cat;
        
        // Dodaj podkategorije
        foreach ($all_categories as $subcat) {
            if ($subcat['parent_id'] == $cat['id']) {
                $subcat['level'] = 1;
                $subcat['name'] = '— ' . $subcat['name'];
                $categories_hierarchy[] = $subcat;
            }
        }
    }
}

// Naslov stranice
$page_title = 'Dodaj kategoriju';

// Uključivanje header-a
require_once '../includes/header.php';
?>

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Dodaj kategoriju</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/admin/">Kontrolna tabla</a></li>
                    <li class="breadcrumb-item"><a href="/admin/categories/">Kategorije</a></li>
                    <li class="breadcrumb-item active">Dodaj kategoriju</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<section class="content">
    <div class="container-fluid">
        <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $error): ?>
                <li><?php echo $error; ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
        
        <form action="" method="post" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Informacije o kategoriji</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="name">Naziv kategorije <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name" name="name" required value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="slug">Slug (URL)</label>
                                <input type="text" class="form-control" id="slug" name="slug" value="<?php echo isset($_POST['slug']) ? htmlspecialchars($_POST['slug']) : ''; ?>">
                                <small class="form-text text-muted">Ostavite prazno za automatsko generisanje.</small>
                            </div>
                            
                            <div class="form-group">
                                <label for="parent_id">Roditeljska kategorija</label>
                                <select class="form-control" id="parent_id" name="parent_id">
                                    <option value="">Nema (glavna kategorija)</option>
                                    <?php foreach ($categories_hierarchy as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php echo isset($_POST['parent_id']) && $_POST['parent_id'] == $cat['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cat['name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="description">Opis (kratak, prikazuje se na vrhu stranice)</label>
                                <textarea class="form-control" id="description" name="description" rows="5"><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
                            </div>
                            
                            <div class="form-group">
                                <label for="seo_content">SEO Sadržaj (duži, prikazuje se na dnu stranice)</label>
                                <textarea class="form-control" id="seo_content" name="seo_content" rows="8"><?php echo isset($_POST['seo_content']) ? htmlspecialchars($_POST['seo_content']) : ''; ?></textarea>
                                <small class="form-text text-muted">Detaljniji tekst za SEO optimizaciju, prikazuje se na dnu stranice.</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">SEO</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="meta_title">Meta naslov</label>
                                <input type="text" class="form-control" id="meta_title" name="meta_title" value="<?php echo isset($_POST['meta_title']) ? htmlspecialchars($_POST['meta_title']) : ''; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="meta_description">Meta opis</label>
                                <textarea class="form-control" id="meta_description" name="meta_description" rows="3"><?php echo isset($_POST['meta_description']) ? htmlspecialchars($_POST['meta_description']) : ''; ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Slika</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="image">Slika kategorije</label>
                                <div class="input-group">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" id="image" name="image" accept="image/*">
                                        <label class="custom-file-label" for="image">Odaberite sliku</label>
                                    </div>
                                </div>
                                <div id="image-preview" class="mt-3"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Objavi</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <button type="submit" class="btn btn-primary btn-block">Sačuvaj kategoriju</button>
                            </div>
                            
                            <div class="form-group mt-3">
                                <a href="/admin/categories/" class="btn btn-default btn-block">Odustani</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>

<script>
// Preview za sliku
$(document).ready(function() {
    $('.custom-file-input').on('change', function() {
        var fileName = $(this).val().split('\\').pop();
        $(this).siblings('.custom-file-label').html(fileName);
        
        // Prikaži preview slike
        var preview = $('#image-preview');
        preview.empty();
        
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            
            reader.onload = function(e) {
                var img = $('<img class="img-thumbnail" style="max-height:200px;">').attr('src', e.target.result);
                preview.append(img);
            }
            
            reader.readAsDataURL(this.files[0]);
        }
    });
});
</script>

<?php require_once '../includes/footer.php'; ?>