<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

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

require_once __DIR__ . '/../config.php';

$message = "";

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: manage_products.php");
    exit();
}

$product_id = intval($_GET['id']);

// ছবির সাইজ কমানোর ফাংশন
function compressAndUploadImage($source_file, $target_path, $quality = 60) {
    $img_info = getimagesize($source_file);
    if ($img_info === false) return false;
    $mime = $img_info['mime'];
    
    switch ($mime) {
        case 'image/jpeg': case 'image/jpg': $image = imagecreatefromjpeg($source_file); break;
        case 'image/png': 
            $image = imagecreatefrompng($source_file);
            imagealphablending($image, false); imagesavealpha($image, true);
            break;
        case 'image/webp': $image = imagecreatefromwebp($source_file); break;
        case 'image/gif': $image = imagecreatefromgif($source_file); break;
        default: return false;
    }

    if ($mime == 'image/png') {
        $png_quality = round((100 - $quality) / 10);
        $result = imagepng($image, $target_path, $png_quality);
    } elseif ($mime == 'image/webp') {
        $result = imagewebp($image, $target_path, $quality);
    } else {
        $result = imagejpeg($image, $target_path, $quality);
    }
    imagedestroy($image);
    return $result;
}

// প্রোডাক্ট আপডেট লজিক
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_product'])) {
    $category_id = intval($_POST['category_id']);
    $sku = !empty(trim($_POST['sku'])) ? trim($_POST['sku']) : null;
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $sizes = !empty($_POST['sizes']) ? trim($_POST['sizes']) : null;
    $colors = !empty($_POST['colors']) ? trim($_POST['colors']) : null;
    $price = floatval($_POST['price']);
    $discount_price = !empty($_POST['discount_price']) ? floatval($_POST['discount_price']) : null;
    $stock_quantity = intval($_POST['stock_quantity']);
    $is_featured = isset($_POST['is_featured']) ? 1 : 0;

    try {
        if ($sku !== null) {
            $stmt = $pdo->prepare("SELECT id FROM products WHERE sku = :sku AND id != :id");
            $stmt->execute(['sku' => $sku, 'id' => $product_id]);
            if ($stmt->rowCount() > 0) {
                $message = "<div class='alert alert-danger'>এই SKU কোডটি অন্য একটি প্রোডাক্টে ইতিমধ্যে ব্যবহার করা হয়েছে!</div>";
            }
        }

        if (empty($message)) {
            $image_name = $_POST['current_image'];
            if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
                $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                if (in_array($ext, ["jpg", "jpeg", "png", "webp", "gif"])) {
                    $new_image_name = "prod_" . time() . "_" . rand(1000, 9999) . "." . $ext;
                    if (compressAndUploadImage($_FILES['image']['tmp_name'], "../uploads/products/" . $new_image_name, 60)) {
                        if (!empty($image_name) && file_exists("../uploads/products/" . $image_name)) unlink("../uploads/products/" . $image_name);
                        $image_name = $new_image_name;
                    }
                }
            }

            $sql = "UPDATE products SET category_id = :category_id, sku = :sku, name = :name, description = :description, sizes = :sizes, colors = :colors, price = :price, discount_price = :discount_price, stock_quantity = :stock_quantity, image = :image, is_featured = :is_featured WHERE id = :id";
            $update_stmt = $pdo->prepare($sql);
            $update_stmt->execute(['category_id' => $category_id, 'sku' => $sku, 'name' => $name, 'description' => $description, 'sizes' => $sizes, 'colors' => $colors, 'price' => $price, 'discount_price' => $discount_price, 'stock_quantity' => $stock_quantity, 'image' => $image_name, 'is_featured' => $is_featured, 'id' => $product_id]);

            // গ্যালারি ইমেজ আপলোড (লিমিটসহ)
            $gal_count_stmt = $pdo->prepare("SELECT COUNT(*) FROM product_images WHERE product_id = ?");
            $gal_count_stmt->execute([$product_id]);
            $current_count = $gal_count_stmt->fetchColumn();

            if (isset($_FILES['gallery_images'])) {
                foreach ($_FILES['gallery_images']['name'] as $i => $name) {
                    if ($current_count >= 5) {
                        $message .= "<div class='alert alert-warning'>সতর্কতা: গ্যালারিতে ৫টির বেশি ছবি রাখা সম্ভব নয়। কিছু ছবি আপলোড হয়নি।</div>";
                        break;
                    }
                    if ($_FILES['gallery_images']['error'][$i] == 0) {
                        $ext = strtolower(pathinfo($_FILES['gallery_images']['name'][$i], PATHINFO_EXTENSION));
                        if (in_array($ext, ["jpg", "jpeg", "png", "webp", "gif"])) {
                            $new_g_name = "gal_" . time() . "_" . rand(10000, 99999) . "." . $ext;
                            if (compressAndUploadImage($_FILES['gallery_images']['tmp_name'][$i], "../uploads/products/" . $new_g_name, 60)) {
                                $pdo->prepare("INSERT INTO product_images (product_id, image_name) VALUES (?, ?)")->execute([$product_id, $new_g_name]);
                                $current_count++;
                            }
                        }
                    }
                }
            }
            $message .= "<div class='alert alert-success'>প্রোডাক্ট সফলভাবে আপডেট করা হয়েছে!</div>";
        }
    } catch (PDOException $e) {
        $message = "<div class='alert alert-danger'>ডাটাবেস ত্রুটি: " . htmlspecialchars($e->getMessage()) . "</div>";
    }
}

// গ্যালারি ডিলিট লজিক
if (isset($_GET['delete_gallery_id'])) {
    $gal_id = intval($_GET['delete_gallery_id']);
    $stmt = $pdo->prepare("SELECT image_name FROM product_images WHERE id = ? AND product_id = ?");
    $stmt->execute([$gal_id, $product_id]);
    $img = $stmt->fetch();
    if ($img) {
        if (file_exists("../uploads/products/" . $img['image_name'])) unlink("../uploads/products/" . $img['image_name']);
        $pdo->prepare("DELETE FROM product_images WHERE id = ?")->execute([$gal_id]);
        header("Location: edit_product.php?id=" . $product_id);
        exit();
    }
}

// ডেটা আনা
$product = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$product->execute([$product_id]);
$product = $product->fetch(PDO::FETCH_ASSOC);
if (!$product) { header("Location: manage_products.php"); exit(); }

$gallery = $pdo->prepare("SELECT * FROM product_images WHERE product_id = ?");
$gallery->execute([$product_id]);
$gallery = $gallery->fetchAll(PDO::FETCH_ASSOC);

$categories = $pdo->query("SELECT id, name FROM categories ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ShopVista | Edit Product</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/sidebar.css?v=3.0">
    <link rel="stylesheet" href="css/dashboard.css?v=3.0">
    <link rel="stylesheet" href="css/products.css?v=3.0">
    
    <link rel="stylesheet" href="css/edit_product.css?v=1.0">
</head>
<body>

    <?php include 'sidebar.php'; ?>

    <div class="main-content">
        <div class="top-bar">
            <h2 class="page-title"><i class="fa-solid fa-pen-to-square"></i> প্রোডাক্ট এডিট করুন</h2>
            <div class="admin-badge">
                <i class="fa-regular fa-user-circle"></i> এডমিন: <?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?>
            </div>
        </div>

        <?php echo $message; ?>

        <div class="full-width-card">
            <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #e3e6f0; padding-bottom: 10px;">
                <h3><i class="fa-solid fa-box"></i> প্রোডাক্টের তথ্য পরিবর্তন করুন</h3>
                <a href="products.php" class="btn-submit" style="background: #858796; padding: 8px 15px; text-decoration: none; font-size: 0.9rem;"><i class="fa-solid fa-arrow-left"></i> তালিকায় ফিরে যান</a>
            </div>

            <form action="" method="POST" enctype="multipart/form-data" style="margin-top: 20px;">
                <input type="hidden" name="current_image" value="<?php echo htmlspecialchars($product['image']); ?>">

                <div class="form-grid-3">
                    <div class="form-group">
                        <label for="prodName">প্রোডাক্টসের নাম ইংরেজিতে *</label>
                        <input type="text" id="prodName" name="name" value="<?php echo htmlspecialchars($product['name']); ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="prodCategory">ক্যাটাগরি সিলেক্ট করুন *</label>
                        <select id="prodCategory" name="category_id" class="form-control" required>
                            <?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 class="form-group">
                        <label for="prodSku">SKU কোড (ঐচ্ছিক)</label>
                        <input type="text" id="prodSku" name="sku" value="<?php echo htmlspecialchars($product['sku'] ?? ''); ?>">
                    </div>
                </div>

                <div class="form-grid-3">
                    <div class="form-group">
                        <label for="prodSizes">সাইজসমূহ (ঐচ্ছিক)</label>
                        <input type="text" id="prodSizes" name="sizes" value="<?php echo htmlspecialchars($product['sizes'] ?? ''); ?>" placeholder="যেমন: M, L, XL">
                        <small class="helper-text">* কমা (,) দিয়ে আলাদা করে লিখুন</small>
                    </div>
                    <div class="form-group">
                        <label for="prodColors">কালারসমূহ (ঐচ্ছিক)</label>
                        <input type="text" id="prodColors" name="colors" value="<?php echo htmlspecialchars($product['colors'] ?? ''); ?>" placeholder="যেমন: Red, Black, Blue">
                        <small class="helper-text">* কমা (,) দিয়ে আলাদা করে লিখুন</small>
                    </div>
                    <div class="form-group">
                        </div>
                </div>

                <div class="form-grid-3">
                    <div class="form-group">
                        <label for="prodPrice">মূল্য (Regular Price) *</label>
                        <input type="number" step="0.01" id="prodPrice" name="price" value="<?php echo $product['price']; ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="prodDiscount">ডিসকাউন্ট মূল্য (Sale Price)</label>
                        <input type="number" step="0.01" id="prodDiscount" name="discount_price" value="<?php echo $product['discount_price'] ?? ''; ?>">
                    </div>
                    <div class="form-group">
                        <label for="prodStock">স্টক পরিমাণ (Quantity) *</label>
                        <input type="number" id="prodStock" name="stock_quantity" value="<?php echo $product['stock_quantity']; ?>" required>
                    </div>
                </div>

                <div class="textarea-group">
                    <label for="prodDesc">প্রোডাক্ট বিস্তারিত বিবরণ (Description)</label>
                    <textarea id="prodDesc" name="description" rows="4"><?php echo htmlspecialchars($product['description']); ?></textarea>
                </div>

                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; margin-bottom: 25px;">
                    <div class="form-group">
                        <label for="prodImage">নতুন প্রধান ছবি (পরিবর্তন করতে চাইলে)</label>
                        <input type="file" id="prodImage" name="image" accept="image/*">
                        <div class="image-preview-box">
                            <span>বর্তমান ছবি:</span>
                            <?php if (!empty($product['image']) && file_exists("../uploads/products/" . $product['image'])): ?>
                                <img src="../uploads/products/<?php echo $product['image']; ?>" style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;">
                            <?php else: ?>
                                <span style="color:#e74a3b;">কোনো ছবি নেই</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="checkbox-group">
                        <input type="checkbox" id="prodFeatured" name="is_featured" value="1" <?php echo ($product['is_featured'] == 1) ? 'checked' : ''; ?>>
                        <label for="prodFeatured" style="font-weight: 600; color: #4e73df; cursor:pointer;">ফিচার্ড প্রোডাক্ট হিসেবে দেখান</label>
                    </div>
                </div>

                <div class="full-width-card" style="background: #f8f9fc; border: 1px dashed #d1d3e2;">
                    <label style="font-weight: bold; color: #4e73df; font-size: 1rem;"><i class="fa-regular fa-images"></i> প্রোডাক্ট গ্যালারি ছবি (সর্বোচ্চ ৫টি ছবি একসাথে আপলোড করতে পারবেন)</label>
                    <input type="file" name="gallery_images[]" accept="image/*" multiple style="margin-top: 10px; display: block;">
                    <small class="helper-text" style="color:#858796;">* আপলোডের সময় সিস্টেম ছবির সাইজ স্বয়ংক্রিয়ভাবে কমিয়ে (Compress করে) স্টোরেজ সাশ্রয় করবে।</small>

                    <div class="gallery-container">
                        <?php if (count($gallery) > 0): ?>
                            <?php foreach ($gallery as $g_item): ?>
                                <div class="gallery-item">
                                    <img src="../uploads/products/<?php echo $g_item['image_name']; ?>" alt="Gallery Image">
                                    <a href="?id=<?php echo $product_id; ?>&delete_gallery_id=<?php echo $g_item['id']; ?>" class="delete-btn" onclick="return confirm('আপনি কি নিশ্চিতভাবে গ্যালারির এই ছবিটি ডিলিট করতে চান?')" title="ডিলিট">✕</a>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <p style="font-size: 0.85rem; color: #858796; margin-top: 10px;">এখনো কোনো গ্যালারি ছবি যুক্ত করা হয়নি।</p>
                        <?php endif; ?>
                    </div>
                </div>

                <button type="submit" name="update_product" class="btn-submit" style="width: auto; padding: 12px 35px; background: #1cc88a;">
                    <i class="fa-solid fa-save"></i> আপডেট সংরক্ষণ করুন
                </button>
            </form>
        </div>
    </div>

</body>
</html>