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

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

requireAdmin();

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

// Get categories for dropdown
$categories = fetchAll("SELECT * FROM categories ORDER BY name");

// Function to generate dummy bids and comments
function generateDummyActivity($product_id) {
    $dummy_users = fetchAll("SELECT id FROM users WHERE is_dummy = 1 LIMIT 30");
    
    $product = fetchOne("SELECT starting_price FROM products WHERE id = $product_id");
    $current_price = $product['starting_price'];
    
    $num_bids = rand(15, 25);
    for ($i = 0; $i < $num_bids; $i++) {
        $increment = rand(50, 500);
        $current_price += $increment;
        $user = $dummy_users[array_rand($dummy_users)];
        
        insert('bids', [
            'product_id' => $product_id,
            'user_id' => $user['id'],
            'amount' => $current_price,
            'is_system_bid' => 1
        ]);
    }
    
    $highest = fetchOne("SELECT MAX(amount) as max FROM bids WHERE product_id = $product_id");
    if ($highest['max']) {
        update('products', ['current_highest_bid' => $highest['max']], "id = $product_id");
    }
    
    $comments_array = [
        "Beautiful car! I'm definitely interested.",
        "Has anyone seen this in person?",
        "What's the maintenance history like?",
        "This is a steal at this price!",
        "I've been looking for one of these.",
        "Can you share more photos?",
        "Is the price negotiable?",
        "Amazing vehicle! Good luck everyone.",
        "I placed my bid! Fingers crossed.",
        "This won't last long at this price.",
        "How many miles does it have?",
        "Original owner? Service records?",
        "Dream car right here!",
        "Someone's getting a great deal.",
        "I'll be watching this one closely."
    ];
    
    $num_comments = rand(15, 25);
    for ($i = 0; $i < $num_comments; $i++) {
        $user = $dummy_users[array_rand($dummy_users)];
        $comment = $comments_array[array_rand($comments_array)];
        
        insert('comments', [
            'product_id' => $product_id,
            'user_id' => $user['id'],
            'comment_text' => $comment,
            'is_system_comment' => 1
        ]);
    }
}

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']);
    
    if (empty($name) || empty($short_desc) || empty($long_desc) || $starting_price <= 0) {
        $error = 'Please fill in all required fields.';
    } else {
        $product_id = insert('products', [
            'name' => $name,
            'short_desc' => $short_desc,
            'long_desc' => $long_desc,
            'starting_price' => $starting_price,
            'current_highest_bid' => $starting_price,
            'end_time' => $end_time,
            'category_id' => $category_id,
            'tags' => $tags,
            'is_reserved' => 0
        ]);
        
        if ($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)) {
                    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_' . $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
                            ]);
                        }
                    }
                }
            }
            
            generateDummyActivity($product_id);
            
            $success = 'Product added successfully!';
        } else {
            $error = 'Failed to add product.';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Product - Admin Panel</title>
    <!-- CKEditor 5 Classic CDN -->
    <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;
        }
        /* 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;
        }
        .ck.ck-toolbar .ck.ck-toolbar__separator {
            background: #444 !important;
        }
        /* Source code view */
        .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">Add New Product</h1>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?> <a href="products.php" style="color: #155724;">View Products</a></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <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" 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 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" class="form-control" required>
            </div>
            
            <div class="form-group">
                <label>End Date & Time *</label>
                <input type="datetime-local" name="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 placeholder="Brief description of the product..."></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;" placeholder="Detailed description with formatting..."></textarea>
            <textarea id="sourceEditor" class="source-editor" placeholder="HTML source code..."></textarea>
        </div>
        
        <div class="form-group">
            <label>Tags (comma separated)</label>
            <input type="text" name="tags" placeholder="luxury, sports, electric" class="form-control">
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label>Featured Image</label>
                <input type="file" name="featured_image" accept="image/*" class="form-control">
            </div>
            
            <div class="form-group">
                <label>Gallery Images (multiple)</label>
                <input type="file" name="gallery_images[]" accept="image/*" multiple class="form-control">
            </div>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">Add Product</button>
            <a href="products.php" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
</div>

<script>
    let editorInstance = null;
    let isVisualMode = true;
    
    // Initialize CKEditor with full table support
    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',
                    'Lucida Sans Unicode, Lucida Grande, sans-serif',
                    'Tahoma, Geneva, sans-serif',
                    'Times New Roman, Times, serif',
                    'Trebuchet MS, Helvetica, sans-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(90, 75%, 60%)', label: 'Light green' },
                    { color: 'hsl(120, 75%, 60%)', label: 'Green' },
                    { color: 'hsl(150, 75%, 60%)', label: 'Aquamarine' },
                    { color: 'hsl(180, 75%, 60%)', label: 'Turquoise' },
                    { color: 'hsl(210, 75%, 60%)', label: 'Light blue' },
                    { color: 'hsl(240, 75%, 60%)', label: 'Blue' },
                    { color: 'hsl(270, 75%, 60%)', label: 'Purple' }
                ]
            },
            // Table configuration with full toolbar
            table: {
                contentToolbar: [ 
                    'tableColumn', 'tableRow', 'mergeTableCells',
                    'tableProperties', 'tableCellProperties'
                ]
            },
            alignment: {
                options: [ 'left', 'center', 'right', 'justify' ]
            },
            // Allow all HTML tags to preserve formatting on paste
            htmlSupport: {
                allow: [
                    {
                        name: /.*/,
                        attributes: true,
                        classes: true,
                        styles: true
                    }
                ]
            },
            // Disable paste filtering to preserve all formatting
            pasteFilter: null,
            // Allow unsafe HTML for complete paste support
            allowUnsafeHtml: true,
            // Paste settings
            paste: {
                allowAll: true
            }
        })
        .then(editor => {
            editorInstance = editor;
            console.log('CKEditor initialized with full table support');
            
            // Sync with source editor when content changes
            editor.model.document.on('change:data', () => {
                if (isVisualMode) {
                    const sourceEditor = document.getElementById('sourceEditor');
                    sourceEditor.value = editor.getData();
                }
            });
        })
        .catch(error => {
            console.error('CKEditor error:', error);
        });
    
    // Visual Mode Button
    document.getElementById('visualModeBtn').addEventListener('click', () => {
        if (!editorInstance) return;
        
        const sourceEditor = document.getElementById('sourceEditor');
        const wysiwygEditor = document.getElementById('editor');
        
        if (!isVisualMode) {
            // Switching from code to visual mode
            const htmlContent = sourceEditor.value;
            editorInstance.setData(htmlContent);
            wysiwygEditor.style.display = 'block';
            sourceEditor.style.display = 'none';
            isVisualMode = true;
            
            document.getElementById('visualModeBtn').classList.add('active');
            document.getElementById('codeModeBtn').classList.remove('active');
        }
    });
    
    // Code Mode Button
    document.getElementById('codeModeBtn').addEventListener('click', () => {
        if (!editorInstance) return;
        
        const sourceEditor = document.getElementById('sourceEditor');
        const wysiwygEditor = document.getElementById('editor');
        
        if (isVisualMode) {
            // Switching from visual to code mode
            const currentContent = editorInstance.getData();
            sourceEditor.value = currentContent;
            wysiwygEditor.style.display = 'none';
            sourceEditor.style.display = 'block';
            isVisualMode = false;
            
            document.getElementById('codeModeBtn').classList.add('active');
            document.getElementById('visualModeBtn').classList.remove('active');
        }
    });
    
    // Sync source editor content to main textarea before form submission
    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'; ?>