<?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;
}

// Provera da li je prosleđen ID kategorije
$category_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($category_id <= 0) {
    header('Location: /admin/categories/');
    exit;
}

// Dohvatanje podataka o kategoriji
$category = get_row("SELECT * FROM categories WHERE id = ?", [$category_id]);

if (!$category) {
    $_SESSION['error_message'] = 'Kategorija nije pronađena.';
    header('Location: /admin/categories/');
    exit;
}

// Obrada forme za ažuriranje kategorije
$errors = [];
$success = '';

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, ažuriraj 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 za drugu kategoriju
        if ($slug !== $category['slug']) {
            $slug_exists = get_row("SELECT id FROM categories WHERE slug = ? AND id != ?", [$slug, $category_id]);
            
            if ($slug_exists) {
                $slug = $slug . '-' . time();
            }
        }
        
        // Priprema podataka za ažuriranje
        $parent_id = !empty($_POST['parent_id']) ? intval($_POST['parent_id']) : null;
        
        // Provera da kategorija ne može biti svoj roditelj ili dete
        if ($parent_id == $category_id) {
            $errors[] = 'Kategorija ne može biti sopstveni roditelj.';
        } else {
            // Proveri da nije dete koje bi dovelo do cirkularnosti
            $current_parent = $parent_id;
            while ($current_parent) {
                $parent_info = get_row("SELECT parent_id FROM categories WHERE id = ?", [$current_parent]);
                
                if ($parent_info && $parent_info['parent_id'] == $category_id) {
                    $errors[] = 'Ne možete postaviti podkategoriju kao roditelja - to bi dovelo do ciklične strukture.';
                    break;
                }
                
                $current_parent = $parent_info ? $parent_info['parent_id'] : null;
            }
        }
        
        if (empty($errors)) {
            $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 nove slike ako je odabrana
                $image_name = $category['image']; // Zadržavanje postojeće slike kao default
                
                if (!empty($_POST['delete_image']) && !empty($category['image'])) {
                    // Brisanje postojeće slike
                    $image_path = UPLOADS_PATH . '/categories/' . $category['image'];
                    if (file_exists($image_path)) {
                        unlink($image_path);
                    }
                    $image_name = null;
                }
                
                // Dodavanje nove slike ako je uploadovana
                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);
                    }
                    
                    // Obriši staru sliku ako postoji
                    if (!empty($category['image'])) {
                        $old_image_path = $upload_dir . '/' . $category['image'];
                        if (file_exists($old_image_path)) {
                            unlink($old_image_path);
                        }
                    }
                    
                    $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.');
                    }
                }
                
                // Ažuriranje kategorije
                $stmt = $conn->prepare("
                    UPDATE categories SET 
                    name = ?, slug = ?, parent_id = ?, description = ?, seo_content = ?,
                    meta_title = ?, meta_description = ?, image = ?, 
                    updated_at = NOW()
                    WHERE id = ?
                ");
                
                $stmt->execute([
                    $name, $slug, $parent_id, $description, $seo_content,
                    $meta_title, $meta_description, $image_name, 
                    $category_id
                ]);
                
                $conn->commit();
                
                $success = 'Kategorija je uspešno ažurirana.';
                
                // Osvežavanje podataka o kategoriji
                $category = get_row("SELECT * FROM categories WHERE id = ?", [$category_id]);
            } 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 WHERE id != ? ORDER BY name ASC", [$category_id]);

// 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['id'] != $category_id) {
                $subcat['level'] = 1;
                $subcat['name'] = '— ' . $subcat['name'];
                $categories_hierarchy[] = $subcat;
            }
        }
    }
}

// Naslov stranice
$page_title = 'Izmeni 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">Izmeni 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">Izmeni 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; ?>
        
        <?php if (!empty($success)): ?>
        <div class="alert alert-success">
            <?php echo $success; ?>
        </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 htmlspecialchars($category['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 htmlspecialchars($category['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 $category['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 htmlspecialchars($category['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 htmlspecialchars($category['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 htmlspecialchars($category['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 htmlspecialchars($category['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">
                            <?php if (!empty($category['image'])): ?>
                            <div class="form-group">
                                <label>Trenutna slika</label>
                                <div class="mb-3">
                                    <img src="<?php echo UPLOADS_URL . '/categories/' . $category['image']; ?>" class="img-thumbnail" style="max-height:200px;">
                                </div>
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="delete_image" name="delete_image" value="1">
                                    <label class="form-check-label" for="delete_image">Obriši ovu sliku</label>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <div class="form-group">
                                <label for="image">Nova 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 novu 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 izmene</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'; ?>