<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once "../config/db.php";

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

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

if ($id <= 0) {
    header("Location: products.php");
    exit();
}

// Get product details
$product = mysqli_query($conn, "SELECT * FROM products WHERE id = $id");

if (!$product || mysqli_num_rows($product) == 0) {
    $_SESSION['error'] = "Product not found!";
    header("Location: products.php");
    exit();
}

$product_data = mysqli_fetch_assoc($product);

// Get categories
$categories = mysqli_query($conn, "SELECT * FROM categories");

// Helper to get images array (handle JSON or old string)
function getImages($imgStr) {
    if (empty($imgStr)) return [];
    $decoded = json_decode($imgStr, true);
    return is_array($decoded) ? $decoded : [$imgStr];
}

$current_images = getImages($product_data['images']);

// Update product
if (isset($_POST['update_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'] ?? '0');
    $rental_price = mysqli_real_escape_string($conn, $_POST['rental_price']);
    $discount_percent = mysqli_real_escape_string($conn, $_POST['discount_percent']);
    $security_deposit = mysqli_real_escape_string($conn, $_POST['security_deposit'] ?? '0');
    $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'] ?? '3');
    $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']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $featured = isset($_POST['featured']) ? 1 : 0;
    $market_price = mysqli_real_escape_string($conn, $_POST['market_price'] ?? '0');
    
    // Handle Images
    $images_to_keep = isset($_POST['keep_images']) ? $_POST['keep_images'] : [];
    $final_images = [];
    
    // 1. Handle Main Image update
    if (isset($_FILES['main_image']) && $_FILES['main_image']['error'] == 0) {
        $file = $_FILES['main_image'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','webp','gif'];
        if (in_array($ext, $allowed)) {
            $new_name = 'main_' . time() . '_' . uniqid() . '.' . $ext;
            if (move_uploaded_file($file['tmp_name'], "../assets/images/products/" . $new_name)) {
                $final_images[] = $new_name;
                // Delete OLD main image if it was the first one
                if (!empty($current_images) && !in_array($current_images[0], $images_to_keep)) {
                     @unlink("../assets/images/products/" . $current_images[0]);
                }
            } else {
                // If upload failed, keep old main image if checked
                if (!empty($current_images) && in_array($current_images[0], $images_to_keep)) {
                    $final_images[] = $current_images[0];
                }
            }
        }
    } else {
        // Keep existing main image if it was at index 0 and still kept
        if (!empty($current_images) && in_array($current_images[0], $images_to_keep)) {
            $final_images[] = $current_images[0];
        }
    }

    // 2. Filter existing gallery images (excluding main which is index 0)
    foreach ($current_images as $idx => $img) {
        if ($idx == 0) continue; // Skip main (handled above)
        if (in_array($img, $images_to_keep)) {
            $final_images[] = $img;
        } else {
            @unlink("../assets/images/products/" . $img);
        }
    }
    
    // 3. Handle NEW gallery image uploads
    if (isset($_FILES['gallery_images']) && !empty($_FILES['gallery_images']['name'][0])) {
        $allowed = ['jpg','jpeg','png','webp','gif'];
        $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)) {
                        $final_images[] = $new_name;
                    }
                }
            }
        }
    }
    
    // 4. Handle Video File (Optional)
    $video_path_update = "";
    if (isset($_POST['remove_video']) && $_POST['remove_video'] == '1') {
        if (!empty($product_data['video_path'])) {
            @unlink("../assets/videos/products/" . $product_data['video_path']);
        }
        $video_path_update = ", video_path = NULL";
    } elseif (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) && $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)) {
                if (!empty($product_data['video_path'])) {
                    @unlink("../assets/videos/products/" . $product_data['video_path']);
                }
                $video_path_update = ", video_path = '$new_video_name'";
            }
        }
    }
    
    $images_json = mysqli_real_escape_string($conn, json_encode($final_images));
    
    $query = "UPDATE products SET 
              name = '$name',
              slug = '$slug',
              original_price = '$original_price',
              price = '$price',
              rental_price = '$rental_price',
              discount_percent = '$discount_percent',
              security_deposit = '$security_deposit',
              brand = '$brand',
              size = '$size',
              color = '$color',
              material = '$material',
              rental_days = '$rental_days',
              category_id = '$category_id',
              description = '$description',
              stock = '$stock',
              status = '$status',
              featured = '$featured',
              market_price = '$market_price',
              images = '$images_json'
              $video_path_update
              WHERE id = $id";
    
    if (mysqli_query($conn, $query)) {
        $_SESSION['flash_message'] = "Product updated successfully!";
        header("Location: products.php");
        exit();
    } else {
        $error = "Error updating product: " . 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>Edit Product - Admin</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">
    <style>
        /* Ensure the main content is visible next to the fixed sidebar */
        .main-content {
            margin-left: 200px;
            padding: 30px;
            background: #f8f9fa;
            min-height: 100vh;
        }
        @media (max-width: 768px) {
            .main-content { margin-left: 0; }
            .sidebar { position: relative; width: 100%; }
        }
    </style>
</head>
<body>
        <?php include __DIR__ . '/includes/sidebar.php'; ?>
    
    <div class="main-content">
        <div class="container-fluid">
            <h2 class="mb-4">Edit Product</h2>
            
            <?php if(isset($error)): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">Product Name</label>
                        <input type="text" name="name" id="productName" class="form-control" value="<?php echo htmlspecialchars($product_data['name']); ?>" required onkeyup="generateSlug(this.value)">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">Product Slug (SEO)</label>
                        <input type="text" name="slug" id="productSlug" class="form-control" value="<?php echo htmlspecialchars($product_data['slug'] ?? ''); ?>" required>
                    </div>
                </div>
                
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Original Price (₹)</label>
                        <div class="input-group">
                            <span class="input-group-text">₹</span>
                            <input type="number" 
                                   name="original_price" 
                                   class="form-control" 
                                   step="0.01"
                                   min="0"
                                   value="<?php echo htmlspecialchars($product_data['original_price'] ?? '0'); ?>">
                        </div>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label fw-bold">Market Price (MRP) (₹)</label>
                        <div class="input-group">
                            <span class="input-group-text">₹</span>
                            <input type="number" 
                                   name="market_price" 
                                   class="form-control" 
                                   step="0.01"
                                   min="0"
                                   value="<?php echo htmlspecialchars($product_data['market_price'] ?? '0'); ?>">
                        </div>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label fw-bold">Rental Price (₹)</label>
                        <div class="input-group">
                            <span class="input-group-text">₹</span>
                            <input type="number" 
                                   name="rental_price" 
                                   id="rental_price"
                                   class="form-control" 
                                   step="0.01"
                                   min="0"
                                   value="<?php echo htmlspecialchars($product_data['rental_price'] > 0 ? $product_data['rental_price'] : $product_data['price']); ?>">
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Discount (%)</label>
                        <div class="input-group">
                            <input type="number" 
                                   name="discount_percent" 
                                   id="discount_percent"
                                   class="form-control" 
                                   step="1"
                                   min="0"
                                   max="100"
                                   value="<?php echo htmlspecialchars($product_data['discount_percent']); ?>">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Final Price (₹)</label>
                        <div class="input-group">
                            <span class="input-group-text">₹</span>
                            <input type="number" 
                                   name="price" 
                                   id="final_price"
                                   class="form-control" 
                                   step="0.01"
                                   min="0"
                                   required
                                   readonly
                                   style="background-color: #f8f9fa;"
                                   value="<?php echo htmlspecialchars($product_data['price']); ?>">
                        </div>
                    </div>

                    <div class="col-md-12 mt-3">
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold">Security Deposit (₹)</label>
                                <div class="input-group">
                                    <span class="input-group-text">₹</span>
                                    <input type="number" 
                                           name="security_deposit" 
                                           class="form-control" 
                                           step="0.01"
                                           min="0"
                                           value="<?php echo htmlspecialchars($product_data['security_deposit'] ?? '0'); ?>">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-12 mb-3">
                        <div id="priceSummary" class="p-3 bg-light rounded border">
                            <!-- Price summary will be displayed here -->
                        </div>
                    </div>
                </div>
                    <div class="col-md-6 mb-3">
                        <label>Category</label>
                        <select name="category_id" class="form-control" required>
                            <option value="">Select Category</option>
                            <?php mysqli_data_seek($categories, 0); ?>
                            <?php while($cat = mysqli_fetch_assoc($categories)): ?>
                                <option value="<?php echo $cat['id']; ?>" <?php echo $product_data['category_id'] == $cat['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['category_name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Stock Quantity</label>
                        <input type="number" name="stock" class="form-control" value="<?php echo $product_data['stock']; ?>" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Status</label>
                        <select name="status" class="form-control">
                            <option value="active" <?php echo ($product_data['status'] ?? 'active') == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo ($product_data['status'] ?? 'active') == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-header mt-4 mb-3">
                    <h5 class="border-bottom pb-2"><i class="fas fa-list-ul me-2 text-primary"></i>Product Specifications</h5>
                </div>
                
                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label fw-bold">Brand</label>
                        <input type="text" name="brand" class="form-control" value="<?php echo htmlspecialchars($product_data['brand'] ?? ''); ?>" placeholder="e.g. Gucci, Zara">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label fw-bold">Material</label>
                        <input type="text" name="material" class="form-control" value="<?php echo htmlspecialchars($product_data['material'] ?? ''); ?>" placeholder="e.g. Silk, Cotton">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label fw-bold">Sizes Available</label>
                        <input type="text" name="size" class="form-control" value="<?php echo htmlspecialchars($product_data['size'] ?? ''); ?>" placeholder="e.g. S, M, L (comma separated)">
                        <small class="text-muted">Comma separated</small>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label fw-bold">Color</label>
                        <input type="text" name="color" class="form-control" value="<?php echo htmlspecialchars($product_data['color'] ?? ''); ?>" placeholder="e.g. Red, Blue">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label fw-bold">Rental Days</label>
                        <input type="number" name="rental_days" class="form-control" value="<?php echo htmlspecialchars($product_data['rental_days'] ?? '3'); ?>" min="1">
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Description</label>
                    <textarea name="description" class="form-control" rows="4"><?php echo htmlspecialchars($product_data['description']); ?></textarea>
                </div>
                
                <div class="mb-3">
                    <label class="form-label"><strong>Current Images</strong></label>
                    <div class="row g-2 mb-3">
                        <?php if (!empty($current_images)): ?>
                            <?php foreach ($current_images as $idx => $img): ?>
                                <div class="col-md-3">
                                    <div class="card h-100 border-<?php echo $idx == 0 ? 'primary' : 'secondary'; ?>">
                                        <div class="card-header p-1 text-center small <?php echo $idx == 0 ? 'bg-primary text-white' : ''; ?>">
                                            <?php echo $idx == 0 ? 'MAIN THUMBNAIL' : 'GALLERY IMAGE'; ?>
                                        </div>
                                        <img src="../assets/images/products/<?php echo htmlspecialchars($img); ?>" 
                                             class="card-img-top" 
                                             style="height: 120px; object-fit: cover;">
                                        <div class="card-body p-2 text-center">
                                            <div class="form-check d-inline-block">
                                                <input class="form-check-input" type="checkbox" name="keep_images[]" 
                                                       value="<?php echo htmlspecialchars($img); ?>" checked>
                                                <label class="form-check-label small">Keep</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="col-12 text-muted">No images found.</div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold text-primary">Replace Main Image</label>
                            <div class="image-preview mb-2" id="mainImagePreview" style="width: 200px; height: 200px; border: 2px dashed #ddd; border-radius: 10px; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                                <i class="fas fa-image fa-3x text-muted"></i>
                            </div>
                            <input type="file" name="main_image" class="form-control" accept="image/*" onchange="previewMainImage(this)">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Add Gallery Images</label>
                            <div id="galleryPreviewContainer" class="d-flex flex-wrap gap-2 mb-2">
                                <div class="image-preview" style="width: 60px; height: 60px; border: 2px dashed #ddd; border-radius: 10px; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                                    <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)">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label class="form-label fw-bold text-info">Product Video (Optional)</label>
                            <?php if(!empty($product_data['video_path'])): ?>
                                <div class="mb-2">
                                    <video src="../assets/videos/products/<?php echo htmlspecialchars($product_data['video_path']); ?>" style="max-height: 200px;" controls class="rounded border mb-2 d-block"></video>
                                    <div class="form-check text-danger mt-2">
                                        <input class="form-check-input" type="checkbox" name="remove_video" id="remove_video" value="1">
                                        <label class="form-check-label" for="remove_video">Remove existing video completely</label>
                                    </div>
                                </div>
                                <label class="form-label text-muted small mt-2">Or replace with a new video:</label>
                            <?php endif; ?>
                            <input type="file" name="product_video" class="form-control" accept="video/mp4,video/webm,video/ogg">
                            <small class="text-muted">Upload Max: 50MB (MP4, WebM)</small>
                        </div>
                    </div>
                </div>
                
                <div class="mb-3 form-check">
                    <input type="checkbox" name="featured" class="form-check-input" id="featured" value="1" <?php echo $product_data['featured'] ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="featured">Featured Product</label>
                </div>
                
                <button type="submit" name="update_product" class="btn btn-primary">
                    <i class="fas fa-save me-2"></i>Update Product
                </button>
                <a href="products.php" class="btn btn-secondary">
                    <i class="fas fa-times me-2"></i>Cancel
                </a>
            </form>
        </div>
    </div>
    <script>
        function generateSlug(text) {
            const slug = text.toLowerCase()
                .trim()
                .replace(/[^\w\s-]/g, '')
                .replace(/[\s_-]+/g, '-')
                .replace(/^-+|-+$/g, '');
            document.getElementById('productSlug').value = slug;
        }

        function previewMainImage(input) {
            const preview = document.getElementById('mainImagePreview');
            preview.innerHTML = '';
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.style.display = 'block';
                    img.style.maxWidth = '100%';
                    img.style.maxHeight = '100%';
                    preview.appendChild(img);
                }
                reader.readAsDataURL(input.files[0]);
            } else {
                preview.innerHTML = '<i class="fas fa-image fa-3x text-muted"></i>';
            }
        }

        function previewGalleryImages(input) {
            const container = document.getElementById('galleryPreviewContainer');
            container.innerHTML = '';
            if (input.files) {
                Array.from(input.files).forEach(file => {
                    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.style.border = '1px solid #ddd';
                        div.style.borderRadius = '5px';
                        div.style.display = 'flex';
                        div.style.alignItems = 'center';
                        div.style.justifyContent = 'center';
                        div.style.overflow = 'hidden';
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.style.display = 'block';
                        img.style.maxWidth = '100%';
                        img.style.maxHeight = '100%';
                        div.appendChild(img);
                        container.appendChild(div);
                    }
                    reader.readAsDataURL(file);
                });
            }
            if (container.innerHTML === '') {
                container.innerHTML = '<div class="image-preview" style="width: 60px; height: 60px;"><i class="fas fa-images text-muted"></i></div>';
            }
        }

        function calculateFinalPrice() {
            const rentalPrice = parseFloat(document.getElementById('rental_price').value) || 0;
            const discountPercent = parseFloat(document.getElementById('discount_percent').value) || 0;
            let finalPrice = rentalPrice;
            let discountAmount = 0;
            if (rentalPrice > 0 && discountPercent > 0) {
                discountAmount = (rentalPrice * discountPercent) / 100;
                finalPrice = rentalPrice - discountAmount;
            }
            document.getElementById('final_price').value = finalPrice.toFixed(2);
            
            const priceSummary = document.getElementById('priceSummary');
            if (rentalPrice > 0) {
                let summaryHTML = '';
                if (discountPercent > 0) {
                    summaryHTML = `
                        <div class="small">
                            <div class="d-flex align-items-center mb-1">
                                <span class="text-muted text-decoration-line-through me-2">₹${rentalPrice.toFixed(2)}</span>
                                <span class="badge bg-danger">(${discountPercent}%) OFF</span>
                            </div>
                            <div>
                                <strong class="text-success">Final Price: ₹${finalPrice.toFixed(2)}</strong>
                                <span class="text-muted ms-2">(Discount Amount: ₹${discountAmount.toFixed(2)})</span>
                            </div>
                        </div>
                    `;
                } else {
                    summaryHTML = `
                        <div class="small">
                            <strong class="text-success">Price: ₹${rentalPrice.toFixed(2)}</strong>
                            <span class="text-muted ms-2">(No discount)</span>
                        </div>
                    `;
                }
                priceSummary.innerHTML = summaryHTML;
            } else {
                priceSummary.innerHTML = '<span class="text-muted small">Enter price to see calculation</span>';
            }
        }

        // Event listeners
        document.getElementById('rental_price').addEventListener('input', calculateFinalPrice);
        document.getElementById('discount_percent').addEventListener('input', calculateFinalPrice);
        
        // Initialize on load
        calculateFinalPrice();
    </script>
</body>
</html>