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

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

$page_title = 'Add Product';

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

// Handle form submission
$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $name = sanitize($_POST['name'] ?? '');
        $slug = slugify($_POST['slug'] ?? $name);
        $category_id = (int)($_POST['category_id'] ?? 0);
        $price = (float)($_POST['price'] ?? 0);
        $sale_price = (float)($_POST['sale_price'] ?? 0);
        $stock = (int)($_POST['stock'] ?? 0);
        $sku = sanitize($_POST['sku'] ?? '');
        $short_description = sanitize($_POST['short_description'] ?? '');
        $description = $_POST['description'] ?? '';

        // ✅ FIXED
        $youtube_url = sanitize($_POST['youtube_url'] ?? '');

        $download_limit = (int)($_POST['download_limit'] ?? 0);
        $download_url = sanitize($_POST['download_url'] ?? '');
        $featured = isset($_POST['featured']) ? 1 : 0;
        $bestseller = isset($_POST['bestseller']) ? 1 : 0;
        $allow_negotiation = isset($_POST['allow_negotiation']) ? 1 : 0;
        $status = sanitize($_POST['status'] ?? 'active');
        $seo_title = sanitize($_POST['seo_title'] ?? '');
        $seo_description = sanitize($_POST['seo_description'] ?? '');
        $seo_keywords = sanitize($_POST['seo_keywords'] ?? '');

        if (empty($name)) $errors[] = 'Product name is required.';
        if ($price <= 0) $errors[] = 'Price must be greater than 0.';
        if ($sale_price > 0 && $sale_price >= $price) $errors[] = 'Sale price must be less than regular price.';
        if ($category_id <= 0) $errors[] = 'Please select a category.';

        if (empty($errors)) {
            $stmt = $pdo->prepare("SELECT id FROM products WHERE slug = ?");
            $stmt->execute([$slug]);
            if ($stmt->fetch()) {
                $slug .= '-' . time();
            }
        }

        // Image upload
        $image = '';
        if (!empty($_FILES['image']['name'])) {
            $upload_result = upload_image($_FILES['image'], 'products');
            if ($upload_result['success']) {
                $image = $upload_result['path'];
            } else {
                $errors[] = 'Image upload failed: ' . $upload_result['message'];
            }
        }

        // File upload
        $file_path = '';
        if (!empty($_FILES['digital_file']['name'])) {
            $file_result = upload_product_file($_FILES['digital_file'], 'products/files');
            if ($file_result['success']) {
                $file_path = $file_result['path'];
            } else {
                $errors[] = 'File upload failed: ' . $file_result['message'];
            }
        }

        if (empty($errors)) {
            try {
                $stmt = $pdo->prepare("INSERT INTO products 
                    (name, slug, category_id, price, sale_price, stock, sku,
                     short_description, description, image, file_path, youtube_url,
                     download_limit, download_url, featured, bestseller, allow_negotiation, status,
                     seo_title, seo_description, seo_keywords, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");

                $stmt->execute([
                    $name, $slug, $category_id, $price, $sale_price, $stock, $sku,
                    $short_description, $description, $image, $file_path, $youtube_url,
                    $download_limit, $download_url, $featured, $bestseller, $allow_negotiation, $status,
                    $seo_title, $seo_description, $seo_keywords
                ]);

                $product_id = $pdo->lastInsertId();

                // Gallery images
                if (!empty($_FILES['gallery']['name'][0])) {
                    foreach ($_FILES['gallery']['tmp_name'] as $key => $tmp_name) {
                        if (!empty($tmp_name)) {
                            $gallery_file = [
                                'name' => $_FILES['gallery']['name'][$key],
                                'type' => $_FILES['gallery']['type'][$key],
                                'tmp_name' => $tmp_name,
                                'error' => $_FILES['gallery']['error'][$key],
                                'size' => $_FILES['gallery']['size'][$key]
                            ];
                            $gallery_result = upload_image($gallery_file, 'products/gallery');
                            if ($gallery_result['success']) {
                                $stmt = $pdo->prepare("INSERT INTO product_images (product_id, image, sort_order) VALUES (?, ?, ?)");
                                $stmt->execute([$product_id, $gallery_result['path'], $key]);
                            }
                        }
                    }
                }

                log_admin_activity($pdo, $admin_id, 'create_product', "Created product: {$name}");

                set_flash_message('Product created successfully.', 'success');
                header('Location: ' . ADMIN_URL . '/products.php');
                exit;

            } catch (PDOException $e) {
                $errors[] = 'Database error: ' . $e->getMessage();
            }
        }
    }
}
?>

<div class="page-header">
    <div>
        <h1>Add Product</h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/index.php">Dashboard</a></li>
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/products.php">Products</a></li>
                <li class="breadcrumb-item active">Add Product</li>
            </ol>
        </nav>
    </div>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-danger alert-dismissible fade show">
    <i class="fas fa-exclamation-circle me-2"></i>
    <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
        <li><?php echo $error; ?></li>
        <?php endforeach; ?>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data">
    <?php echo csrf_field(); ?>
    
    <div class="row">
        <!-- Basic Info -->
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-header"><i class="fas fa-info-circle me-2"></i>Basic Information</div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Product Name *</label>
                        <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Slug</label>
                        <input type="text" name="slug" class="form-control" value="<?php echo htmlspecialchars($_POST['slug'] ?? ''); ?>">
                        <small class="text-muted">Leave empty to auto-generate from name</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Category *</label>
                        <select name="category_id" class="form-select" required>
                            <option value="">Select Category</option>
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo ($_POST['category_id'] ?? '') == $cat['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Price *</label>
                            <div class="input-group">
                                <span class="input-group-text"><?php echo get_setting('currency_symbol', '$'); ?></span>
                                <input type="number" name="price" class="form-control" step="0.01" min="0" value="<?php echo $_POST['price'] ?? ''; ?>" required>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label 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" name="sale_price" class="form-control" step="0.01" min="0" value="<?php echo $_POST['sale_price'] ?? ''; ?>">
                            </div>
                            <small class="text-muted">Leave 0 for no sale</small>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Stock</label>
                            <input type="number" name="stock" class="form-control" min="0" value="<?php echo $_POST['stock'] ?? '0'; ?>">
                            <small class="text-muted">0 for unlimited</small>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">SKU</label>
                        <input type="text" name="sku" class="form-control" value="<?php echo htmlspecialchars($_POST['sku'] ?? ''); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Short Description</label>
                        <textarea name="short_description" class="form-control" rows="2"><?php echo htmlspecialchars($_POST['short_description'] ?? ''); ?></textarea>
                        <small class="text-muted">Brief summary shown in product listings</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Full Description</label>
                        <textarea name="description" class="form-control" rows="6"><?php echo htmlspecialchars($_POST['description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
    <label class="form-label">YouTube Video URL</label>
    <input type="text" name="youtube_url" class="form-control" 
           value="<?php echo htmlspecialchars($product['youtube_url'] ?? ''); ?>"
           placeholder="https://youtube.com/watch?v=...">
</div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Download Limit</label>
                            <input type="number" name="download_limit" class="form-control" min="0" value="<?php echo $_POST['download_limit'] ?? '0'; ?>">
                            <small class="text-muted">0 for unlimited downloads</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">External Download URL</label>
                            <input type="url" name="download_url" class="form-control" value="<?php echo htmlspecialchars($_POST['download_url'] ?? ''); ?>"
                                   placeholder="https://example.com/download">
                            <small class="text-muted">Optional: External download link</small>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- SEO -->
            <div class="card mb-4">
                <div class="card-header"><i class="fas fa-search me-2"></i>SEO Settings</div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">SEO Title</label>
                        <input type="text" name="seo_title" class="form-control" value="<?php echo htmlspecialchars($_POST['seo_title'] ?? ''); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">SEO Description</label>
                        <textarea name="seo_description" class="form-control" rows="2"><?php echo htmlspecialchars($_POST['seo_description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">SEO Keywords</label>
                        <input type="text" name="seo_keywords" class="form-control" value="<?php echo htmlspecialchars($_POST['seo_keywords'] ?? ''); ?>">
                        <small class="text-muted">Comma-separated keywords</small>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Sidebar -->
        <div class="col-lg-4">
            <div class="card mb-4">
                <div class="card-header"><i class="fas fa-image me-2"></i>Product Image</div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Main Image</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                        <small class="text-muted">Recommended: 800x600px</small>
                    </div>
                </div>
            </div>
            
            <div class="card mb-4">
                <div class="card-header"><i class="fas fa-images me-2"></i>Gallery Images</div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Additional Images</label>
                        <input type="file" name="gallery[]" class="form-control" accept="image/*" multiple>
                        <small class="text-muted">Hold Ctrl/Cmd to select multiple</small>
                    </div>
                </div>
            </div>
            
            <div class="card mb-4">
                <div class="card-header"><i class="fas fa-file-archive me-2"></i>Digital File</div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Product File</label>
                        <input type="file" name="digital_file" class="form-control">
                        <small class="text-muted">Allowed: ZIP, PDF, JPG, PNG, DOC, MP4, MP3</small>
                    </div>
                </div>
            </div>
            
            <div class="card mb-4">
                <div class="card-header"><i class="fas fa-cog me-2"></i>Settings</div>
                <div class="card-body">
                    <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>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="bestseller" class="form-check-input" id="bestseller" <?php echo isset($_POST['bestseller']) ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="bestseller">Mark as Bestseller</label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="allow_negotiation" class="form-check-input" id="allow_negotiation" <?php echo isset($_POST['allow_negotiation']) ? '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 class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="active" <?php echo ($_POST['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo ($_POST['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                            <option value="draft" <?php echo ($_POST['status'] ?? '') === 'draft' ? 'selected' : ''; ?>>Draft</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="d-grid">
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="fas fa-save me-2"></i> Create Product
                </button>
                <a href="<?php echo ADMIN_URL; ?>/products.php" class="btn btn-outline-secondary mt-2">
                    <i class="fas fa-times me-2"></i> Cancel
                </a>
            </div>
        </div>
    </div>
</form>

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