<?php session_start();
ob_start();

include("configa.php");

if( isset($_GET['id']) && isset($_GET['ref']) ){
  $id = $_GET['id'];
  $ref = $_GET['ref'];
}else{
  $id = 1;
  $ref = '';
}

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

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

$stmt = $conn->prepare("SELECT * FROM goods_category WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result2 = $stmt->get_result();
$row2 = $result2->fetch_object();

if (!$row2) {
    echo "পণ্যটি পাওয়া যায়নি।";
    $conn->close();
    return;
}
?>

<div class="img_order_payment_container">
    <div>
        <img class="model" src="category/jamal.jpg">
    </div>

    <div class="img_order_payment">
        <div class="product_image">
            <img style="width: 70%;" class="product_img" src='<?php echo "category/" . $row2->category_picture;?>'>
        </div>
        <div class="order_box">
            <p>
                <strong>
                    <span style="font-size: 20pt;"><?php echo "পণ্য : " . $row2->product_name;?></span>
                </strong>
                <br>
                <?php echo "ক্যাটাগরী : " . $row2->item;?><br>
                <?php echo "সিরিয়াল নং : " . $row2->gks;?><br>
                <?php echo "বিক্রেতা : " . $row2->seller;?>
            </p>
            <hr>
            <br>
            <div style="display: flex; flex-direction: row; ">
                <strong>
                    <span style="font-size: 20pt; margin: 5pt; color: red;"><?php echo "Taka : " . $row2->current_price;?></span>
                </strong>
                <span style="font-size: 18pt; margin: 5pt; text-decoration: line-through; color: #969496"><?php echo "" . " " . $row2->price;?></span>
                <span style="font-size: 12pt; margin: 5pt; color: #097EF7; "><?php echo "" . " " . $row2->discount . " Off";?></span>
            </div>
            <div class="rating-container">
                <span class="stars" id="productStars">*****</span>
                <span class="review-count" id="productReviews">0 Review(S)</span>
            </div>
            <div style="display: flex; flex-direction: row;">
                <div class="quantity-control">
                    <span class="minus">-</span>
                    <input type="text" name="quantity_input" value="1" class="quantity-input">
                    <span class="plus">+</span>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="heading_details" style="width: 100%;">
    <div class="tab-buttons">
        <button class="tab-button active" data-target="descriptionChild">Description</button>
        <button class="tab-button" data-target="specificationChild">Specification</button>
    </div>
    <div class="description">
        <div class="descriptionChild tab-content active">
            <?php echo $row2->description; ?>
        </div>
    </div>
    <div class="specification">
        <div class="specificationChild tab-content">
            <?php echo $row2->specification; ?>
        </div>
    </div>
</div>

<video id="previewVideo" width="600" controls></video>
<canvas id="videoCanvas" width="600" height="400" hidden></canvas>

<script src="https://cdn.jsdelivr.net/npm/ccapture.js@1.1.0/build/CCapture.all.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('videoCanvas');
    const ctx = canvas.getContext('2d');
    const video = document.getElementById('previewVideo');

    const productImgElement = document.querySelector('.product_img');
    const productImg = productImgElement ? productImgElement.src : null;
    const productName = "<?php echo $row2->product_name; ?>";
    const description = "<?php echo preg_replace('/<[^>]*>/', '', $row2->description); ?>";
    const tabs = ["Description", "Specification", "Vendor Info", "Customer Reviews", "Q&A"];

    if (!productImg) {
        console.error("Product image element not found.");
        return;
    }

    const img = new Image();
    img.src = productImg;

    img.onload = () => {
        const capturer = new CCapture({
            format: 'webm',
            framerate: 30,
            quality: 10
        });

        // ভিডিও ক্যাপচার শুরু
        capturer.start();
        animate();
    };

    function animate(frame = 0) {
        if (frame > 150) { // 5 seconds @ 30fps
            capturer.stop();
            capturer.save((blob) => {
                const formData = new FormData();
                formData.append('video', blob, 'video.webm');
                formData.append('description', description);

                fetch('process_video.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("ভিডিও মার্জ সফল হয়েছে:", data);
                    if (data.video_url) {
                        video.src = data.video_url;
                        video.play();
                    } else {
                        console.error("ভিডিও URL পাওয়া যায়নি।");
                    }
                })
                .catch(error => {
                    console.error('ভিডিও আপলোড বা মার্জ করতে সমস্যা হয়েছে:', error);
                });
            });
            return;
        }

        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 50, 50, 200, 200);
        ctx.font = "bold 24px Arial";
        ctx.fillStyle = "black";
        ctx.fillText("পণ্য: " + productName, 50, 30);
        tabs.forEach((tab, index) => {
            ctx.font = "20px Arial";
            ctx.fillStyle = "#007bff";
            ctx.fillText(tab, 300, 100 + index * 30);
        });
        ctx.font = "20px Arial";
        ctx.fillStyle = "blue";
        ctx.fillText("মডেল বলছে: " + description.substring(0, 50) + "...", 50, 300);

        capturer.capture(canvas);
        requestAnimationFrame(() => animate(frame + 1));
    }

    img.onerror = () => {
        console.error("Image failed to load:", productImg);
    };
});
</script>