<?php
require_once __DIR__ . '/includes/config.php';

// Validate product ID
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    header('Location: ' . SITE_URL . '/shop.php');
    exit;
}

$product = getProductById($id);
if (!$product) {
    header('HTTP/1.0 404 Not Found');
    $pageTitle = 'Product Not Found';
    include __DIR__ . '/includes/header.php';
    echo '<div class="container py-5 text-center"><h3>Product not found.</h3><a href="' . SITE_URL . '/shop.php" class="btn btn-primary mt-3">Back to Shop</a></div>';
    include __DIR__ . '/includes/footer.php';
    exit;
}

$images  = $product['images'];
$pageTitle = $product['name'];

// Get a random phone for Call Now
$randomPhone = getRandomPhone();

// Build WhatsApp link using main WhatsApp number (first active)
$phones = getAllPhones();
$waPhone = null;
foreach ($phones as $ph) {
    if ($ph['is_active'] && $ph['whatsapp_number']) {
        $waPhone = $ph;
        break;
    }
}
$whatsappLink = $waPhone ? buildWhatsAppLink($product, $waPhone['whatsapp_number']) : '#';

// Related products (excluding current)
$db = getDB();
$stmt = $db->prepare(
    "SELECT p.*, (SELECT image_path FROM product_images WHERE product_id = p.id ORDER BY sort_order ASC LIMIT 1) AS main_image
     FROM products p WHERE p.id != ? AND p.selling_status = 'available' ORDER BY RAND() LIMIT 4"
);
$stmt->execute([$id]);
$relatedProducts = $stmt->fetchAll();

include __DIR__ . '/includes/header.php';
?>

<!-- Breadcrumb -->
<div class="container-fluid bg-secondary py-3 mb-0">
    <div class="container">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0">
                <li class="breadcrumb-item"><a href="<?= SITE_URL ?>/" class="text-white">Home</a></li>
                <li class="breadcrumb-item"><a href="<?= SITE_URL ?>/shop.php" class="text-white">Shop</a></li>
                <li class="breadcrumb-item active text-white-50"><?= sanitize($product['name']) ?></li>
            </ol>
        </nav>
    </div>
</div>

<!-- Product Detail -->
<div class="container-fluid py-5">
    <div class="container">
        <div class="row g-5">

            <!-- LEFT: Image Carousel -->
            <div class="col-xl-6 col-lg-6">
                <?php if (!empty($images)): ?>
                    <?php if (count($images) > 1): ?>
                        <div class="single-carousel owl-carousel" id="productCarousel">
                            <?php foreach ($images as $img): ?>
                            <div class="single-item"
                                 data-dot="<img class='img-fluid rounded' src='<?= UPLOAD_URL . sanitize($img['image_path']) ?>' alt=''>">
                                <div class="single-inner bg-light rounded p-4 text-center" style="min-height:380px;display:flex;align-items:center;justify-content:center;">
                                    <a href="<?= UPLOAD_URL . sanitize($img['image_path']) ?>" rel="lightbox" data-lightbox="product-<?= $product['id'] ?>" data-title="<?= sanitize($product['name']) ?>">
                                        <img src="<?= UPLOAD_URL . sanitize($img['image_path']) ?>"
                                             class="img-fluid rounded"
                                             style="max-height:350px;object-fit:contain;"
                                             alt="<?= sanitize($product['name']) ?>">
                                    </a>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <?php $img = $images[0]; ?>
                        <div class="single-item">
                            <div class="single-inner bg-light rounded p-4 text-center" style="min-height:380px;display:flex;align-items:center;justify-content:center;">
                                <a href="<?= UPLOAD_URL . sanitize($img['image_path']) ?>" rel="lightbox" data-lightbox="product-<?= $product['id'] ?>" data-title="<?= sanitize($product['name']) ?>">
                                    <img src="<?= UPLOAD_URL . sanitize($img['image_path']) ?>"
                                         class="img-fluid rounded"
                                         style="max-height:350px;object-fit:contain;"
                                         alt="<?= sanitize($product['name']) ?>">
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="bg-light rounded d-flex align-items-center justify-content-center" style="height:380px;">
                        <div class="text-center text-muted">
                            <i class="fas fa-image fa-5x mb-3"></i>
                            <p>No images available</p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- RIGHT: Product Info -->
            <div class="col-xl-6 col-lg-6">
                <div class="d-flex align-items-start justify-content-between mb-2">
                    <h2 class="fw-bold mb-0"><?= sanitize($product['name']) ?></h2>
                    <?= getStatusBadge($product['selling_status']) ?>
                </div>

                <h3 class="text-primary fw-bold my-3"><?= formatPrice($product['price']) ?></h3>

                <hr>

                <!-- Meta Details -->
                <div class="mb-3">
                    <?php if ($product['color']): ?>
                    <div class="d-flex align-items-center mb-2">
                        <strong class="me-2" style="min-width:100px;">Color:</strong>
                        <span class="product-color-swatch me-2"
                              style="background-color:<?= sanitize($product['color']) ?>;"
                              title="<?= sanitize($product['color']) ?>"></span>
                        <span><?= sanitize($product['color']) ?></span>
                    </div>
                    <?php endif; ?>

                    <div class="d-flex align-items-center mb-2">
                        <strong class="me-2" style="min-width:100px;">Status:</strong>
                        <?php
                        $statusText = [
                            'available'    => '<span class="text-success"><i class="fas fa-check-circle me-1"></i>In Stock & Available</span>',
                            'out_of_stock' => '<span class="text-danger"><i class="fas fa-times-circle me-1"></i>Currently Out of Stock</span>',
                            'coming_soon'  => '<span class="text-warning"><i class="fas fa-clock me-1"></i>Coming Soon</span>',
                        ];
                        echo $statusText[$product['selling_status']] ?? sanitize($product['selling_status']);
                        ?>
                    </div>

                    <div class="d-flex align-items-center mb-2">
                        <strong class="me-2" style="min-width:100px;">Images:</strong>
                        <span><?= count($images) ?> photo(s)</span>
                    </div>
                </div>

                <hr>

                <!-- Description -->
                <?php if ($product['description']): ?>
                <div class="mb-4">
                    <h5 class="fw-bold mb-2">Description</h5>
                    <p class="text-muted lh-lg"><?= nl2br(sanitize($product['description'])) ?></p>
                </div>
                <?php endif; ?>

                <hr>

                <!-- Action Buttons -->
                <div class="row g-3 mt-2">
                    <!-- Call Now Button (random number) -->
                    <?php if ($randomPhone): ?>
                    <div class="col-12">
                        <a href="tel:<?= sanitize($randomPhone['phone_number']) ?>"
                           class="btn call-btn text-white w-100 py-3 fs-5 fw-bold"
                           id="callNowBtn"
                           onclick="rotateCallNumber(event)">
                            <i class="fas fa-phone-alt me-2"></i>
                            Call Now &nbsp;<span class="call-number-display"><?= sanitize($randomPhone['phone_number']) ?></span>
                        </a>
                    </div>
                    <?php endif; ?>

                    <!-- WhatsApp Button -->
                    <?php if ($waPhone): ?>
                    <div class="col-12">
                        <a href="<?= $whatsappLink ?>"
                           target="_blank"
                           rel="noopener noreferrer"
                           class="btn whatsapp-btn text-white w-100 py-3 fs-5 fw-bold">
                            <i class="fab fa-whatsapp me-2"></i>
                            WhatsApp Us
                        </a>
                    </div>
                    <?php endif; ?>

                    <!-- Share Link -->
                    <div class="col-12">
                        <button class="btn btn-outline-secondary w-100 py-2" onclick="copyProductLink()">
                            <i class="fas fa-share-alt me-2"></i>Copy Product Link
                        </button>
                    </div>
                </div>

                <!-- Product Link (hidden, for copy) -->
                <input type="hidden" id="productLink" value="<?= getProductUrl($product['id']) ?>">

                <!-- All Phone Numbers (hidden, for JS rotation) -->
                <script>
                var allPhones = <?= json_encode(array_column(getAllPhones(), 'phone_number')) ?>;
                </script>
            </div>
        </div>
    </div>
</div>

<!-- Related Products -->
<?php if (!empty($relatedProducts)): ?>
<div class="container-fluid related-product bg-light py-5">
    <div class="container">
        <h4 class="fw-bold mb-4">Related Products</h4>
        <div class="row g-4">
            <?php foreach ($relatedProducts as $rp): ?>
            <div class="col-lg-3 col-md-6 col-sm-6">
                <div class="card border-0 shadow-sm h-100 product-card">
                    <a href="<?= SITE_URL ?>/product.php?id=<?= $rp['id'] ?>" class="text-decoration-none">
                        <div class="bg-light" style="height:180px;overflow:hidden;">
                            <?php if ($rp['main_image']): ?>
                                <img src="<?= UPLOAD_URL . sanitize($rp['main_image']) ?>"
                                     class="w-100 h-100 p-2"
                                     style="object-fit:contain;"
                                     alt="<?= sanitize($rp['name']) ?>">
                            <?php else: ?>
                                <div class="d-flex align-items-center justify-content-center h-100">
                                    <i class="fas fa-image fa-3x text-muted"></i>
                                </div>
                            <?php endif; ?>
                        </div>
                    </a>
                    <div class="card-body">
                        <a href="<?= SITE_URL ?>/product.php?id=<?= $rp['id'] ?>" class="text-decoration-none text-dark">
                            <h6 class="fw-bold"><?= sanitize($rp['name']) ?></h6>
                        </a>
                        <div class="d-flex align-items-center justify-content-between mt-2">
                            <span class="fw-bold text-primary"><?= formatPrice($rp['price']) ?></span>
                            <a href="<?= SITE_URL ?>/product.php?id=<?= $rp['id'] ?>" class="btn btn-sm btn-primary">View</a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<style>
.single-carousel .owl-dot img { width: 60px; height: 60px; object-fit: contain; border: 2px solid transparent; border-radius: 6px; }
.single-carousel .owl-dot.active img { border-color: #0d6efd; }
.single-carousel .owl-dots { margin-top: 12px; display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; }
.single-carousel .owl-dot { padding: 0 !important; background: none !important; }
.product-card { transition: transform 0.2s; }
.product-card:hover { transform: translateY(-4px); }
</style>

<script>
// Rotate call number randomly on each click
function rotateCallNumber(e) {
    if (!allPhones || allPhones.length === 0) return;
    var random = allPhones[Math.floor(Math.random() * allPhones.length)];
    var btn = document.getElementById('callNowBtn');
    if (btn) {
        btn.href = 'tel:' + random;
        btn.querySelector('.call-number-display').textContent = random;
    }
}

// Copy product link to clipboard
function copyProductLink() {
    var link = document.getElementById('productLink').value;
    if (navigator.clipboard) {
        navigator.clipboard.writeText(link).then(function() {
            alert('Product link copied!\n' + link);
        });
    } else {
        var el = document.createElement('textarea');
        el.value = link;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert('Product link copied!\n' + link);
    }
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
