<?php
// Uključujemo za debug
ini_set('display_errors', 1);
error_reporting(E_ALL);

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 proizvoda
$product_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

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

// Dohvatanje podataka o proizvodu
$product = get_row("SELECT * FROM products WHERE id = ?", [$product_id]);

if (!$product) {
    $_SESSION['error_message'] = 'Proizvod nije pronađen.';
    header('Location: /admin/products/');
    exit;
}

// Dohvatanje kategorija proizvoda
$product_categories = get_rows("
    SELECT category_id FROM product_categories WHERE product_id = ?
", [$product_id]);

$selected_categories = [];
foreach ($product_categories as $cat) {
    $selected_categories[] = $cat['category_id'];
}

// Dohvatanje slika proizvoda
$product_images = get_rows("
    SELECT * FROM product_images WHERE product_id = ? ORDER BY sort_order ASC
", [$product_id]);

// Priprema specifikacija za prikaz
$specifications_text = '';
if (!empty($product['specifications'])) {
    $specs_array = json_decode($product['specifications'], true);
    if (is_array($specs_array)) {
        $specs_lines = [];
        foreach ($specs_array as $spec) {
            if (isset($spec['name']) && isset($spec['value'])) {
                $specs_lines[] = $spec['name'] . ': ' . $spec['value'];
            }
        }
        $specifications_text = implode("\n", $specs_lines);
    } else {
        // Ako nisu u JSON formatu, prikazujemo direktno
        $specifications_text = $product['specifications'];
    }
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // DEBUG: Log the form data
    error_log("FORM SUBMISSION - Product ID: " . $product_id);
    error_log("FORM SUBMISSION - Product name: " . (isset($_POST['product_name']) ? $_POST['product_name'] : 'NOT SET'));
    
    // Validacija obaveznih polja
    $required_fields = ['product_name', 'sku', 'price'];
    
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = ucfirst(str_replace('product_', '', $field)) . ' je obavezno polje.';
        }
    }
    
    // Provera da li je SKU jedinstven (ako je promenjen)
    $sku = trim($_POST['sku']);
    if ($sku !== $product['sku']) {
        $sku_exists = get_row("SELECT id FROM products WHERE sku = ? AND id != ?", [$sku, $product_id]);
        
        if ($sku_exists) {
            $errors[] = 'SKU već postoji. Molimo koristite jedinstveni SKU.';
        }
    }
    
    // Ako nema grešaka, ažuriraj proizvod
    if (empty($errors)) {
        $name = trim($_POST['product_name']);
        error_log("PROCESSING - Product name after trim: " . $name);
        
        $slug = !empty($_POST['slug']) ? trim($_POST['slug']) : create_slug($name);
        
        // Provera da li slug postoji za drugi proizvod
        if ($slug !== $product['slug']) {
            $slug_exists = get_row("SELECT id FROM products WHERE slug = ? AND id != ?", [$slug, $product_id]);
            
            if ($slug_exists) {
                $slug = $slug . '-' . time();
            }
        }
        
        // Priprema podataka za ažuriranje
        $price = floatval($_POST['price']);
        $sale_price = !empty($_POST['sale_price']) ? floatval($_POST['sale_price']) : null;
        $stock = !empty($_POST['stock']) ? intval($_POST['stock']) : 0;
        $short_description = !empty($_POST['short_description']) ? trim($_POST['short_description']) : '';
        $description = !empty($_POST['description']) ? trim($_POST['description']) : '';
        $features = !empty($_POST['features']) ? trim($_POST['features']) : '';
        $meta_title = !empty($_POST['meta_title']) ? trim($_POST['meta_title']) : '';
        $meta_description = !empty($_POST['meta_description']) ? trim($_POST['meta_description']) : '';
        $status = !empty($_POST['status']) ? trim($_POST['status']) : 'draft';
        
        // Obrada specifikacija
        $specifications_json = null;
        if (!empty($_POST['specifications'])) {
            $specs_text = trim($_POST['specifications']);
            $specs_lines = explode("\n", $specs_text);
            $specs_array = [];
            
            foreach ($specs_lines as $line) {
                $line = trim($line);
                if (empty($line)) continue;
                
                $parts = explode(':', $line, 2);
                if (count($parts) == 2) {
                    $spec_name = trim($parts[0]);
                    $value = trim($parts[1]);
                    $specs_array[] = ["name" => $spec_name, "value" => $value];
                }
            }
            
            if (!empty($specs_array)) {
                $specifications_json = json_encode($specs_array, JSON_UNESCAPED_UNICODE);
            }
        }
        
        // Final debug check before database update
        error_log("RIGHT BEFORE DB UPDATE - Name value: " . $name);
        
        try {
            $conn->beginTransaction();
            
            // Ažuriranje proizvoda
            $stmt = $conn->prepare("
                UPDATE products SET 
                name = ?, slug = ?, sku = ?, price = ?, sale_price = ?,
                stock = ?, short_description = ?, description = ?,
                features = ?, specifications = ?, meta_title = ?,
                meta_description = ?, status = ?, updated_at = NOW()
                WHERE id = ?
            ");
            
            $stmt->execute([
                $name, $slug, $sku, $price, $sale_price,
                $stock, $short_description, $description,
                $features, $specifications_json, $meta_title,
                $meta_description, $status, $product_id
            ]);
            
            // Ažuriranje kategorija
            $categories = isset($_POST['categories']) ? $_POST['categories'] : [];
            
            // Brisanje postojećih veza sa kategorijama
            execute_query("DELETE FROM product_categories WHERE product_id = ?", [$product_id]);
            
            
            
            // Ažuriranje preporučenih proizvoda
$recommended_products = isset($_POST['recommended_products']) ? $_POST['recommended_products'] : [];

// Brisanje postojećih preporuka
execute_query("DELETE FROM product_recommendations WHERE product_id = ?", [$product_id]);

// Dodavanje novih preporuka
if (!empty($recommended_products)) {
    $stmt = $conn->prepare("INSERT INTO product_recommendations (product_id, recommended_product_id, sort_order) VALUES (?, ?, ?)");
    
    foreach ($recommended_products as $index => $rec_product_id) {
        $stmt->execute([$product_id, $rec_product_id, $index]);
    }
}
            
            
            // Dodavanje novih veza sa kategorijama
            if (!empty($categories)) {
                foreach ($categories as $category_id) {
                    execute_query("INSERT INTO product_categories (product_id, category_id) VALUES (?, ?)", 
                                [$product_id, $category_id]);
                }
            }
            
            // Upload novih slika
            if (!empty($_FILES['images']['name'][0])) {
                $upload_dir = UPLOADS_PATH . '/products';
                
                // Kreiraj direktorijum ako ne postoji
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }
                
                // Broj postojećih slika (za sort order)
                $sort_order_start = count($product_images);
                
                foreach ($_FILES['images']['name'] as $key => $name) {
                    if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                        $tmp_name = $_FILES['images']['tmp_name'][$key];
                        $extension = pathinfo($name, PATHINFO_EXTENSION);
                        $new_name = uniqid() . '.' . $extension;
                        
if (move_uploaded_file($tmp_name, $upload_dir . '/' . $new_name)) {
    // Generiši thumbnail i large verziju slike
    generate_product_image_sizes($new_name, $upload_dir . '/' . $new_name);
    
    $alt_text = !empty($_POST['image_alts'][$key]) ? trim($_POST['image_alts'][$key]) : $name;
    $sort_order = intval($key);
    
    $stmt = $conn->prepare("
        INSERT INTO product_images (product_id, image, alt_text, sort_order) 
        VALUES (?, ?, ?, ?)
    ");
    
    $stmt->execute([$product_id, $new_name, $alt_text, $sort_order]);
}
                    }
                }
            }
            
            // Brisanje slika ako je zatraženo
            if (!empty($_POST['delete_images'])) {
                foreach ($_POST['delete_images'] as $image_id) {
                    // Prvo dohvati ime slike
                    $image = get_row("SELECT image FROM product_images WHERE id = ? AND product_id = ?", 
                                    [$image_id, $product_id]);
                    
                    if ($image) {
                        // Izbriši fajl ako postoji
                        $image_path = UPLOADS_PATH . '/products/' . $image['image'];
                        if (file_exists($image_path)) {
                            unlink($image_path);
                        }
                        
                        // Izbriši zapis iz baze
                        execute_query("DELETE FROM product_images WHERE id = ?", [$image_id]);
                    }
                }
            }
            
            // Ažuriranje redosleda slika
            if (!empty($_POST['image_orders'])) {
                foreach ($_POST['image_orders'] as $image_id => $order) {
                    execute_query("UPDATE product_images SET sort_order = ? WHERE id = ?", 
                                [intval($order), $image_id]);
                }
            }
            
            $conn->commit();
            
            $success = 'Proizvod je uspešno ažuriran.';
            
            // Osvežavanje podataka o proizvodu
            $product = get_row("SELECT * FROM products WHERE id = ?", [$product_id]);
            $product_images = get_rows("
                SELECT * FROM product_images WHERE product_id = ? ORDER BY sort_order ASC
            ", [$product_id]);
            
            $product_categories = get_rows("
                SELECT category_id FROM product_categories WHERE product_id = ?
            ", [$product_id]);
            
            $selected_categories = [];
            foreach ($product_categories as $cat) {
                $selected_categories[] = $cat['category_id'];
            }
            
            // Osvežavanje specifikacija za prikaz
            $specifications_text = '';
            if (!empty($product['specifications'])) {
                $specs_array = json_decode($product['specifications'], true);
                if (is_array($specs_array)) {
                    $specs_lines = [];
                    foreach ($specs_array as $spec) {
                        if (isset($spec['name']) && isset($spec['value'])) {
                            $specs_lines[] = $spec['name'] . ': ' . $spec['value'];
                        }
                    }
                    $specifications_text = implode("\n", $specs_lines);
                } else {
                    $specifications_text = $product['specifications'];
                }
            }
            
        } catch (Exception $e) {
            $conn->rollBack();
            $errors[] = 'Došlo je do greške: ' . $e->getMessage();
        }
    }
}

// Dobavljanje svih kategorija
$categories = get_rows("SELECT id, name FROM categories ORDER BY name ASC");

// Naslov stranice
$page_title = 'Izmeni proizvod';

// 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 proizvod</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/products/">Proizvodi</a></li>
                    <li class="breadcrumb-item active">Izmeni proizvod</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 proizvodu</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="product_name">Naziv proizvoda <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="product_name" name="product_name" required autocomplete="off" value="<?php echo htmlspecialchars($product['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($product['slug']); ?>">
                                <small class="form-text text-muted">Ostavite prazno za automatsko generisanje.</small>
                            </div>
                            
                            <div class="form-group">
                                <label for="sku">SKU <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="sku" name="sku" required value="<?php echo htmlspecialchars($product['sku']); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="short_description">Kratak opis</label>
                                <textarea class="form-control" id="short_description" name="short_description" rows="3"><?php echo htmlspecialchars($product['short_description']); ?></textarea>
                            </div>
                            
                            <div class="form-group">
                                <label for="description">Detaljan opis</label>
                                <textarea class="form-control" id="description" name="description" rows="6"><?php echo htmlspecialchars($product['description']); ?></textarea>
                            </div>
                            
                            <div class="form-group">
                                <label for="features">Ključne karakteristike</label>
                                <textarea class="form-control" id="features" name="features" rows="5" placeholder="Unesite svaku karakteristiku u novi red"><?php echo htmlspecialchars($product['features']); ?></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Slike</h3>
                        </div>
                        <div class="card-body">
                            <!-- Postojeće slike -->
                            <?php if (!empty($product_images)): ?>
                            <div class="existing-images mb-4">
                                <h5>Postojeće slike</h5>
                                <div class="row">
                                    <?php foreach ($product_images as $image): ?>
                                    <div class="col-md-3 col-sm-4 mb-3">
                                        <div class="card h-100">
                                            <img src="<?php echo UPLOADS_URL . '/products/' . $image['image']; ?>" class="card-img-top" alt="<?php echo htmlspecialchars($image['alt_text']); ?>" style="height: 150px; object-fit: contain;">
                                            <div class="card-body p-2">
                                                <div class="form-group mb-2">
                                                    <input type="text" class="form-control form-control-sm" name="image_alts[<?php echo $image['id']; ?>]" value="<?php echo htmlspecialchars($image['alt_text']); ?>" placeholder="Alt tekst">
                                                </div>
                                                <div class="form-group mb-2">
                                                    <input type="number" class="form-control form-control-sm" name="image_orders[<?php echo $image['id']; ?>]" value="<?php echo $image['sort_order']; ?>" placeholder="Redosled">
                                                </div>
                                                <div class="form-check">
                                                    <input type="checkbox" class="form-check-input" id="delete_image_<?php echo $image['id']; ?>" name="delete_images[]" value="<?php echo $image['id']; ?>">
                                                    <label class="form-check-label" for="delete_image_<?php echo $image['id']; ?>">Obriši</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Dodavanje novih slika -->
                            <div class="form-group">
                                <label>Dodaj nove slike</label>
                                <div class="input-group">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" id="product-images" name="images[]" multiple>
                                        <label class="custom-file-label" for="product-images">Odaberite slike</label>
                                    </div>
                                </div>
                                <small class="form-text text-muted">Možete odabrati više slika odjednom.</small>
                                <div id="image-preview" class="mt-3 d-flex flex-wrap"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Specifikacije</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <textarea class="form-control" id="specifications" name="specifications" rows="5" placeholder="Format: Naziv: Vrednost (po jedan u svakom redu)"><?php echo htmlspecialchars($specifications_text); ?></textarea>
                                <small class="form-text text-muted">Unesite specifikacije u formatu "Naziv: Vrednost", jedan po redu.</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($product['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($product['meta_description']); ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Objavi</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="status">Status</label>
                                <select class="form-control" id="status" name="status">
                                    <option value="draft" <?php echo $product['status'] === 'draft' ? 'selected' : ''; ?>>Nacrt</option>
                                    <option value="active" <?php echo $product['status'] === 'active' ? 'selected' : ''; ?>>Aktivan</option>
                                    <option value="inactive" <?php echo $product['status'] === 'inactive' ? 'selected' : ''; ?>>Neaktivan</option>
                                </select>
                            </div>
                            
                            <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/products/" class="btn btn-default btn-block">Odustani</a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Kategorije</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <div class="categories-list" style="max-height: 200px; overflow-y: auto;">
                                    <?php foreach ($categories as $category): ?>
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="category-<?php echo $category['id']; ?>" name="categories[]" value="<?php echo $category['id']; ?>" <?php echo in_array($category['id'], $selected_categories) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="category-<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></label>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Cena i zalihe</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="price">Redovna cena <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">RSD</span>
                                    </div>
                                    <input type="number" class="form-control" id="price" name="price" step="0.01" required value="<?php echo floatval($product['price']); ?>">
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="sale_price">Akcijska cena</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">RSD</span>
                                    </div>
                                    <input type="number" class="form-control" id="sale_price" name="sale_price" step="0.01" value="<?php echo !empty($product['sale_price']) ? floatval($product['sale_price']) : ''; ?>">
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="stock">Stanje na zalihama</label>
                                <input type="number" class="form-control" id="stock" name="stock" value="<?php echo intval($product['stock']); ?>">
                            </div>
                        </div>
                    </div>
                    
                    
                    <div class="card">
    <div class="card-header">
        <h3 class="card-title">Preporučeni proizvodi</h3>
    </div>
    <div class="card-body">
        <p class="text-muted small mb-2">Izaberite proizvode koji će se prikazivati u sekciji "Kupci često kupuju i". Maks. 4 proizvoda.</p>
        
        <?php
        // Dohvati sve aktivne proizvode osim trenutnog
        $all_products = get_rows("
            SELECT id, name, sku 
            FROM products 
            WHERE status = 'active' AND id != ? 
            ORDER BY name ASC
        ", [$product_id]);
        
        // Dohvati trenutno preporučene proizvode
        $current_recommendations = get_rows("
            SELECT recommended_product_id 
            FROM product_recommendations 
            WHERE product_id = ? 
            ORDER BY sort_order ASC
        ", [$product_id]);
        
        $recommended_ids = array_column($current_recommendations, 'recommended_product_id');
        ?>
        
        <div class="form-group">
            <select name="recommended_products[]" class="form-control select2" multiple>
                <?php foreach($all_products as $p): ?>
                    <option value="<?php echo $p['id']; ?>" <?php echo in_array($p['id'], $recommended_ids) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($p['name']) . ' (' . $p['sku'] . ')'; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <small class="form-text text-muted mt-2">Ako ne izaberete nijedan, sistem će automatski prikazati proizvode iz iste kategorije.</small>
        </div>
    </div>
</div>
                    
                    
                </div>
            </div>
        </form>
    </div>
</section>

<script>
// Preview za nove slike
$(document).ready(function() {
    $('.custom-file-input').on('change', function() {
        var fileInput = $(this);
        var numFiles = fileInput.get(0).files.length;
        var fileName = numFiles > 1 ? numFiles + ' fajlova odabrano' : fileInput.get(0).files[0].name;
        fileInput.siblings('.custom-file-label').html(fileName);
        
        // Preview slika
        var preview = $('#image-preview');
        preview.empty();
        
        for (var i = 0; i < numFiles; i++) {
            var file = fileInput.get(0).files[i];
            var reader = new FileReader();
            
            reader.onload = function(e) {
                var img = $('<div class="image-item mr-2 mb-2"><img src="' + e.target.result + '" class="img-thumbnail" style="max-width:150px; max-height:150px;"></div>');
                preview.append(img);
            }
            
            reader.readAsDataURL(file);
        }
    });
});

// Inicijalizacija Select2 za preporučene proizvode
$('.select2').select2({
    placeholder: 'Izaberite preporučene proizvode',
    allowClear: true,
    maximumSelectionLength: 4,
    language: {
        maximumSelected: function() {
            return 'Možete izabrati najviše 4 proizvoda';
        }
    }
});

</script>

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