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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id <= 0) {
    $_SESSION['error_msg'] = 'Invalid product ID';
    header('Location: products.php');
    exit;
}

// Get product
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();

if (!$product) {
    $_SESSION['error_msg'] = 'Product not found';
    header('Location: products.php');
    exit;
}

// Get product attributes
$stmt = $pdo->prepare("SELECT * FROM product_attributes WHERE product_id = ?");
$stmt->execute([$id]);
$attributes = $stmt->fetchAll();

$categories = getCategories($pdo);
$error_msg = '';
$success_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['name']) ? sanitize($_POST['name']) : '';
    $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
    $subcategory_id = isset($_POST['subcategory_id']) && !empty($_POST['subcategory_id']) ? intval($_POST['subcategory_id']) : null;
    $price = isset($_POST['price']) ? floatval($_POST['price']) : 0;
    $sale_price = isset($_POST['sale_price']) && !empty($_POST['sale_price']) ? floatval($_POST['sale_price']) : null;
    $stock = isset($_POST['stock']) ? intval($_POST['stock']) : 0;
    $description = isset($_POST['description']) ? sanitize($_POST['description']) : '';
    $specification = isset($_POST['specification']) ? sanitize($_POST['specification']) : '';
    $featured = isset($_POST['featured']) ? 1 : 0;
    $new = isset($_POST['new']) ? 1 : 0;
    $top_selling = isset($_POST['top_selling']) ? 1 : 0;
    $status = isset($_POST['status']) ? 1 : 0;
    
    if (empty($name)) {
        $error_msg = 'Product name is required';
    } elseif ($category_id == 0) {
        $error_msg = 'Category is required';
    } elseif ($price <= 0) {
        $error_msg = 'Price must be greater than 0';
    } else {
        // Update product
        $sql = "UPDATE products SET 
                category_id = ?, subcategory_id = ?, name = ?, 
                price = ?, sale_price = ?, stock = ?, 
                description = ?, specification = ?, 
                featured = ?, new = ?, top_selling = ?, status = ?";
        $params = [$category_id, $subcategory_id, $name, $price, $sale_price, $stock, 
                   $description, $specification, $featured, $new, $top_selling, $status];
        
        // Handle image upload
        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);
            
            // Delete old image
            if ($product['image'] && file_exists($upload_dir . $product['image'])) {
                unlink($upload_dir . $product['image']);
            }
            
            $sql .= ", image = ?";
            $params[] = $image;
        }
        
        $sql .= " WHERE id = ?";
        $params[] = $id;
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        // Delete existing attributes
        $stmt = $pdo->prepare("DELETE FROM product_attributes WHERE product_id = ?");
        $stmt->execute([$id]);
        
        // Insert new 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([
                        $id,
                        $attr_name,
                        $_POST['attribute_value'][$i],
                        floatval($_POST['extra_price'][$i] ?? 0),
                        intval($_POST['attr_stock'][$i] ?? 0)
                    ]);
                }
            }
        }
        
        $_SESSION['success_msg'] = 'Product updated successfully!';
        header('Location: products.php');
        exit;
    }
}

include 'header.php';
?>

<div class="admin-card">
    <h5 class="card-title">Edit Product</h5>
    
    <?php if ($error_msg): ?>
    <div class="alert alert-danger"><?php echo $error_msg; ?></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 htmlspecialchars($product['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 ($product['category_id'] == $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 $product['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 $product['sale_price']; ?>">
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Stock *</label>
                    <input type="number" name="stock" class="form-control" value="<?php echo $product['stock']; ?>" required>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="mb-3">
                    <label class="form-label">Product Image</label>
                    <?php if ($product['image']): ?>
                    <div class="mb-2">
                        <img src="../assets/images/products/<?php echo $product['image']; ?>" alt="Current" style="width:100px; height:100px; object-fit:cover; border-radius:8px;">
                    </div>
                    <?php endif; ?>
                    <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 htmlspecialchars($product['description']); ?></textarea>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Specification</label>
                    <textarea name="specification" class="form-control" rows="3"><?php echo htmlspecialchars($product['specification']); ?></textarea>
                </div>
                
                <div class="mb-3">
                    <div class="form-check">
                        <input type="checkbox" name="featured" class="form-check-input" id="featured" <?php echo $product['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 $product['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 $product['top_selling'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="top_selling">Top Selling</label>
                    </div>
                    <div class="form-check">
                        <input type="checkbox" name="status" class="form-check-input" id="status" <?php echo $product['status'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="status">Active</label>
                    </div>
                </div>
            </div>
        </div>
        
        <h6 class="mt-3">Product Attributes</h6>
        <div id="attributes-container">
            <?php if (empty($attributes)): ?>
            <div class="row attribute-row g-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>
            <?php else: ?>
            <?php foreach ($attributes as $attr): ?>
            <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" value="<?php echo htmlspecialchars($attr['attribute_name']); ?>">
                </div>
                <div class="col-md-3">
                    <input type="text" name="attribute_value[]" class="form-control" placeholder="Value" value="<?php echo htmlspecialchars($attr['attribute_value']); ?>">
                </div>
                <div class="col-md-2">
                    <input type="number" name="extra_price[]" class="form-control" placeholder="Extra Price" step="0.01" value="<?php echo $attr['extra_price']; ?>">
                </div>
                <div class="col-md-2">
                    <input type="number" name="attr_stock[]" class="form-control" placeholder="Stock" value="<?php echo $attr['stock']; ?>">
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-danger w-100" onclick="removeAttribute(this)">Remove</button>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </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">Update 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>');
                });
                // Set selected subcategory
                <?php if ($product['subcategory_id']): ?>
                $('#subcategory_id').val(<?php echo $product['subcategory_id']; ?>);
                <?php endif; ?>
            }
        });
    }
});

// Trigger change to load subcategories
$(document).ready(function() {
    $('#category_id').trigger('change');
});

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