<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\CodeGenerator; use App\Core\Database;
$slug=trim((string)($_GET['slug']??''));
$ref=trim((string)($_GET['ref']??''));if($ref!==''&&Database::safeFetchOne('SELECT id FROM affiliate_members WHERE referral_code=? AND status="active" LIMIT 1',[$ref]))$_SESSION['affiliate_referral_code']=$ref;
$product=Database::safeFetchOne('SELECT p.*,v.shop_name,v.slug vendor_slug,b.name brand_name,b.slug brand_slug,c.name category_name,c.slug category_slug FROM products p LEFT JOIN vendors v ON v.id=p.vendor_id LEFT JOIN brands b ON b.id=p.brand_id LEFT JOIN categories c ON c.id=p.category_id WHERE p.slug=? AND p.status="published" LIMIT 1',[$slug]);
if(!$product&&!Database::isConnected())$product=sample_products()[0];
if(!$product){http_response_code(404);$pageTitle='Product Not Found';include ROOT_PATH.'/app/Layouts/frontend_header.php';echo '<section class="container py-5"><div class="alert alert-warning">Product not found.</div></section>';include ROOT_PATH.'/app/Layouts/frontend_footer.php';exit;}
$variants=Database::safeFetchAll('SELECT * FROM product_variants WHERE product_id=? ORDER BY id',[$product['id']]);
$images=Database::safeFetchAll('SELECT * FROM product_images WHERE product_id=? ORDER BY sort_order,id',[$product['id']]);
$specs=Database::safeFetchAll('SELECT * FROM product_specifications WHERE product_id=? ORDER BY group_name,sort_order,id',[$product['id']]);
$reviews=Database::safeFetchAll('SELECT pr.*,u.name user_name FROM product_reviews pr LEFT JOIN users u ON u.id=pr.user_id WHERE pr.product_id=? AND pr.status="approved" ORDER BY pr.id DESC LIMIT 10',[$product['id']]);
$related=Database::safeFetchAll('SELECT p.* FROM related_products r JOIN products p ON p.id=r.related_product_id WHERE r.product_id=? AND p.status="published" ORDER BY r.sort_order LIMIT 4',[$product['id']]);
Database::safeExecute('INSERT INTO product_metrics (product_id,views,carts,sales,conversion_rate,updated_at) VALUES (?,1,0,0,0,NOW()) ON DUPLICATE KEY UPDATE views=views+1,updated_at=NOW()',[$product['id']]);
$payload=CodeGenerator::productPayload($product); $pageTitle=(($product['meta_title']??'')?:($product['name']??'Product')).' | '.BRAND_NAME; $pageDescription=mb_substr(trim(strip_tags((string)(($product['meta_description']??'')?:($product['short_description']??'')))),0,320); $pageOgImage=product_image(['image'=>(($product['og_image']??'')?:($product['image']??''))]); $pageOgType='product'; $pageCanonical=(APP_URL!==''?rtrim(APP_URL,'/').'/product/'.rawurlencode((string)$product['slug']):''); include ROOT_PATH.'/app/Layouts/frontend_header.php';
?>
<section class="container py-5"><div class="row g-5"><div class="col-lg-6"><img class="img-fluid rounded-4 border w-100" src="<?= e(product_image($product)) ?>" alt="<?= e($product['name']) ?>" style="max-height:560px;object-fit:contain"><?php if($images): ?><div class="d-flex gap-2 mt-3 flex-wrap"><?php foreach($images as $im): ?><img src="<?= e(product_image(['image'=>$im['image_path']])) ?>" width="80" height="70" style="object-fit:cover" class="border rounded" alt=""><?php endforeach; ?></div><?php endif; ?></div><div class="col-lg-6"><small class="text-muted"><a href="<?= url('public/products.php?category='.urlencode($product['category_slug']??'')) ?>"><?= e($product['category_name']??'') ?></a> / <?= e($product['sku']) ?></small><h1 class="fw-bold"><?= e($product['name']) ?></h1><div class="price fs-3 mb-2"><?= money($product['sale_price']?:$product['regular_price']) ?></div><div class="text-muted mb-3"><?= sanitize_rich_html((string)($product['short_description']??'')) ?></div><p>Stock: <strong><?= (int)$product['stock'] ?></strong> · Brand: <a href="<?= url('brand/'.($product['brand_slug']??'')) ?>"><?= e($product['brand_name']??'') ?></a> · Shop: <a href="<?= url('shop/'.($product['vendor_slug']??'')) ?>"><?= e($product['shop_name']??'') ?></a></p><?php if($variants): ?><label class="form-label">Option</label><select id="productVariant" class="form-select mb-3"><?php foreach($variants as $v): ?><option value="<?= (int)$v['id'] ?>" data-stock="<?= (int)$v['stock'] ?>"><?= e($v['variant_name']) ?> — <?= money($v['price']) ?> (<?= (int)$v['stock'] ?> in stock)</option><?php endforeach; ?></select><?php endif; ?><div class="d-flex flex-wrap gap-2 mb-4"><button class="btn btn-primary btn-lg" <?= (int)$product['stock']<1?'disabled':'' ?> onclick="phAddCart(<?= (int)$product['id'] ?>,1,document.getElementById('productVariant')?.value)">Add to Cart</button><?php if(current_user()): ?><button class="btn btn-outline-primary" onclick="phToggleList('wishlist',<?= (int)$product['id'] ?>,this,false)"><i class="bi bi-heart"></i></button><button class="btn btn-outline-primary" onclick="phToggleList('compare',<?= (int)$product['id'] ?>,this,false)">Compare</button><?php endif; ?></div><div class="row g-3"><div class="col-md-6"><div class="border rounded-4 p-3 text-center"><h6>Barcode</h6><?= CodeGenerator::barcodeSvg($product['sku']??('PH-'.$product['id']),54) ?></div></div><div class="col-md-6"><div class="border rounded-4 p-3 text-center qr-box"><h6>QR</h6><?= CodeGenerator::qrSvg($payload,180) ?></div></div></div><div class="mt-3"><a class="btn btn-outline-success btn-sm" target="_blank" rel="noopener" href="https://wa.me/?text=<?= urlencode(url('product/'.$product['slug'])) ?>">Share on WhatsApp</a></div></div></div>
<div class="row g-4 mt-4"><div class="col-lg-8"><div class="card border-0 shadow-sm"><div class="card-body"><h4>Description</h4><div class="product-rich-description"><?= sanitize_rich_html((string)($product['description']??'')) ?></div><?php if($specs): ?><h4 class="mt-4">Specifications</h4><table class="table table-striped"><?php foreach($specs as $s): ?><tr><th><?= e($s['spec_name']) ?></th><td><?= e($s['spec_value']) ?></td></tr><?php endforeach; ?></table><?php endif; ?></div></div></div><div class="col-lg-4"><div class="card border-0 shadow-sm"><div class="card-body"><h4>Customer reviews</h4><?php if(!$reviews): ?><p class="text-muted">No approved reviews yet.</p><?php endif; ?><?php foreach($reviews as $r): ?><div class="border-bottom py-2"><strong><?= e($r['user_name']??'Customer') ?></strong><span class="text-warning"><?= str_repeat('★',max(0,min(5,(int)$r['rating']))) ?></span><p class="mb-0 small"><?= e($r['review']) ?></p></div><?php endforeach; ?></div></div></div></div>
<?php if($related): ?><h3 class="mt-5">Related products</h3><div class="row g-4"><?php foreach($related as $p): ?><div class="col-md-3"><div class="product-card"><img class="w-100" src="<?= e(product_image($p)) ?>"><div class="p-3"><h6><?= e($p['name']) ?></h6><a class="btn btn-sm btn-primary" href="<?= url('product/'.$p['slug']) ?>">View</a></div></div></div><?php endforeach; ?></div><?php endif; ?></section>
<?php include ROOT_PATH.'/app/Layouts/frontend_footer.php'; ?>
