<?php
// Check for POST size error before starting session
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
    $max_size = ini_get('post_max_size');
    die("Error: Total upload size exceeds the server limit of $max_size. Please upload smaller files or reduce the number of images.");
}
session_start();
include "../config/db.php";

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

$categories = mysqli_query($conn, "SELECT * FROM categories");
$success = '';
$error = '';

if (isset($_POST['add_product'])) {
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $slug = mysqli_real_escape_string($conn, $_POST['slug']);
    if (empty($slug)) {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
    }
    $price = mysqli_real_escape_string($conn, $_POST['price']);
    $original_price = mysqli_real_escape_string($conn, $_POST['original_price']);
    $rental_price = mysqli_real_escape_string($conn, $_POST['rental_price']);
    $discount_percent = mysqli_real_escape_string($conn, $_POST['discount_percent']);
    $category_id = mysqli_real_escape_string($conn, $_POST['category_id']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $stock = mysqli_real_escape_string($conn, $_POST['stock']);
    $security_deposit = mysqli_real_escape_string($conn, $_POST['security_deposit']);
    $brand = mysqli_real_escape_string($conn, $_POST['brand']);
    $size = mysqli_real_escape_string($conn, $_POST['size']);
    $color = mysqli_real_escape_string($conn, $_POST['color']);
    $material = mysqli_real_escape_string($conn, $_POST['material']);
    $rental_days = mysqli_real_escape_string($conn, $_POST['rental_days']);
    $market_price = mysqli_real_escape_string($conn, $_POST['market_price'] ?? '0');
    $featured = isset($_POST['featured']) ? 1 : 0;

    // Calculate final price if discount is applied
    if (!empty($rental_price) && !empty($discount_percent)) {
        $discount_amount = ($rental_price * $discount_percent) / 100;
        $price = $rental_price - $discount_amount;
    }

    $image_names = [];
    $allowed = ['jpg','jpeg','png','webp','gif'];
    
    // 1. Handle Main Image
    if (isset($_FILES['main_image']) && $_FILES['main_image']['error'] == 0) {
        $file = $_FILES['main_image'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $allowed)) {
            $new_name = 'main_' . time() . '_' . uniqid() . '.' . $ext;
            if (move_uploaded_file($file['tmp_name'], "../assets/images/products/" . $new_name)) {
                $image_names[] = $new_name;
            }
        }
    }

    // 2. Handle Gallery Images
    if (isset($_FILES['gallery_images']) && !empty($_FILES['gallery_images']['name'][0])) {
        $files = $_FILES['gallery_images'];
        foreach ($files['name'] as $key => $fname) {
            if ($files['error'][$key] == 0) {
                $ext = strtolower(pathinfo($fname, PATHINFO_EXTENSION));
                if (in_array($ext, $allowed)) {
                    $new_name = 'gal_' . time() . '_' . uniqid() . '.' . $ext;
                    if (move_uploaded_file($files['tmp_name'][$key], "../assets/images/products/" . $new_name)) {
                        $image_names[] = $new_name;
                    }
                }
            }
        }
    }

    // 3. Handle Video File (Optional)
    $video_path = '';
    if (isset($_FILES['product_video']) && $_FILES['product_video']['error'] == 0) {
        $video_file = $_FILES['product_video'];
        $video_ext = strtolower(pathinfo($video_file['name'], PATHINFO_EXTENSION));
        $allowed_videos = ['mp4', 'webm', 'ogg'];
        
        if (in_array($video_ext, $allowed_videos)) {
            // Check file size (e.g. max 50MB) 
            if ($video_file['size'] <= 50000000) {
                if (!file_exists("../assets/videos/products/")) {
                    mkdir("../assets/videos/products/", 0777, true);
                }
                $new_video_name = 'vid_' . time() . '_' . uniqid() . '.' . $video_ext;
                if (move_uploaded_file($video_file['tmp_name'], "../assets/videos/products/" . $new_video_name)) {
                    $video_path = $new_video_name;
                }
            } else {
                $error = "Video size exceeds 50MB limit.";
            }
        } else {
            $error = "Invalid video format! Allowed: MP4, WebM, OGG.";
        }
    }

    if (empty($image_names)) {
        $error = "Main image is required!";
    } elseif (empty($error)) {
        $images_json = mysqli_real_escape_string($conn, json_encode($image_names));
        
        $check_columns = mysqli_query($conn, "SHOW COLUMNS FROM products");
        $columns = [];
        while($col = mysqli_fetch_assoc($check_columns)) {
            $columns[] = $col['Field'];
        }
        
        $missing_columns = [
            'slug' => "VARCHAR(255) UNIQUE",
            'rental_price' => "DECIMAL(10,2) DEFAULT 0",
            'discount_percent' => "DECIMAL(5,2) DEFAULT 0",
            'security_deposit' => "DECIMAL(10,2) DEFAULT 0",
            'brand' => "VARCHAR(100)",
            'size' => "VARCHAR(255)", 
            'color' => "VARCHAR(50)",
            'material' => "VARCHAR(100)",
            'rental_days' => "INT DEFAULT 3",
            'featured' => "TINYINT(1) DEFAULT 0",
            'video_path' => "VARCHAR(255) NULL",
            'market_price' => "DECIMAL(10,2) DEFAULT 0"
        ];
        
        foreach($missing_columns as $col_name => $col_type) {
            if(!in_array($col_name, $columns)) {
                mysqli_query($conn, "ALTER TABLE products ADD COLUMN $col_name $col_type");
            }
        }

        $query = "INSERT INTO products (name, slug, original_price, market_price, price, rental_price, discount_percent, category_id, images, description, stock, security_deposit, brand, size, color, material, rental_days, featured, video_path) 
                  VALUES ('$name', '$slug', '$original_price', '$market_price', '$price', '$rental_price', '$discount_percent', '$category_id', '$images_json', '$description', '$stock', '$security_deposit', '$brand', '$size', '$color', '$material', '$rental_days', '$featured', '$video_path')";

        if (mysqli_query($conn, $query)) {
            $success = "Product added successfully!";
            $_POST = array();
        } else {
            $error = "Error: " . mysqli_error($conn);
        }
    }
}
?>
<!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>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .main-content {
            margin-left: 220px;
            padding: 30px;
            background: #f8f9fa;
            min-height: 100vh;
        }
        .add-product-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
        }
        .form-header {
            border-bottom: 2px solid #eee;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .image-preview, .video-preview {
            width: 200px;
            height: 200px;
            border: 2px dashed #ddd;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            margin-bottom: 15px;
        }
        .image-preview img, .video-preview video {
            max-width: 100%;
            max-height: 100%;
            display: none;
        }
        .featured-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background: var(--primary-orange);
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 0.8rem;
        }
        .price-display {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 10px;
        }
        .rental-price {
            text-decoration: line-through;
            color: #999;
        }
        .discount-badge {
            background: #dc3545;
            color: white;
            padding: 3px 10px;
            border-radius: 5px;
            font-size: 0.9rem;
            margin-left: 10px;
        }
        .security-badge {
            background: #28a745;
            color: white;
            padding: 3px 10px;
            border-radius: 5px;
            font-size: 0.9rem;
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <?php include "includes/sidebar.php"; ?>

    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 style="color: var(--dark-blue);">
                <i class="fas fa-plus-circle me-2"></i>Add New Product
            </h2>
            <a href="products.php" class="btn btn-outline-primary">
                <i class="fas fa-arrow-left me-2"></i>Back to Products
            </a>
        </div>

        <?php if($success): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <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; ?>

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

        <div class="add-product-container">
            <form method="POST" enctype="multipart/form-data" id="productForm" onsubmit="return validateFileSize()">
                <div class="row">
                    <!-- Product Media -->
                    <div class="col-md-4 mb-4">
                        <div class="form-header">
                            <h5><i class="fas fa-images me-2"></i>Product Media</h5>
                        </div>
                        
                        <div class="mb-4">
                            <label class="form-label fw-bold text-primary">Main Image (Thumbnail) *</label>
                            <div class="image-preview mb-2" id="mainImagePreview">
                                <i class="fas fa-image fa-3x text-muted"></i>
                                <img src="" alt="Preview">
                            </div>
                            <input type="file" name="main_image" class="form-control" accept="image/*" required onchange="previewMainImage(this)">
                            <small class="text-muted">This image will be shown in lists.</small>
                        </div>

                        <div class="mb-4">
                            <label class="form-label fw-bold">Gallery Images</label>
                            <div id="galleryPreviewContainer" class="d-flex flex-wrap gap-2 mb-2">
                                <div class="image-preview" style="width: 60px; height: 60px;">
                                    <i class="fas fa-images text-muted"></i>
                                </div>
                            </div>
                            <input type="file" name="gallery_images[]" class="form-control" accept="image/*" multiple onchange="previewGalleryImages(this)">
                            <small class="text-muted">Will be shown in slider. Select multiple.</small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold text-info">Product Video (Optional)</label>
                            <div class="video-preview mb-2" id="videoPreviewContainer">
                                <i class="fas fa-video fa-3x text-muted" id="videoPlaceholderIcon"></i>
                                <video controls id="videoPreviewElement" style="display: none;"></video>
                            </div>
                            <input type="file" name="product_video" class="form-control" accept="video/mp4,video/webm,video/ogg" onchange="previewVideo(this)">
                            <small class="text-muted">Upload Max: 50MB (MP4, WebM)</small>
                        </div>
                    </div>

                    <!-- Product Details -->
                    <div class="col-md-8">
                        <div class="form-header">
                            <h5><i class="fas fa-info-circle me-2"></i>Product Details</h5>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Product Name *</label>
                                <input type="text" name="name" class="form-control" required 
                                       value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>"
                                       onkeyup="generateSlug(this.value)">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">URL Slug</label>
                                <input type="text" name="slug" id="slug" class="form-control" 
                                       value="<?php echo isset($_POST['slug']) ? htmlspecialchars($_POST['slug']) : ''; ?>">
                                <small class="text-muted">Leave blank to auto-generate</small>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Category *</label>
                                <select name="category_id" class="form-select" required>
                                    <option value="">Select Category</option>
                                    <?php 
                                    mysqli_data_seek($categories, 0);
                                    while($cat = mysqli_fetch_assoc($categories)): 
                                    ?>
                                        <option value="<?php echo $cat['id']; ?>" 
                                            <?php echo (isset($_POST['category_id']) && $_POST['category_id'] == $cat['id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($cat['category_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Brand</label>
                                <input type="text" name="brand" class="form-control" 
                                       value="<?php echo isset($_POST['brand']) ? htmlspecialchars($_POST['brand']) : ''; ?>">
                            </div>
                        </div>

                        <div class="form-header mt-4">
                            <h5><i class="fas fa-tags me-2"></i>Pricing & Inventory</h5>
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold">Original Price (₹) *</label>
                                <input type="number" name="original_price" id="original_price" class="form-control" required min="0" step="0.01"
                                       value="<?php echo isset($_POST['original_price']) ? htmlspecialchars($_POST['original_price']) : ''; ?>"
                                       onkeyup="calculateDiscount()">
                                <small class="text-muted">Previous rental price (if any)</small>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold">Market Price (MRP) *</label>
                                <input type="number" name="market_price" id="market_price" class="form-control" required min="0" step="0.01"
                                       value="<?php echo isset($_POST['market_price']) ? htmlspecialchars($_POST['market_price']) : ''; ?>">
                                <small class="text-muted">Retail market value</small>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold">Base Rental Price (₹) *</label>
                                <input type="number" name="rental_price" id="rental_price" class="form-control" required min="0" step="0.01"
                                       value="<?php echo isset($_POST['rental_price']) ? htmlspecialchars($_POST['rental_price']) : ''; ?>"
                                       onkeyup="calculateDiscount()">
                                <small class="text-muted">Price before discount</small>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold">Discount (%)</label>
                                <input type="number" name="discount_percent" id="discount_percent" class="form-control" min="0" max="100"
                                       value="<?php echo isset($_POST['discount_percent']) ? htmlspecialchars($_POST['discount_percent']) : ''; ?>"
                                       onkeyup="calculateDiscount()">
                            </div>
                        </div>

                        <!-- Price Preview Display -->
                        <div class="price-display mb-4">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h6 class="mb-1 text-primary">Final Rental Price Calculation</h6>
                                    <small class="text-muted">This is what customers will pay.</small>
                                </div>
                                <div class="col-md-4 text-end">
                                    <div id="pricePreview">
                                        <span class="fs-4 fw-bold text-success">₹0.00</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold">Security Deposit (₹) *</label>
                                <input type="number" name="security_deposit" class="form-control" required min="0" step="0.01"
                                       value="<?php echo isset($_POST['security_deposit']) ? htmlspecialchars($_POST['security_deposit']) : ''; ?>">
                                <small class="text-muted">Refundable amount</small>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold">Stock Quantity *</label>
                                <input type="number" name="stock" class="form-control" required min="0"
                                       value="<?php echo isset($_POST['stock']) ? htmlspecialchars($_POST['stock']) : '1'; ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold">Rental Days *</label>
                                <input type="number" name="rental_days" class="form-control" required min="1"
                                       value="<?php echo isset($_POST['rental_days']) ? htmlspecialchars($_POST['rental_days']) : '3'; ?>">
                                <small class="text-muted">Default rental duration</small>
                            </div>
                        </div>

                        <div class="form-header mt-4">
                            <h5><i class="fas fa-list-ul me-2"></i>Product Specifications</h5>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Sizes Available</label>
                                <input type="text" name="size" class="form-control" placeholder="e.g., S, M, L, XL"
                                       value="<?php echo isset($_POST['size']) ? htmlspecialchars($_POST['size']) : ''; ?>">
                                <small class="text-muted">Comma separated</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Color</label>
                                <input type="text" name="color" class="form-control"
                                       value="<?php echo isset($_POST['color']) ? htmlspecialchars($_POST['color']) : ''; ?>">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label fw-bold">Material</label>
                                <input type="text" name="material" class="form-control"
                                       value="<?php echo isset($_POST['material']) ? htmlspecialchars($_POST['material']) : ''; ?>">
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label fw-bold">Product Description *</label>
                            <textarea name="description" class="form-control" rows="5" required><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
                        </div>

                        <div class="mb-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="featured" id="featured" value="1" 
                                    <?php echo isset($_POST['featured']) ? 'checked' : ''; ?>>
                                <label class="form-check-label fw-bold" for="featured">
                                    Mark as Featured Product
                                    <br><small class="text-muted">Featured products appear on the homepage.</small>
                                </label>
                            </div>
                        </div>

                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="reset" class="btn btn-light me-md-2" id="resetBtn">Reset</button>
                            <button type="submit" name="add_product" class="btn btn-primary px-4">
                                <i class="fas fa-save me-2"></i>Save Product
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Hidden input to store price to pass to DB directly -->
    <input type="hidden" name="price" id="final_price_input" value="0" form="productForm">

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Generate slug from name
        function generateSlug(text) {
            const slug = text.toLowerCase()
                .replace(/[^\w\s-]/g, '')
                .replace(/[\s_-]+/g, '-')
                .replace(/^-+|-+$/g, '');
            document.getElementById('slug').value = slug;
        }

        // Calculate and preview discount
        function calculateDiscount() {
            const rentalPrice = parseFloat(document.getElementById('rental_price').value) || 0;
            const discountPercent = parseFloat(document.getElementById('discount_percent').value) || 0;
            
            let finalPrice = rentalPrice;
            let displayHTML = '';
            
            if (discountPercent > 0) {
                const discountAmount = (rentalPrice * discountPercent) / 100;
                finalPrice = rentalPrice - discountAmount;
                
                displayHTML = `
                    <span class="rental-price fs-5 me-2">₹${rentalPrice.toFixed(2)}</span>
                    <span class="fs-3 fw-bold text-success">₹${finalPrice.toFixed(2)}</span>
                    <span class="discount-badge">-${discountPercent}%</span>
                `;
            } else {
                displayHTML = `<span class="fs-3 fw-bold text-success">₹${finalPrice.toFixed(2)}</span>`;
            }
            
            document.getElementById('pricePreview').innerHTML = displayHTML;
            document.getElementById('final_price_input').value = finalPrice.toFixed(2);
        }

        // Preview single main image
        function previewMainImage(input) {
            const preview = document.getElementById('mainImagePreview');
            const icon = preview.querySelector('i');
            let img = preview.querySelector('img');
            
            if (!img) {
                img = document.createElement('img');
                preview.appendChild(img);
            }

            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    img.src = e.target.result;
                    img.style.display = 'block';
                    icon.style.display = 'none';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        
        // Preview Product Video
        function previewVideo(input) {
            const preview = document.getElementById('videoPreviewContainer');
            const icon = document.getElementById('videoPlaceholderIcon');
            const video = document.getElementById('videoPreviewElement');

            if (input.files && input.files[0]) {
                const file = input.files[0];
                
                // Ensure size does not exceed 50MB dynamically on frontend
                if(file.size > 50000000) {
                    alert('Video size exceeds 50MB limit. Please upload a smaller file.');
                    input.value = '';
                    video.style.display = 'none';
                    icon.style.display = 'block';
                    return;
                }

                const fileURL = URL.createObjectURL(file);
                video.src = fileURL;
                video.style.display = 'block';
                icon.style.display = 'none';
            } else {
                video.style.display = 'none';
                icon.style.display = 'block';
                video.src = '';
            }
        }

        // Preview multiple gallery images
        function previewGalleryImages(input) {
            const container = document.getElementById('galleryPreviewContainer');
            container.innerHTML = ''; // Clear existing

            if (input.files) {
                Array.from(input.files).forEach(file => {
                    if (file.type.startsWith('image/')) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const div = document.createElement('div');
                            div.className = 'image-preview';
                            div.style.width = '60px';
                            div.style.height = '60px';
                            div.innerHTML = `<img src="${e.target.result}" style="display:block; width:100%; height:100%; object-fit:cover;">`;
                            container.appendChild(div);
                        }
                        reader.readAsDataURL(file);
                    }
                });
            }
            
            if (container.children.length === 0) {
                container.innerHTML = `
                    <div class="image-preview" style="width: 60px; height: 60px;">
                        <i class="fas fa-images text-muted"></i>
                    </div>
                `;
            }
        }

        // Validate total file size before submission
        function validateFileSize() {
            const mainImg = document.querySelector('input[name="main_image"]');
            const galleryImgs = document.querySelector('input[name="gallery_images[]"]');
            const productVid = document.querySelector('input[name="product_video"]');
            
            let totalSize = 0;
            
            if (mainImg && mainImg.files[0]) totalSize += mainImg.files[0].size;
            if (galleryImgs && galleryImgs.files) {
                Array.from(galleryImgs.files).forEach(file => totalSize += file.size);
            }
            if (productVid && productVid.files[0]) totalSize += productVid.files[0].size;
            
            // Get the actual PHP limit from backend
            const limitInMB = parseInt('<?php echo (int)ini_get("post_max_size"); ?>') || 8;
            const limit = limitInMB * 1024 * 1024;
            
            if (totalSize > limit) {
                alert(`Total upload size is ${(totalSize / (1024 * 1024)).toFixed(2)}MB, which exceeds your server's current limit of ${limitInMB}MB. Please remove some images or use a smaller video file.`);
                return false;
            }
            return true;
        }
    </script>
</body>
</html>