<?php
/**
 * Admin Edit Product - COMPLETE FIXED VERSION
 * Digital Product Store
 */

require_once __DIR__ . '/includes/header.php';

$page_title = 'Edit Product';

// Check if ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    set_flash_message('Invalid product ID.', 'error');
    header('Location: ' . ADMIN_URL . '/products.php');
    exit;
}

$product_id = intval($_GET['id']);

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

if (!$product) {
    set_flash_message('Product not found.', 'error');
    header('Location: ' . ADMIN_URL . '/products.php');
    exit;
}

// Get categories for dropdown
try {
    $categories = $pdo->query("SELECT * FROM categories WHERE is_active = 1 ORDER BY name ASC")->fetchAll();
} catch (PDOException $e) {
    $categories = [];
}

// Get product images
$product_images = get_product_images($product_id);

$errors = [];
$success = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $name = sanitize($_POST['name'] ?? '');
        $slug = sanitize($_POST['slug'] ?? '');
        $description = $_POST['description'] ?? '';
        $short_description = sanitize($_POST['short_description'] ?? '');
        $price = floatval($_POST['price'] ?? 0);
        $sale_price = !empty($_POST['sale_price']) ? floatval($_POST['sale_price']) : null;
        $category_id = intval($_POST['category_id'] ?? 0);
        $stock = intval($_POST['stock'] ?? 0);
        $sku = sanitize($_POST['sku'] ?? '');
        $status = sanitize($_POST['status'] ?? 'active');
        $featured = isset($_POST['featured']) ? 1 : 0;
        $bestseller = isset($_POST['bestseller']) ? 1 : 0;
        $allow_negotiation = isset($_POST['allow_negotiation']) ? 1 : 0;
        $video_url = sanitize($_POST['video_url'] ?? '');
        $download_limit = intval($_POST['download_limit'] ?? 0);
        $download_url = sanitize($_POST['download_url'] ?? '');
        $seo_title = sanitize($_POST['seo_title'] ?? '');
        $seo_description = sanitize($_POST['seo_description'] ?? '');
        $seo_keywords = sanitize($_POST['seo_keywords'] ?? '');
        
        // Validation
        if (empty($name)) {
            $errors[] = 'Product name is required';
        }
        
        if ($price <= 0) {
            $errors[] = 'Price must be greater than 0';
        }
        
        if ($category_id <= 0) {
            $errors[] = 'Please select a category';
        }
        
        // Generate slug if empty
        if (empty($slug)) {
            $slug = slugify($name);
        }
        
        // Check if slug exists (excluding current product)
        $stmt = $pdo->prepare("SELECT id FROM products WHERE slug = ? AND id != ?");
        $stmt->execute([$slug, $product_id]);
        if ($stmt->fetch()) {
            $slug = $slug . '-' . time();
        }
        
        // Handle main image upload
        $image = $product['image'];
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $upload_result = upload_image($_FILES['image'], 'products');
            if ($upload_result['success']) {
                // Delete old image
                if ($image && file_exists('../' . $image)) {
                    unlink('../' . $image);
                }
                $image = $upload_result['path'];
            } else {
                $errors[] = $upload_result['message'];
            }
        }
        
        // Handle digital file upload
        $file_path = $product['file_path'];
        if (isset($_FILES['digital_file']) && $_FILES['digital_file']['error'] === UPLOAD_ERR_OK) {
            $upload_result = upload_product_file($_FILES['digital_file'], 'products/files');
            if ($upload_result['success']) {
                // Delete old file
                if ($file_path && file_exists('../' . $file_path)) {
                    unlink('../' . $file_path);
                }
                $file_path = $upload_result['path'];
            } else {
                $errors[] = $upload_result['message'];
            }
        }
        
        // Handle additional images upload
        if (isset($_FILES['additional_images']) && !empty($_FILES['additional_images']['name'][0])) {
            $file_count = count($_FILES['additional_images']['name']);
            for ($i = 0; $i < $file_count; $i++) {
                if ($_FILES['additional_images']['error'][$i] === UPLOAD_ERR_OK) {
                    $file = [
                        'name' => $_FILES['additional_images']['name'][$i],
                        'type' => $_FILES['additional_images']['type'][$i],
                        'tmp_name' => $_FILES['additional_images']['tmp_name'][$i],
                        'error' => $_FILES['additional_images']['error'][$i],
                        'size' => $_FILES['additional_images']['size'][$i]
                    ];
                    
                    $upload_result = upload_image($file, 'products/gallery');
                    if ($upload_result['success']) {
                        // FIXED: Use only 'image' column
                        $stmt = $pdo->prepare("INSERT INTO product_images (product_id, image, sort_order) VALUES (?, ?, ?)");
                        $stmt->execute([$product_id, $upload_result['path'], $i]);
                    }
                }
            }
        }
        
        // Delete selected additional images
        if (isset($_POST['delete_images']) && is_array($_POST['delete_images'])) {
            foreach ($_POST['delete_images'] as $image_id) {
                // FIXED: Use 'image' column instead of 'image_path'
                $stmt = $pdo->prepare("SELECT image FROM product_images WHERE id = ? AND product_id = ?");
                $stmt->execute([$image_id, $product_id]);
                $img = $stmt->fetch();
                
                if ($img) {
                    // Delete file
                    if (!empty($img['image']) && file_exists('../' . $img['image'])) {
                        unlink('../' . $img['image']);
                    }
                    // Delete record
                    $stmt = $pdo->prepare("DELETE FROM product_images WHERE id = ?");
                    $stmt->execute([$image_id]);
                }
            }
        }
        
        if (empty($errors)) {
            try {
                $stmt = $pdo->prepare("
                    UPDATE products 
                    SET name = ?, slug = ?, description = ?, short_description = ?, 
                        price = ?, sale_price = ?, category_id = ?, stock = ?, 
                        sku = ?, status = ?, featured = ?, bestseller = ?, allow_negotiation = ?,
                        image = ?, file_path = ?, video_url = ?, download_limit = ?,
                        download_url = ?, seo_title = ?, seo_description = ?, seo_keywords = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                
                $stmt->execute([
                    $name, $slug, $description, $short_description,
                    $price, $sale_price, $category_id, $stock,
                    $sku, $status, $featured, $bestseller, $allow_negotiation,
                    $image, $file_path, $video_url, $download_limit,
                    $download_url, $seo_title, $seo_description, $seo_keywords,
                    $product_id
                ]);
                
                // Log activity
                log_admin_activity($pdo, $admin_id, 'update_product', "Updated product: {$name}");
                
                $success = 'Product updated successfully!';
                
                // Refresh product data
                $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
                $stmt->execute([$product_id]);
                $product = $stmt->fetch();
                $product_images = get_product_images($product_id);
                
            } catch (PDOException $e) {
                $errors[] = 'Error updating product: ' . $e->getMessage();
            }
        }
    }
}
?>

<div class="page-header">
    <div>
        <h1>Edit Product</h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/products.php">Products</a></li>
                <li class="breadcrumb-item active">Edit Product</li>
            </ol>
        </nav>
    </div>
    <a href="<?php echo ADMIN_URL; ?>/products.php" class="btn btn-secondary">
        <i class="fas fa-arrow-left me-2"></i>Back to Products
    </a>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <i class="fas fa-exclamation-circle me-2"></i>
        <?php echo implode('<br>', $errors); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="row">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-edit me-2"></i>Product Information
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>
                    
                    <div class="mb-3">
                        <label for="name" class="form-label">Product Name *</label>
                        <input type="text" class="form-control" id="name" name="name" 
                               value="<?php echo htmlspecialchars($product['name']); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="slug" class="form-label">Slug</label>
                        <input type="text" class="form-control" id="slug" name="slug" 
                               value="<?php echo htmlspecialchars($product['slug']); ?>">
                        <small class="text-muted">Leave empty to auto-generate from name</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="5"><?php echo htmlspecialchars($product['description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="short_description" class="form-label">Short Description</label>
                        <textarea class="form-control" id="short_description" name="short_description" rows="2"><?php echo htmlspecialchars($product['short_description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="price" class="form-label">Price *</label>
                            <div class="input-group">
                                <span class="input-group-text"><?php echo get_setting('currency_symbol', '$'); ?></span>
                                <input type="number" class="form-control" id="price" name="price" 
                                       step="0.01" min="0" value="<?php echo $product['price']; ?>" required>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="sale_price" class="form-label">Sale Price</label>
                            <div class="input-group">
                                <span class="input-group-text"><?php echo get_setting('currency_symbol', '$'); ?></span>
                                <input type="number" class="form-control" id="sale_price" name="sale_price" 
                                       step="0.01" min="0" value="<?php echo $product['sale_price'] ?? ''; ?>">
                            </div>
                            <small class="text-muted">Leave empty for no sale</small>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="category_id" class="form-label">Category *</label>
                            <select class="form-select" id="category_id" name="category_id" required>
                                <option value="">Select Category</option>
                                <?php foreach ($categories as $category): ?>
                                    <option value="<?php echo $category['id']; ?>" 
                                            <?php echo $product['category_id'] == $category['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($category['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="stock" class="form-label">Stock Quantity</label>
                            <input type="number" class="form-control" id="stock" name="stock" 
                                   min="0" value="<?php echo $product['stock']; ?>">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="sku" class="form-label">SKU</label>
                            <input type="text" class="form-control" id="sku" name="sku" 
                                   value="<?php echo htmlspecialchars($product['sku'] ?? ''); ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select" id="status" name="status">
                                <option value="active" <?php echo $product['status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo $product['status'] == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                <option value="draft" <?php echo $product['status'] == 'draft' ? 'selected' : ''; ?>>Draft</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="video_url" class="form-label">YouTube Video URL</label>
                        <input type="url" class="form-control" id="video_url" name="video_url" 
                               value="<?php echo htmlspecialchars($product['video_url'] ?? ''); ?>"
                               placeholder="https://www.youtube.com/watch?v=...">
                    </div>
                    
                    <div class="mb-3">
                        <label for="download_limit" class="form-label">Download Limit</label>
                        <input type="number" class="form-control" id="download_limit" name="download_limit" 
                               min="0" value="<?php echo $product['download_limit'] ?? 0; ?>">
                        <small class="text-muted">0 for unlimited downloads</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="download_url" class="form-label">External Download URL</label>
                        <input type="url" class="form-control" id="download_url" name="download_url" 
                               value="<?php echo htmlspecialchars($product['download_url'] ?? ''); ?>"
                               placeholder="https://example.com/download">
                        <small class="text-muted">Optional: External download link</small>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="featured" name="featured" 
                                       <?php echo $product['featured'] ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="featured">Featured Product</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="bestseller" name="bestseller" 
                                       <?php echo $product['bestseller'] ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="bestseller">Bestseller</label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="allow_negotiation" name="allow_negotiation" 
                                       <?php echo ($product['allow_negotiation'] ?? 0) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="allow_negotiation">Allow Price Negotiation</label>
                            </div>
                            <small class="text-muted">Let customers make offers on this product</small>
                        </div>
                    </div>
                    
                    <hr class="my-4">
                    
                    <h5 class="mb-3">SEO Settings</h5>
                    
                    <div class="mb-3">
                        <label for="seo_title" class="form-label">SEO Title</label>
                        <input type="text" class="form-control" id="seo_title" name="seo_title" 
                               value="<?php echo htmlspecialchars($product['seo_title'] ?? ''); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label for="seo_description" class="form-label">SEO Description</label>
                        <textarea class="form-control" id="seo_description" name="seo_description" rows="2"><?php echo htmlspecialchars($product['seo_description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="seo_keywords" class="form-label">SEO Keywords</label>
                        <input type="text" class="form-control" id="seo_keywords" name="seo_keywords" 
                               value="<?php echo htmlspecialchars($product['seo_keywords'] ?? ''); ?>">
                    </div>
                    
                    <hr class="my-4">
                    
                    <h5 class="mb-3">Product Images</h5>
                    
                    <!-- Main Image -->
                    <div class="mb-4">
                        <label class="form-label">Main Product Image</label>
                        <?php if ($product['image']): ?>
                            <div class="mb-2">
                                <img src="<?php echo BASE_URL . '/' . $product['image']; ?>" 
                                     alt="Current Image" class="img-thumbnail" style="max-height: 150px;">
                            </div>
                        <?php endif; ?>
                        <input type="file" class="form-control" id="image" name="image" accept="image/*">
                        <small class="text-muted">Upload a new image to replace the current one</small>
                    </div>
                    
                    <!-- Additional Images -->
                    <div class="mb-4">
                        <label class="form-label">Additional Images</label>
                        
                        <?php if (!empty($product_images)): ?>
                            <div class="row mb-3">
                                <?php foreach ($product_images as $img): ?>
                                    <div class="col-md-3 col-sm-4 mb-3">
                                        <div class="card">
                                            <!-- FIXED: Use 'image' column only -->
                                            <img src="<?php echo BASE_URL . '/' . $img['image']; ?>" 
                                                 class="card-img-top" style="height: 100px; object-fit: cover;">
                                            <div class="card-body p-2 text-center">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" 
                                                           name="delete_images[]" value="<?php echo $img['id']; ?>" id="del_img_<?php echo $img['id']; ?>">
                                                    <label class="form-check-label" for="del_img_<?php echo $img['id']; ?>" style="font-size: 0.75rem;">
                                                        Delete
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <input type="file" class="form-control" id="additional_images" name="additional_images[]" 
                               accept="image/*" multiple>
                        <small class="text-muted">Select multiple images to add to the gallery</small>
                    </div>
                    
                    <!-- Digital File -->
                    <div class="mb-4">
                        <label class="form-label">Digital Product File</label>
                        <?php if ($product['file_path']): ?>
                            <div class="mb-2">
                                <span class="badge bg-info">Current file: <?php echo basename($product['file_path']); ?></span>
                            </div>
                        <?php endif; ?>
                        <input type="file" class="form-control" id="digital_file" name="digital_file">
                        <small class="text-muted">Upload digital product file (ZIP, PDF, etc.)</small>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>Update Product
                        </button>
                        <a href="<?php echo ADMIN_URL; ?>/products.php" class="btn btn-secondary">Cancel</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-lg-4">
        <!-- Product Preview Card -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-eye me-2"></i>Product Preview
            </div>
            <div class="card-body text-center">
                <?php if ($product['image']): ?>
                    <img src="<?php echo BASE_URL . '/' . $product['image']; ?>" 
                         alt="<?php echo htmlspecialchars($product['name']); ?>" 
                         class="img-fluid rounded mb-3" style="max-height: 200px;">
                <?php else: ?>
                    <div class="bg-light rounded p-4 mb-3">
                        <i class="fas fa-image fa-3x text-muted"></i>
                        <p class="text-muted mt-2">No image</p>
                    </div>
                <?php endif; ?>
                
                <h5><?php echo htmlspecialchars($product['name']); ?></h5>
                <p class="text-muted mb-2">SKU: <?php echo htmlspecialchars($product['sku'] ?: 'N/A'); ?></p>
                
                <div class="mb-2">
                    <?php if ($product['sale_price']): ?>
                        <span class="text-decoration-line-through text-muted"><?php echo format_price($product['price']); ?></span>
                        <span class="h4 text-danger ms-2"><?php echo format_price($product['sale_price']); ?></span>
                    <?php else: ?>
                        <span class="h4"><?php echo format_price($product['price']); ?></span>
                    <?php endif; ?>
                </div>
                
                <p class="mb-2">
                    <span class="badge bg-<?php echo $product['status'] == 'active' ? 'success' : 'secondary'; ?>">
                        <?php echo ucfirst($product['status']); ?>
                    </span>
                    <?php if ($product['featured']): ?>
                        <span class="badge bg-warning">Featured</span>
                    <?php endif; ?>
                    <?php if ($product['bestseller']): ?>
                        <span class="badge bg-info">Bestseller</span>
                    <?php endif; ?>
                </p>
                
                <p class="text-muted">Stock: <?php echo $product['stock']; ?> units</p>
                
                <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo $product['slug']; ?>" 
                   target="_blank" class="btn btn-outline-primary btn-sm">
                    <i class="fas fa-external-link-alt me-2"></i>View on Site
                </a>
            </div>
        </div>
        
        <!-- Quick Stats -->
        <div class="card mt-3">
            <div class="card-header">
                <i class="fas fa-chart-bar me-2"></i>Quick Stats
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between mb-2">
                    <span>Total Views:</span>
                    <strong><?php echo number_format($product['views'] ?? 0); ?></strong>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>Times Sold:</span>
                    <strong><?php echo number_format($product['times_sold'] ?? 0); ?></strong>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>Sales Count:</span>
                    <strong><?php echo number_format($product['sales_count'] ?? 0); ?></strong>
                </div>
                <div class="d-flex justify-content-between">
                    <span>Added:</span>
                    <strong><?php echo format_date($product['created_at']); ?></strong>
                </div>
            </div>
        </div>
    </div>
</div>

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