<?php
// admin/add-product.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$categories = getCategories($pdo);
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name'] ?? '');
    $category_id = intval($_POST['category_id'] ?? 0);
    $subcategory_id = $_POST['subcategory_id'] ? intval($_POST['subcategory_id']) : null;
    $price = floatval($_POST['price'] ?? 0);
    $sale_price = $_POST['sale_price'] ? floatval($_POST['sale_price']) : null;
    $stock = intval($_POST['stock'] ?? 0);
    $description = sanitize($_POST['description'] ?? '');
    $specification = sanitize($_POST['specification'] ?? '');
    $featured = isset($_POST['featured']) ? 1 : 0;
    $new = isset($_POST['new']) ? 1 : 0;
    $top_selling = isset($_POST['top_selling']) ? 1 : 0;
    
    // Validate
    if (empty($name)) {
        $error = 'Product name is required';
    } elseif ($category_id == 0) {
        $error = 'Category is required';
    } elseif ($price <= 0) {
        $error = 'Price must be greater than 0';
    } else {
        // Generate slug
        $slug = generateSlug($name);
        
        // Check if slug exists
        $stmt = $pdo->prepare("SELECT id FROM products WHERE slug = ?");
        $stmt->execute([$slug]);
        if ($stmt->fetch()) {
            $slug = $slug . '-' . time();
        }
        
        // Generate product code
        $product_code = 'P-' . date('Ymd') . '-' . rand(1000, 9999);
        
        // Handle image upload
        $image = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/../assets/images/products/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $image = time() . '_' . uniqid() . '.' . $ext;
            move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $image);
        }
        
        // Insert product
        $stmt = $pdo->prepare("INSERT INTO products (
            category_id, subcategory_id, name, slug, product_code, description, 
            specification, price, sale_price, stock, image, featured, new, top_selling
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $category_id, $subcategory_id, $name, $slug, $product_code, $description,
            $specification, $price, $sale_price, $stock, $image, $featured, $new, $top_selling
        ]);
        
        $product_id = $pdo->lastInsertId();
        
        // Handle attributes
        if (isset($_POST['attribute_name']) && is_array($_POST['attribute_name'])) {
            foreach ($_POST['attribute_name'] as $i => $attr_name) {
                if (!empty($attr_name) && !empty($_POST['attribute_value'][$i])) {
                    $stmt = $pdo->prepare("INSERT INTO product_attributes (
                        product_id, attribute_name, attribute_value, extra_price, stock
                    ) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $product_id,
                        $attr_name,
                        $_POST['attribute_value'][$i],
                        floatval($_POST['extra_price'][$i] ?? 0),
                        intval($_POST['attr_stock'][$i] ?? 0)
                    ]);
                }
            }
        }
        
        $success = 'Product added successfully!';
        // Clear form data
        $_POST = [];
    }
}

include 'header.php';
?>

<div class="admin-card">
    <h5 class="card-title">Add Product</h5>
    
    <?php if ($error): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <?php if ($success): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    
    <form method="POST" enctype="multipart/form-data">
        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label class="form-label">Product Name *</label>
                    <input type="text" name="name" class="form-control" value="<?php echo $_POST['name'] ?? ''; ?>" required>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Category *</label>
                    <select name="category_id" id="category_id" class="form-control" required>
                        <option value="">Select Category</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" <?php echo (($_POST['category_id'] ?? 0) == $cat['id']) ? 'selected' : ''; ?>>
                            <?php echo $cat['name']; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Subcategory</label>
                    <select name="subcategory_id" id="subcategory_id" class="form-control">
                        <option value="">Select Subcategory</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Price (TK) *</label>
                    <input type="number" name="price" class="form-control" step="0.01" value="<?php echo $_POST['price'] ?? ''; ?>" required>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Sale Price (TK)</label>
                    <input type="number" name="sale_price" class="form-control" step="0.01" value="<?php echo $_POST['sale_price'] ?? ''; ?>">
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Stock *</label>
                    <input type="number" name="stock" class="form-control" value="<?php echo $_POST['stock'] ?? 0; ?>" required>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="mb-3">
                    <label class="form-label">Product Image</label>
                    <input type="file" name="image" class="form-control" accept="image/*">
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="3"><?php echo $_POST['description'] ?? ''; ?></textarea>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Specification</label>
                    <textarea name="specification" class="form-control" rows="3"><?php echo $_POST['specification'] ?? ''; ?></textarea>
                </div>
                
                <div class="mb-3">
                    <div class="form-check">
                        <input type="checkbox" name="featured" class="form-check-input" id="featured" <?php echo isset($_POST['featured']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="featured">Featured Product</label>
                    </div>
                    <div class="form-check">
                        <input type="checkbox" name="new" class="form-check-input" id="new" <?php echo isset($_POST['new']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="new">New Product</label>
                    </div>
                    <div class="form-check">
                        <input type="checkbox" name="top_selling" class="form-check-input" id="top_selling" <?php echo isset($_POST['top_selling']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="top_selling">Top Selling</label>
                    </div>
                </div>
            </div>
        </div>
        
        <h6 class="mt-3">Product Attributes</h6>
        <div id="attributes-container">
            <div class="row attribute-row g-2">
                <div class="col-md-3">
                    <input type="text" name="attribute_name[]" class="form-control" placeholder="Attribute Name (e.g. Size)">
                </div>
                <div class="col-md-3">
                    <input type="text" name="attribute_value[]" class="form-control" placeholder="Value (e.g. Large)">
                </div>
                <div class="col-md-2">
                    <input type="number" name="extra_price[]" class="form-control" placeholder="Extra Price" step="0.01">
                </div>
                <div class="col-md-2">
                    <input type="number" name="attr_stock[]" class="form-control" placeholder="Stock">
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-danger w-100" onclick="removeAttribute(this)">Remove</button>
                </div>
            </div>
        </div>
        <button type="button" class="btn btn-secondary mt-2" onclick="addAttribute()">
            <i class="fa-solid fa-plus"></i> Add Attribute
        </button>
        
        <div class="mt-4">
            <button type="submit" class="btn btn-primary">Save Product</button>
            <a href="products.php" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
</div>

<script>
// Load subcategories
$('#category_id').change(function() {
    var category_id = $(this).val();
    if (category_id) {
        $.ajax({
            url: 'get-subcategories.php',
            type: 'POST',
            data: {category_id: category_id},
            dataType: 'json',
            success: function(data) {
                $('#subcategory_id').html('<option value="">Select Subcategory</option>');
                $.each(data, function(key, value) {
                    $('#subcategory_id').append('<option value="'+value.id+'">'+value.name+'</option>');
                });
            }
        });
    }
});

// Add attribute row
function addAttribute() {
    var html = `
        <div class="row attribute-row g-2 mt-2">
            <div class="col-md-3">
                <input type="text" name="attribute_name[]" class="form-control" placeholder="Attribute Name">
            </div>
            <div class="col-md-3">
                <input type="text" name="attribute_value[]" class="form-control" placeholder="Value">
            </div>
            <div class="col-md-2">
                <input type="number" name="extra_price[]" class="form-control" placeholder="Extra Price" step="0.01">
            </div>
            <div class="col-md-2">
                <input type="number" name="attr_stock[]" class="form-control" placeholder="Stock">
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-danger w-100" onclick="removeAttribute(this)">Remove</button>
            </div>
        </div>
    `;
    $('#attributes-container').append(html);
}

function removeAttribute(btn) {
    $(btn).closest('.attribute-row').remove();
}
</script>

<?php include 'footer.php'; ?>