<?php
// edit_product.php - Edit Product with Full WYSIWYG Editor & Table Support
// File location: /bidwheels.net/admin/edit_product.php

require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once 'includes/admin_header.php';

requireAdmin();

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

if ($product_id <= 0) {
    redirect('/admin/products.php');
}

$product = fetchOne("SELECT * FROM products WHERE id = $product_id");
if (!$product) {
    redirect('/admin/products.php');
}

$categories = fetchAll("SELECT * FROM categories ORDER BY name");
$images = fetchAll("SELECT * FROM product_images WHERE product_id = $product_id");

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = sanitize($_POST['name']);
    $short_desc = sanitize($_POST['short_desc']);
    $long_desc = $_POST['long_desc'];
    $starting_price = floatval($_POST['starting_price']);
    $category_id = intval($_POST['category_id']);
    $tags = sanitize($_POST['tags']);
    $end_time = sanitize($_POST['end_time']);
    $is_reserved = isset($_POST['is_reserved']) ? 1 : 0;
    
    update('products', [
        'name' => $name,
        'short_desc' => $short_desc,
        'long_desc' => $long_desc,
        'starting_price' => $starting_price,
        'category_id' => $category_id,
        'tags' => $tags,
        'end_time' => $end_time,
        'is_reserved' => $is_reserved
    ], "id = $product_id");
    
    $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/bidwheels/uploads/products/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] == 0) {
        $ext = pathinfo($_FILES['featured_image']['name'], PATHINFO_EXTENSION);
        $filename = 'product_' . $product_id . '_featured.' . $ext;
        $filepath = $upload_dir . $filename;
        
        if (move_uploaded_file($_FILES['featured_image']['tmp_name'], $filepath)) {
            $old_featured = fetchOne("SELECT id FROM product_images WHERE product_id = $product_id AND is_featured = 1");
            if ($old_featured) {
                delete('product_images', "id = {$old_featured['id']}");
            }
            
            insert('product_images', [
                'product_id' => $product_id,
                'image_path' => $filename,
                'is_featured' => 1
            ]);
        }
    }
    
    if (isset($_FILES['gallery_images'])) {
        foreach ($_FILES['gallery_images']['tmp_name'] as $key => $tmp_name) {
            if ($_FILES['gallery_images']['error'][$key] == 0) {
                $ext = pathinfo($_FILES['gallery_images']['name'][$key], PATHINFO_EXTENSION);
                $filename = 'product_' . $product_id . '_gallery_' . time() . '_' . $key . '.' . $ext;
                $filepath = $upload_dir . $filename;
                
                if (move_uploaded_file($tmp_name, $filepath)) {
                    insert('product_images', [
                        'product_id' => $product_id,
                        'image_path' => $filename,
                        'is_featured' => 0
                    ]);
                }
            }
        }
    }
    
    $success = 'Product updated successfully!';
    $product = fetchOne("SELECT * FROM products WHERE id = $product_id");
}

if (isset($_GET['delete_image'])) {
    $image_id = (int)$_GET['delete_image'];
    $image = fetchOne("SELECT image_path FROM product_images WHERE id = $image_id");
    if ($image) {
        $filepath = $_SERVER['DOCUMENT_ROOT'] . '/bidwheels/uploads/products/' . $image['image_path'];
        if (file_exists($filepath)) {
            unlink($filepath);
        }
        delete('product_images', "id = $image_id");
        setSuccess('Image deleted.');
    }
    redirect("/admin/edit_product.php?id=$product_id");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Product - Admin Panel</title>
    <script src="https://cdn.ckeditor.com/ckeditor5/41.4.2/classic/ckeditor.js"></script>
    <style>
        .admin-page {
            max-width: 1200px;
            margin: 0 auto;
        }
        .page-title {
            margin-bottom: 25px;
            font-size: 24px;
            color: #fff;
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #ccc;
        }
        .form-control {
            width: 100%;
            padding: 12px;
            border: 1px solid #333;
            border-radius: 8px;
            background: #1a1a1a;
            color: white;
            font-family: inherit;
        }
        .form-control:focus {
            outline: none;
            border-color: #FF8C3E;
        }
        textarea.form-control {
            resize: vertical;
            min-height: 100px;
        }
        .form-actions {
            margin-top: 30px;
            display: flex;
            gap: 15px;
        }
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-weight: 600;
            font-family: inherit;
        }
        .btn-primary {
            background: #FF8C3E;
            color: #0a0a0a;
        }
        .btn-primary:hover {
            background: #e67a22;
        }
        .btn-secondary {
            background: #2a2a2a;
            color: white;
        }
        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .alert-success {
            background: #d4edda;
            color: #155724;
        }
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
        }
        .current-images {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 10px;
        }
        .image-item {
            position: relative;
            width: 100px;
            text-align: center;
        }
        .image-item img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 8px;
        }
        .image-item span {
            display: block;
            font-size: 11px;
            margin-top: 5px;
            color: #aaa;
        }
        .btn-icon {
            padding: 4px 8px;
            border-radius: 4px;
            color: white;
            text-decoration: none;
            font-size: 12px;
        }
        .btn-danger {
            background: #dc3545;
        }
        /* Editor Toolbar */
        .editor-toolbar {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        .editor-mode-btn {
            padding: 8px 16px;
            background: #2a2a2a;
            border: 1px solid #444;
            border-radius: 6px;
            color: white;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s;
        }
        .editor-mode-btn.active {
            background: #FF8C3E;
            color: #0a0a0a;
            border-color: #FF8C3E;
        }
        .editor-mode-btn:hover {
            background: #3a3a3a;
        }
        .ck-editor__editable {
            min-height: 450px;
            background: #1a1a1a !important;
            color: #e0e0e0 !important;
        }
        .ck.ck-editor__main>.ck-editor__editable {
            background: #1a1a1a;
            color: #e0e0e0;
        }
        .ck.ck-toolbar {
            background: #2a2a2a !important;
            border-color: #444 !important;
        }
        .ck.ck-button, .ck.ck-button.ck-on {
            color: white !important;
        }
        .ck.ck-button:hover {
            background: #3a3a3a !important;
        }
        .source-editor {
            width: 100%;
            min-height: 450px;
            padding: 15px;
            background: #0d0d0d;
            color: #e0e0e0;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            border: 1px solid #333;
            border-radius: 8px;
            display: none;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        /* Table styling for editor */
        .ck-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 16px 0;
        }
        .ck-content table td,
        .ck-content table th {
            border: 1px solid #555;
            padding: 8px 12px;
        }
        .ck-content table th {
            background: #2a2a2a;
        }
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
<div class="admin-page">
    <h1 class="page-title">Edit Product</h1>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <?php echo getMessage(); ?>
    
    <form method="POST" action="" enctype="multipart/form-data">
        <div class="form-row">
            <div class="form-group">
                <label>Product Name *</label>
                <input type="text" name="name" value="<?php echo htmlspecialchars($product['name']); ?>" class="form-control" required>
            </div>
            
            <div class="form-group">
                <label>Category *</label>
                <select name="category_id" class="form-control" required>
                    <option value="">Select Category</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" <?php echo $cat['id'] == $product['category_id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label>Starting Price (USD) *</label>
                <input type="number" name="starting_price" step="1" value="<?php echo $product['starting_price']; ?>" class="form-control" required>
            </div>
            
            <div class="form-group">
                <label>End Date & Time *</label>
                <input type="datetime-local" name="end_time" value="<?php echo date('Y-m-d\TH:i', strtotime($product['end_time'])); ?>" class="form-control" required>
            </div>
        </div>
        
        <div class="form-group">
            <label>Short Description *</label>
            <textarea name="short_desc" rows="3" class="form-control" required><?php echo htmlspecialchars($product['short_desc']); ?></textarea>
        </div>
        
        <div class="form-group">
            <label>Long Description *</label>
            <div class="editor-toolbar">
                <button type="button" class="editor-mode-btn active" id="visualModeBtn">Visual Mode</button>
                <button type="button" class="editor-mode-btn" id="codeModeBtn">Code Mode</button>
            </div>
            <textarea name="long_desc" id="editor" rows="10" class="form-control" style="display: block;"><?php echo htmlspecialchars($product['long_desc']); ?></textarea>
            <textarea id="sourceEditor" class="source-editor"><?php echo htmlspecialchars($product['long_desc']); ?></textarea>
        </div>
        
        <div class="form-group">
            <label>Tags (comma separated)</label>
            <input type="text" name="tags" value="<?php echo htmlspecialchars($product['tags']); ?>" placeholder="luxury, sports, electric" class="form-control">
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" name="is_reserved" value="1" <?php echo $product['is_reserved'] ? 'checked' : ''; ?>>
                Mark as Reserved (stops bidding)
            </label>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label>New Featured Image</label>
                <input type="file" name="featured_image" accept="image/*" class="form-control">
                <small>Leave empty to keep current image</small>
            </div>
            
            <div class="form-group">
                <label>Add Gallery Images (multiple)</label>
                <input type="file" name="gallery_images[]" accept="image/*" multiple class="form-control">
            </div>
        </div>
        
        <?php if (count($images) > 0): ?>
            <div class="form-group">
                <label>Current Images</label>
                <div class="current-images">
                    <?php foreach ($images as $img): ?>
                        <div class="image-item">
                            <img src="<?php echo SITE_URL; ?>/uploads/products/<?php echo $img['image_path']; ?>">
                            <span><?php echo $img['is_featured'] ? 'Featured' : 'Gallery'; ?></span>
                            <a href="?id=<?php echo $product_id; ?>&delete_image=<?php echo $img['id']; ?>" class="btn-icon btn-danger" onclick="return confirm('Delete this image?')">Delete</a>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">Save Changes</button>
            <a href="products.php" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
</div>

<script>
    let editorInstance = null;
    let isVisualMode = true;
    
    ClassicEditor
        .create(document.querySelector('#editor'), {
            toolbar: {
                items: [
                    'undo', 'redo',
                    '|', 'heading',
                    '|', 'bold', 'italic', 'underline', 'strikethrough',
                    '|', 'bulletedList', 'numberedList',
                    '|', 'alignment',
                    '|', 'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor',
                    '|', 'link', 'insertTable',
                    '|', 'blockQuote', 'codeBlock',
                    '|', 'removeFormat'
                ],
                shouldNotGroupWhenFull: true
            },
            heading: {
                options: [
                    { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
                    { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
                    { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' },
                    { model: 'heading3', view: 'h3', title: 'Heading 3', class: 'ck-heading_heading3' },
                    { model: 'heading4', view: 'h4', title: 'Heading 4', class: 'ck-heading_heading4' }
                ]
            },
            fontSize: {
                options: ['tiny', 'small', 'default', 'big', 'huge']
            },
            fontFamily: {
                options: [
                    'default',
                    'Arial, Helvetica, sans-serif',
                    'Courier New, Courier, monospace',
                    'Georgia, serif',
                    'Times New Roman, Times, serif',
                    'Verdana, Geneva, sans-serif'
                ]
            },
            fontColor: {
                colors: [
                    { color: 'hsl(0, 0%, 0%)', label: 'Black' },
                    { color: 'hsl(0, 0%, 30%)', label: 'Dim grey' },
                    { color: 'hsl(0, 0%, 60%)', label: 'Grey' },
                    { color: 'hsl(0, 0%, 90%)', label: 'Light grey' },
                    { color: 'hsl(0, 0%, 100%)', label: 'White' },
                    { color: 'hsl(0, 75%, 60%)', label: 'Red' },
                    { color: 'hsl(30, 75%, 60%)', label: 'Orange' },
                    { color: 'hsl(60, 75%, 60%)', label: 'Yellow' },
                    { color: 'hsl(120, 75%, 60%)', label: 'Green' },
                    { color: 'hsl(240, 75%, 60%)', label: 'Blue' },
                    { color: 'hsl(270, 75%, 60%)', label: 'Purple' }
                ]
            },
            table: {
                contentToolbar: [ 
                    'tableColumn', 'tableRow', 'mergeTableCells',
                    'tableProperties', 'tableCellProperties'
                ]
            },
            alignment: {
                options: [ 'left', 'center', 'right', 'justify' ]
            },
            htmlSupport: {
                allow: [
                    {
                        name: /.*/,
                        attributes: true,
                        classes: true,
                        styles: true
                    }
                ]
            },
            pasteFilter: null,
            allowUnsafeHtml: true,
            paste: {
                allowAll: true
            }
        })
        .then(editor => {
            editorInstance = editor;
            console.log('CKEditor initialized with full table support');
            
            editor.model.document.on('change:data', () => {
                if (isVisualMode) {
                    document.getElementById('sourceEditor').value = editor.getData();
                }
            });
        })
        .catch(error => {
            console.error('CKEditor error:', error);
        });
    
    document.getElementById('visualModeBtn').addEventListener('click', () => {
        if (!editorInstance) return;
        
        if (!isVisualMode) {
            editorInstance.setData(document.getElementById('sourceEditor').value);
            document.getElementById('editor').style.display = 'block';
            document.getElementById('sourceEditor').style.display = 'none';
            isVisualMode = true;
            
            document.getElementById('visualModeBtn').classList.add('active');
            document.getElementById('codeModeBtn').classList.remove('active');
        }
    });
    
    document.getElementById('codeModeBtn').addEventListener('click', () => {
        if (!editorInstance) return;
        
        if (isVisualMode) {
            document.getElementById('sourceEditor').value = editorInstance.getData();
            document.getElementById('editor').style.display = 'none';
            document.getElementById('sourceEditor').style.display = 'block';
            isVisualMode = false;
            
            document.getElementById('codeModeBtn').classList.add('active');
            document.getElementById('visualModeBtn').classList.remove('active');
        }
    });
    
    document.querySelector('form').addEventListener('submit', () => {
        if (editorInstance) {
            if (isVisualMode) {
                document.getElementById('editor').value = editorInstance.getData();
            } else {
                document.getElementById('editor').value = document.getElementById('sourceEditor').value;
            }
        }
    });
</script>

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