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

// Check if user is logged in and is admin
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate required fields
    $required_fields = ['name', 'sku', 'price'];
    $errors = [];
    
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = ucfirst($field) . ' is required.';
        }
    }
    
    // Validate SKU uniqueness
    $sku = trim($_POST['sku']);
    $sku_exists = get_row("SELECT id FROM products WHERE sku = ?", [$sku]);
    
    if ($sku_exists) {
        $errors[] = 'SKU already exists. Please use a unique SKU.';
    }
    
    // If no errors, insert product
    if (empty($errors)) {
        $name = trim($_POST['name']);
        $slug = create_slug($name);
        
        // Check if slug exists
        $slug_exists = get_row("SELECT id FROM products WHERE slug = ?", [$slug]);
        if ($slug_exists) {
            $slug = $slug . '-' . time();
        }
        
        // Prepare product data
        $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']) : '';
        $specifications = !empty($_POST['specifications']) ? trim($_POST['specifications']) : '';
        $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';
        
        try {
            $conn->beginTransaction();
            
            // Insert product
            $stmt = $conn->prepare("
                INSERT INTO products (
                    sku, name, slug, price, sale_price, stock, short_description, 
                    description, features, specifications, meta_title, meta_description, status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $sku, $name, $slug, $price, $sale_price, $stock, $short_description,
                $description, $features, $specifications, $meta_title, $meta_description, $status
            ]);
            
            $product_id = $conn->lastInsertId();
            
            // Add product categories
            if (!empty($_POST['categories'])) {
                $categories = is_array($_POST['categories']) ? $_POST['categories'] : [$_POST['categories']];
                
                foreach ($categories as $category_id) {
                    $stmt = $conn->prepare("INSERT INTO product_categories (product_id, category_id) VALUES (?, ?)");
                    $stmt->execute([$product_id, $category_id]);
                }
            }
            
            // Upload product images
            if (!empty($_FILES['images']['name'][0])) {
                $upload_dir = UPLOADS_PATH . '/products';
                
                // Create directory if it doesn't exist
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }
                
                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]);
}
                    }
                }
            }
            
            $conn->commit();
            
            // Redirect to edit page
            $_SESSION['success_message'] = 'Product added successfully.';
            header('Location: /admin/products/edit.php?id=' . $product_id);
            exit;
        } catch (Exception $e) {
            $conn->rollBack();
            $errors[] = 'An error occurred: ' . $e->getMessage();
        }
    }
}

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

// Page title
$page_title = 'Add Product';

// Include header
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">Add Product</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/admin/">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="/admin/products/">Products</a></li>
                    <li class="breadcrumb-item active">Add Product</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">Product Information</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="name">Product Name <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="sku">SKU <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="sku" name="sku" required value="<?php echo isset($_POST['sku']) ? htmlspecialchars($_POST['sku']) : ''; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="short_description">Short Description</label>
                                <textarea class="form-control" id="short_description" name="short_description" rows="3"><?php echo isset($_POST['short_description']) ? htmlspecialchars($_POST['short_description']) : ''; ?></textarea>
                            </div>
                            
                            <div class="form-group">
                                <label for="description">Description</label>
                                <textarea class="form-control editor" id="description" name="description" rows="6"><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
                            </div>
                            
                            <div class="form-group">
                                <label for="features">Key Features</label>
                                <textarea class="form-control" id="features" name="features" rows="5" placeholder="Enter each feature on a new line"><?php echo isset($_POST['features']) ? htmlspecialchars($_POST['features']) : ''; ?></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Images</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
    <label for="product-images">Slike proizvoda</label>
    <div id="dropzone-upload" class="dropzone">
        <div class="dz-message" data-dz-message>
            <span>Prevucite slike ovde ili kliknite za upload</span>
        </div>
    </div>
    <small class="form-text text-muted">Prva slika će biti korišćena kao glavna slika proizvoda.</small>
</div>
<input type="hidden" id="product-images-json" name="images_json">
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Specifications</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <textarea class="form-control" id="specifications" name="specifications" rows="5" placeholder="Format: Name: Value (one per line)"><?php echo isset($_POST['specifications']) ? htmlspecialchars($_POST['specifications']) : ''; ?></textarea>
                                <small class="form-text text-muted">Enter specifications in the format "Name: Value", one per line.</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 Title</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 Description</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">Publish</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 isset($_POST['status']) && $_POST['status'] === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                    <option value="active" <?php echo isset($_POST['status']) && $_POST['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo isset($_POST['status']) && $_POST['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <button type="submit" class="btn btn-primary btn-block">Save Product</button>
                            </div>
                            
                            <div class="form-group mt-3">
                                <a href="/admin/products/" class="btn btn-default btn-block">Cancel</a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Categories</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="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="category-<?php echo $category['id']; ?>" name="categories[]" value="<?php echo $category['id']; ?>" <?php echo isset($_POST['categories']) && in_array($category['id'], $_POST['categories']) ? 'checked' : ''; ?>>
                                        <label class="custom-control-label" for="category-<?php echo $category['id']; ?>"><?php echo $category['name']; ?></label>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Pricing & Inventory</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="price">Regular Price <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 isset($_POST['price']) ? floatval($_POST['price']) : ''; ?>">
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="sale_price">Sale Price</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 isset($_POST['sale_price']) ? floatval($_POST['sale_price']) : ''; ?>">
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="stock">Stock Quantity</label>
                                <input type="number" class="form-control" id="stock" name="stock" value="<?php echo isset($_POST['stock']) ? intval($_POST['stock']) : '0'; ?>">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>

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