<?php
declare(strict_types=1);require __DIR__.'/bootstrap.php';
$lang=($_GET['lang']??'en')==='bn'?'bn':'en';
function tr(string $en,string $bn):string{global $lang;return $lang==='bn'?$bn:$en;}
function store_link(array $params=[]):string{global $lang;$params=array_merge($params,['lang'=>$lang]);return 'index.php?'.http_build_query($params);}
function short_text(string $text,int $limit=155):string{$length=function_exists('mb_strlen')?mb_strlen($text):strlen($text);if($length<=$limit)return $text;return (function_exists('mb_substr')?mb_substr($text,0,$limit-3):substr($text,0,$limit-3)).'…';}
$settings=store_settings($pdo);$pixel=(string)($settings['facebook_pixel']??'');
function uuid4():string{$d=random_bytes(16);$d[6]=chr((ord($d[6])&15)|64);$d[8]=chr((ord($d[8])&63)|128);return vsprintf('%s%s-%s-%s-%s-%s%s%s',str_split(bin2hex($d),4));}
function pixel_head(string $id):string{if(!preg_match('/^\d{5,25}$/',$id))return '';return "<script>!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('init','".e($id)."');fbq('track','PageView');</script>";}
function meta_purchase(array $settings,array $order):void{$dataset=trim((string)($settings['facebook_dataset_id']??$settings['facebook_pixel']??''));$token=trim((string)($settings['facebook_access_token']??''));if(!preg_match('/^\d{5,25}$/',$dataset)||$token==='')return;$phone=preg_replace('/\D+/','',(string)$order['phone']);$payload=['data'=>[['event_name'=>'Purchase','event_time'=>time(),'event_id'=>$order['id'],'action_source'=>'website','event_source_url'=>(isset($_SERVER['HTTPS'])?'https':'http').'://'.($_SERVER['HTTP_HOST']??'localhost').($_SERVER['REQUEST_URI']??'/'),'user_data'=>array_filter(['ph'=>$phone?hash('sha256',$phone):null,'client_ip_address'=>$_SERVER['REMOTE_ADDR']??null,'client_user_agent'=>$_SERVER['HTTP_USER_AGENT']??null]),'custom_data'=>['currency'=>'BDT','value'=>(float)$order['total'],'order_id'=>$order['id']]]]];$url='https://graph.facebook.com/v21.0/'.rawurlencode($dataset).'/events?access_token='.rawurlencode($token);if(function_exists('curl_init')){$ch=curl_init($url);curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode($payload),CURLOPT_HTTPHEADER=>['Content-Type: application/json'],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>4]);curl_exec($ch);curl_close($ch);}}
function send_store_mail(PDO $pdo,array $settings,string $orderId,string $to,string $subject,string $html,string $type):bool{
 $to=trim($to);$sent=false;$error='';
 if(!filter_var($to,FILTER_VALIDATE_EMAIL)){$error='Invalid recipient email.';}elseif(!function_exists('mail')){$error='PHP mail function is unavailable.';}else{
  $from=trim((string)($settings['mail_from_email']??''));if(!filter_var($from,FILTER_VALIDATE_EMAIL)){$from=trim((string)($settings['notification_email']??''));}
  if(!filter_var($from,FILTER_VALIDATE_EMAIL)){$host=preg_replace('/:\d+$/','',(string)($_SERVER['HTTP_HOST']??''));$from=preg_match('/^[a-z0-9.-]+$/i',$host)?'no-reply@'.$host:'';}
  $fromName=preg_replace('/[\r\n]+/',' ',trim((string)($settings['mail_from_name']??$settings['site_name']??'Personalized StoryBook')));
  $safeSubject=preg_replace('/[\r\n]+/',' ',$subject);if(function_exists('mb_encode_mimeheader')){$safeSubject=mb_encode_mimeheader($safeSubject,'UTF-8','B','\r\n');$fromName=mb_encode_mimeheader($fromName,'UTF-8','B','\r\n');}$headers=['MIME-Version: 1.0','Content-Type: text/html; charset=UTF-8'];if(filter_var($from,FILTER_VALIDATE_EMAIL))$headers[]='From: '.$fromName.' <'.$from.'>';$reply=filter_var($settings['notification_email']??'',FILTER_VALIDATE_EMAIL)?$settings['notification_email']:$from;if(filter_var($reply,FILTER_VALIDATE_EMAIL))$headers[]='Reply-To: '.$reply;
  $sent=@mail($to,$safeSubject,$html,implode("\r\n",$headers));if(!$sent)$error='The cPanel mail server did not accept the message.';
 }
 try{$log=$pdo->prepare('INSERT INTO store_email_log(order_id,recipient,email_type,sent,error_message) VALUES(?,?,?,?,?)');$log->execute([$orderId,$to,$type,$sent?1:0,$error?:null]);}catch(Throwable $e){}
 return $sent;
}
function notify_store_order(PDO $pdo,array $settings,array $order,string $lang):void{
 $site=e((string)($settings['site_name']??'Personalized StoryBook'));$id=e($order['id']);$product=e($order['product']);$customer=e($order['customer']);$phone=e($order['phone']);$address=nl2br(e($order['address']));$character=e($order['character']);$age=e($order['age']);$gender=e($order['gender']);$bookLanguage=$order['book_language']==='bn'?'Bangla':'English';$zone=$order['zone']==='outside'?'Outside Dhaka':'Inside Dhaka';$notes=$order['notes']!==''?nl2br(e($order['notes'])):'—';$total=money($order['total']);
 $style='<div style="font-family:Arial,sans-serif;max-width:680px;margin:auto;color:#221711"><div style="background:#23649b;color:#fff;padding:18px 22px"><h2 style="margin:0">'.$site.'</h2></div><div style="padding:22px;border:1px solid #ded9d4">';
 $admin=$style.'<h2>New storefront order</h2><p><b>Order ID:</b> '.$id.'</p><table style="width:100%;border-collapse:collapse;line-height:1.7"><tr><td><b>Book</b></td><td>'.$product.'</td></tr><tr><td><b>Book language</b></td><td>'.$bookLanguage.'</td></tr><tr><td><b>Customer</b></td><td>'.$customer.'</td></tr><tr><td><b>Phone</b></td><td>'.$phone.'</td></tr><tr><td><b>Email</b></td><td>'.e($order['email']?:'—').'</td></tr><tr><td><b>Address</b></td><td>'.$address.'</td></tr><tr><td><b>Delivery</b></td><td>'.$zone.' ('.money($order['delivery']).')</td></tr><tr><td><b>Character</b></td><td>'.$character.', age '.$age.', '.$gender.'</td></tr><tr><td><b>Photos</b></td><td>Required face photo + '.count($order['extra_photos']).' additional photo(s) saved with the order</td></tr><tr><td><b>Notes</b></td><td>'.$notes.'</td></tr><tr><td><b>Total</b></td><td><b>'.$total.'</b></td></tr></table></div></div>';
 $adminEmail=trim((string)($settings['notification_email']??''));if(filter_var($adminEmail,FILTER_VALIDATE_EMAIL))send_store_mail($pdo,$settings,$order['id'],$adminEmail,'New StoryBook order — '.$order['id'],$admin,'admin');
 if(filter_var($order['email'],FILTER_VALIDATE_EMAIL)){$bn=$lang==='bn';$customerHtml=$style.'<h2>'.($bn?'আপনার অর্ডার গ্রহণ করা হয়েছে':'Your order has been received').'</h2><p>'.($bn?'ধন্যবাদ':'Thank you').', '.$customer.'।</p><p>'.($bn?'আমরা আপনার ব্যক্তিগত StoryBook তৈরি করার আগে প্রিভিউ পাঠাব।':'We will send you a preview before producing your personalized StoryBook.').'</p><table style="width:100%;border-collapse:collapse;line-height:1.8"><tr><td><b>'.($bn?'অর্ডার আইডি':'Order ID').'</b></td><td>'.$id.'</td></tr><tr><td><b>'.($bn?'বই':'Book').'</b></td><td>'.$product.'</td></tr><tr><td><b>'.($bn?'বইয়ের ভাষা':'Book language').'</b></td><td>'.$bookLanguage.'</td></tr><tr><td><b>'.($bn?'চরিত্র':'Character').'</b></td><td>'.$character.', '.$age.'</td></tr><tr><td><b>'.($bn?'মোট':'Total').'</b></td><td>'.$total.'</td></tr></table><p>'.($bn?'প্রয়োজনে আমাদের সঙ্গে যোগাযোগ করুন।':'Contact us if you need any help.').'</p></div></div>';send_store_mail($pdo,$settings,$order['id'],$order['email'],$bn?'আপনার StoryBook অর্ডার নিশ্চিত হয়েছে':'Your StoryBook order is confirmed',$customerHtml,'customer');}
}
$slug=trim((string)($_GET['book']??''));$checkout=isset($_GET['checkout']);$success=false;$error='';$product=null;
if($slug!==''){$s=$pdo->prepare('SELECT * FROM store_products WHERE slug=? AND active=1');$s->execute([$slug]);$product=$s->fetch();if(!$product){http_response_code(404);}}
if($_SERVER['REQUEST_METHOD']==='POST'&&$product){check_csrf();
 $customer=trim((string)($_POST['customer_name']??''));$phone=trim((string)($_POST['phone']??''));$email=trim((string)($_POST['customer_email']??''));$address=trim((string)($_POST['delivery_address']??''));$zone=($_POST['delivery_zone']??'inside')==='outside'?'outside':'inside';$notes=trim((string)($_POST['notes']??''));$name=trim((string)($_POST['character_name']??''));$age=trim((string)($_POST['character_age']??''));$gender=($_POST['character_gender']??'girl')==='boy'?'boy':'girl';$bookLanguage=($_POST['book_language']??'en')==='bn'?'bn':'en';$coupon=strtoupper(preg_replace('/[^A-Za-z0-9_-]/','',trim((string)($_POST['coupon_code']??''))));
 if(!$customer||!$phone||!$address||!$name||!$age)$error=tr('Please complete all required information.','সব প্রয়োজনীয় তথ্য পূরণ করুন।');elseif($email!==''&&!filter_var($email,FILTER_VALIDATE_EMAIL))$error=tr('Please enter a valid email address.','সঠিক ইমেইল ঠিকানা দিন।');elseif(empty($_FILES['baby_photo']['tmp_name']))$error=tr('A clear front-facing child photo is required.','শিশুর সামনে থেকে তোলা পরিষ্কার ছবি অবশ্যই দিতে হবে।');else try{$babyPhoto=upload_image('baby_photo','customer-face');$extraPhotos=[];foreach(array_slice($_FILES['extra_photos']['tmp_name']??[],0,5) as $i=>$tmp){if(!$tmp)continue;$_FILES['_extra_photo']=['name'=>$_FILES['extra_photos']['name'][$i],'type'=>$_FILES['extra_photos']['type'][$i],'tmp_name'=>$tmp,'error'=>$_FILES['extra_photos']['error'][$i],'size'=>$_FILES['extra_photos']['size'][$i]];$uploaded=upload_image('_extra_photo','customer-extra');if($uploaded)$extraPhotos[]=$uploaded;}$subtotal=(float)$product['price'];$delivery=$zone==='outside'?150:80;$discount=0;if($coupon){$c=$pdo->prepare('SELECT * FROM store_coupons WHERE code=? AND active=1 AND (expires_at IS NULL OR expires_at>=CURDATE())');$c->execute([$coupon]);$cp=$c->fetch();if(!$cp)throw new RuntimeException(tr('Coupon code is not valid.','কুপন কোডটি সঠিক নয়।'));$discount=$cp['discount_type']==='percent'?$subtotal*min(100,(float)$cp['discount_value'])/100:min($subtotal,(float)$cp['discount_value']);}$total=max(0,$subtotal-$discount)+$delivery;$id=uuid4();$now=gmdate('c');$pdo->beginTransaction();$s=$pdo->prepare('INSERT INTO store_orders(id,product_id,customer_name,phone,customer_email,delivery_address,delivery_zone,delivery_fee,notes,character_name,character_age,character_gender,book_language,baby_photo,extra_photos_json,subtotal,discount,coupon_code,total) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');$s->execute([$id,$product['id'],$customer,$phone,$email?:null,$address,$zone,$delivery,$notes,$name,$age,$gender,$bookLanguage,$babyPhoto,json_encode($extraPhotos,JSON_UNESCAPED_SLASHES),$subtotal,$discount,$coupon?:null,$total]);$pdo->exec("INSERT IGNORE INTO cms_state(state_key,state_json,updated_by) VALUES('storybook-orders','[]',NULL)");$st=$pdo->query("SELECT state_json FROM cms_state WHERE state_key='storybook-orders' FOR UPDATE");$orders=json_decode((string)$st->fetchColumn(),true);$orders=is_array($orders)?$orders:[];array_unshift($orders,['id'=>$id,'createdAt'=>$now,'updatedAt'=>$now,'customerName'=>$customer,'address'=>$address,'phone'=>$phone,'email'=>$email,'babyName'=>$name,'babyAge'=>$age,'babyGender'=>$gender,'language'=>$bookLanguage,'babyPhoto'=>$babyPhoto,'extraPhotos'=>$extraPhotos,'total'=>$total,'advance'=>0,'theme'=>$product['theme'],'status'=>'placed','history'=>[['status'=>'placed','at'=>$now]],'cancelNote'=>'','source'=>'storefront','notes'=>$notes,'coupon'=>$coupon,'deliveryZone'=>$zone]);$up=$pdo->prepare("UPDATE cms_state SET state_json=?,updated_by=NULL WHERE state_key='storybook-orders'");$up->execute([json_encode($orders,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)]);$pdo->commit();$success=['id'=>$id,'total'=>$total,'name'=>$name,'product'=>$product['title']];meta_purchase($settings,['id'=>$id,'total'=>$total,'phone'=>$phone]);$mailProduct=$bookLanguage==='bn'&&!empty($product['title_bn'])?$product['title_bn']:$product['title'];try{notify_store_order($pdo,$settings,['id'=>$id,'product'=>$mailProduct,'customer'=>$customer,'phone'=>$phone,'email'=>$email,'address'=>$address,'zone'=>$zone,'delivery'=>$delivery,'character'=>$name,'age'=>$age,'gender'=>$gender,'book_language'=>$bookLanguage,'extra_photos'=>$extraPhotos,'notes'=>$notes,'total'=>$total],$bookLanguage);}catch(Throwable $mailError){}}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();$error=$e->getMessage();}
}
$products=$slug===''?$pdo->query('SELECT * FROM store_products WHERE active=1 ORDER BY sort_order,title')->fetchAll():[];$sliders=$slug===''?$pdo->query('SELECT * FROM store_sliders WHERE active=1 ORDER BY sort_order,id')->fetchAll():[];
$productTitle=$product&&$lang==='bn'&&$product['title_bn']?$product['title_bn']:($product['title']??'');$productSummary=$product&&$lang==='bn'&&$product['summary_bn']?$product['summary_bn']:($product['summary']??'');
$siteName=$settings['site_name']??'Personalized StoryBook by WindowMind';$seoTitle=$product?($productTitle.' — '.$siteName):($settings['seo_title']??($siteName.' Store'));$seoDescription=$product?$productSummary:($settings['seo_description']??'Personalized storybooks where your child becomes the hero.');$canonical=rtrim((string)($settings['canonical_url']??''),'/');$canonicalUrl=$canonical?($canonical.'/'.($product?'?book='.rawurlencode($product['slug']):'')):'';$ogImage=$product?($product['cover_image']??''):($settings['seo_og_image']??'');?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="<?=e($seoDescription)?>">
<?php if(!empty($settings['seo_keywords'])):?>
<meta name="keywords" content="<?=e($settings['seo_keywords'])?>">
<?php endif?>
<?php if(!empty($settings['facebook_domain_verification'])):?>
<meta name="facebook-domain-verification" content="<?=e($settings['facebook_domain_verification'])?>">
<?php endif?>
<?php if($canonicalUrl):?>
<link rel="canonical" href="<?=e($canonicalUrl)?>">
<?php endif?>
<meta property="og:title" content="<?=e($seoTitle)?>">
<meta property="og:description" content="<?=e($seoDescription)?>">
<meta property="og:type" content="<?=$product?'product':'website'?>">
<?php if($ogImage):?>
<meta property="og:image" content="<?=e($ogImage)?>">
<?php endif?>
<title>
<?=e($seoTitle)?>
</title>
<link rel="stylesheet" href="assets/store.css">
<?=pixel_head($pixel)?>
</head>
<body>
<div class="topbar">
<?=e($lang==='bn'?($settings['topbar_text_bn']??'আপনার শিশু। তার নিজের গল্প। তার অবিস্মরণীয় অভিযান।'):($settings['topbar_text']??'Your child. Their story. Their unforgettable adventure.'))?>
</div>
<header class="header">
<nav class="nav wrap">
<a class="logo" href="<?=e(store_link())?>">
<?php if(!empty($settings['site_logo'])):?>
<img src="<?=e($settings['site_logo'])?>" alt="<?=e($siteName)?>">
<span><?=e($siteName)?></span>
<?php else:?>
<?=e($siteName)?>
<?php endif?>
</a>
<div class="navlinks">
<a href="<?=e(store_link())?>#books"><?=tr('Books','বইসমূহ')?></a>
<a href="<?=e(store_link())?>#how"><?=tr('How it works','কীভাবে কাজ করে')?></a>
<div class="lang-switch"><a class="<?=$lang==='en'?'active':''?>" href="<?=e('index.php?'.http_build_query(array_filter(['book'=>$slug?:null,'checkout'=>$checkout?1:null,'lang'=>'en'])))?>">EN</a><a class="<?=$lang==='bn'?'active':''?>" href="<?=e('index.php?'.http_build_query(array_filter(['book'=>$slug?:null,'checkout'=>$checkout?1:null,'lang'=>'bn'])))?>">বাংলা</a></div>
<?php if($product&&!$checkout):?>
<a class="btn" href="<?=e(store_link(['book'=>$product['slug'],'checkout'=>1]))?>"><?=tr('Personalize & Order','পার্সোনালাইজ ও অর্ডার')?></a>
<?php endif?>
</div>
</nav>
</header>
<?php if($success):?>
<main class="success">
<div class="eyebrow"><?=tr('Order confirmed','অর্ডার নিশ্চিত হয়েছে')?></div>
<h1 class="section-title"><?=tr('Thank you','ধন্যবাদ')?>, <?=e($success['name'])?>!</h1>
<p><?=tr('Your personalized','আপনার ব্যক্তিগত')?> <b>
<?=e($success['product'])?>
</b> <?=tr('order has been received.','বইয়ের অর্ডার গ্রহণ করা হয়েছে।')?></p>
<p><?=tr('Order ID','অর্ডার আইডি')?>: <b>
<?=e($success['id'])?>
</b>
<br><?=tr('Total','মোট')?>: <b>
<?=money($success['total'])?>
</b>
</p>
<a class="btn green" href="<?=e(store_link())?>"><?=tr('Back to store','স্টোরে ফিরে যান')?></a>
</main>
<script>if(window.fbq)fbq('track','Purchase',{value:<?=json_encode($success['total'])?>,currency:'BDT'},{eventID:<?=json_encode($success['id'])?>});</script>
<?php elseif($checkout&&$product):?>
<main class="checkout">
<div class="eyebrow"><?=tr('Personalized order','ব্যক্তিগত বইয়ের অর্ডার')?></div>
<h1 class="section-title">
<?=e($productTitle)?>
</h1>
<?php if($error):?>
<div class="notice" style="background:#ffe8e8;color:#8a2525">
<?=e($error)?>
</div>
<?php endif?>
<div class="steps">
<div class="step on" id="step1Label"><?=tr('1. Order Information','১. অর্ডারের তথ্য')?></div>
<div class="step" id="step2Label"><?=tr('2. Personalize Book','২. বই ব্যক্তিগত করুন')?></div>
</div>
<form method="post" enctype="multipart/form-data" id="orderForm">
<input type="hidden" name="csrf" value="<?=e(csrf())?>">
<section class="panel" id="step1">
<div class="fields">
<div>
<label><?=tr('Customer name *','ক্রেতার নাম *')?></label>
<input name="customer_name" required value="<?=e($_POST['customer_name']??'')?>">
</div>
<div>
<label><?=tr('Phone number *','ফোন নম্বর *')?></label>
<input name="phone" required value="<?=e($_POST['phone']??'')?>">
</div>
<div>
<label><?=tr('Email address (optional)','ইমেইল ঠিকানা (ঐচ্ছিক)')?></label>
<input type="email" name="customer_email" value="<?=e($_POST['customer_email']??'')?>" placeholder="name@example.com">
</div>
<div class="field full">
<label><?=tr('Delivery address *','ডেলিভারি ঠিকানা *')?></label>
<textarea name="delivery_address" required>
<?=e($_POST['delivery_address']??'')?>
</textarea>
</div>
<div>
<label><?=tr('Delivery area *','ডেলিভারি এলাকা *')?></label>
<select name="delivery_zone" id="zone">
<option value="inside"><?=tr('Inside Dhaka','ঢাকার ভিতরে')?> — ৳80</option>
<option value="outside"><?=tr('Outside Dhaka','ঢাকার বাইরে')?> — ৳150</option>
</select>
</div>
<div>
<label><?=tr('Coupon code','কুপন কোড')?></label>
<input name="coupon_code" placeholder="Optional" value="<?=e($_POST['coupon_code']??'')?>">
</div>
<div class="field full">
<label><?=tr('Note','নোট')?></label>
<textarea name="notes" placeholder="Any special request">
<?=e($_POST['notes']??'')?>
</textarea>
</div>
</div>
<button type="button" class="btn green" style="margin-top:18px" onclick="goStep(2)"><?=tr('Continue to Personalize →','ব্যক্তিগত তথ্য দিন →')?></button>
</section>
<section class="panel" id="step2" style="display:none">
<div class="fields">
<div>
<label><?=tr('Character name *','চরিত্রের নাম *')?></label>
<input name="character_name" required value="<?=e($_POST['character_name']??'')?>">
</div>
<div>
<label><?=tr('Age *','বয়স *')?></label>
<input type="number" min="1" max="19" name="character_age" required value="<?=e($_POST['character_age']??'')?>">
</div>
<div>
<label><?=tr('Gender *','লিঙ্গ *')?></label>
<select name="character_gender">
<option value="girl"><?=tr('Girl','মেয়ে')?></option>
<option value="boy"><?=tr('Boy','ছেলে')?></option>
</select>
</div>
<div>
<label><?=tr('Book language *','বইয়ের ভাষা *')?></label>
<select name="book_language" required>
<option value="bn" <?=($_POST['book_language']??$lang)==='bn'?'selected':''?>>বাংলা</option>
<option value="en" <?=($_POST['book_language']??$lang)==='en'?'selected':''?>>English</option>
</select>
</div>
<div>
<label><?=tr('Selected story','নির্বাচিত গল্প')?></label>
<input disabled value="<?=e($productTitle)?>">
</div>
<div class="field full photo-upload-block">
<label><?=tr("Child's clear front-facing photo *","শিশুর সামনে থেকে তোলা পরিষ্কার ছবি *")?></label>
<div class="photo-guide"><strong><?=tr('Passport-style photo guideline','পাসপোর্ট ধরনের ছবির নির্দেশনা')?></strong><ul><li><?=tr('Face the camera directly; full face, eyes and hair must be visible.','সরাসরি ক্যামেরার দিকে তাকানো; পুরো মুখ, চোখ ও চুল স্পষ্ট থাকতে হবে।')?></li><li><?=tr('Use bright, even light and a simple background.','পর্যাপ্ত আলো ও সাধারণ পটভূমি ব্যবহার করুন।')?></li><li><?=tr('No sunglasses, mask, heavy shadow, filter or another person.','সানগ্লাস, মাস্ক, গাঢ় ছায়া, ফিল্টার বা অন্য ব্যক্তি থাকবে না।')?></li></ul></div>
<input type="file" name="baby_photo" id="babyPhoto" required accept="image/jpeg,image/png,image/webp" capture="user">
<div class="upload-preview" id="babyPhotoPreview"></div>
</div>
<div class="field full photo-upload-block">
<label><?=tr('Additional photos from phone (optional, maximum 5)','ফোন থেকে অতিরিক্ত ছবি (ঐচ্ছিক, সর্বোচ্চ ৫টি)')?></label>
<input type="file" name="extra_photos[]" id="extraPhotos" multiple accept="image/jpeg,image/png,image/webp">
<p class="summary"><?=tr('You can select several photos together. JPG, PNG or WebP; maximum 15 MB per photo.','একসঙ্গে একাধিক ছবি নির্বাচন করা যাবে। JPG, PNG বা WebP; প্রতিটি ছবি সর্বোচ্চ ১৫ MB।')?></p>
<div class="upload-preview multi" id="extraPhotoPreview"></div>
</div>
</div>
<div class="totalbox">
<div><?=tr('Book price','বইয়ের মূল্য')?>: <b>
<?=money($product['price'])?>
</b>
</div>
<div><?=tr('Delivery','ডেলিভারি')?>: <b id="deliveryText">৳80</b>
</div>
<div><?=tr('Coupon discount will be verified when placing the order.','অর্ডার দেওয়ার সময় কুপন ছাড় যাচাই হবে।')?></div>
<div style="font-size:20px"><?=tr('Total before coupon','কুপনের আগে মোট')?>: <b id="totalText">
<?=money((float)$product['price']+80)?>
</b>
</div>
</div>
<div class="actions" style="margin-top:18px">
<button type="button" class="btn outline" onclick="goStep(1)">← <?=tr('Back','ফিরে যান')?></button>
<button class="btn"><?=tr('Place Order','অর্ডার করুন')?></button>
</div>
</section>
</form>
</main>
<script>if(window.fbq)fbq('track','InitiateCheckout',{value:<?=json_encode((float)$product['price'])?>,currency:'BDT'});const zone=document.getElementById('zone');zone.onchange=cost;function cost(){let d=zone.value==='outside'?150:80;document.getElementById('deliveryText').textContent='৳'+d;document.getElementById('totalText').textContent='৳'+(<?=json_encode((float)$product['price'])?>+d).toLocaleString()}function goStep(n){if(n===2){for(const el of document.querySelectorAll('#step1 [required]'))if(!el.reportValidity())return}document.getElementById('step1').style.display=n===1?'block':'none';document.getElementById('step2').style.display=n===2?'block':'none';document.getElementById('step1Label').classList.toggle('on',n===1);document.getElementById('step2Label').classList.toggle('on',n===2);scrollTo({top:0,behavior:'smooth'})}</script>
<script>(()=>{const one=document.getElementById('babyPhoto'),many=document.getElementById('extraPhotos'),oneBox=document.getElementById('babyPhotoPreview'),manyBox=document.getElementById('extraPhotoPreview');const draw=(box,files)=>{box.innerHTML='';[...files].forEach(file=>{const img=document.createElement('img');img.alt=file.name;img.src=URL.createObjectURL(file);img.onload=()=>URL.revokeObjectURL(img.src);box.appendChild(img)})};one.addEventListener('change',()=>draw(oneBox,one.files));many.addEventListener('change',()=>{if(many.files.length>5){alert(<?=json_encode(tr('Please select a maximum of 5 additional photos.','সর্বোচ্চ ৫টি অতিরিক্ত ছবি নির্বাচন করুন।'))?>);many.value='';manyBox.innerHTML='';return}draw(manyBox,many.files)})})();</script>
<?php elseif($product):$gallery=array_values(array_filter(array_merge([$product['cover_image']],json_decode((string)$product['gallery_json'],true)?:[])));?>
<main>
<section class="wrap detail">
<div>
<div class="gallery-main" id="mainImage">
<?php if($gallery):?>
<img src="<?=e($gallery[0])?>" alt="<?=e($product['title'])?>">
<?php else:?>
<div class="cover-placeholder"><img src="assets/brand-logo.jpg" alt="<?=e($siteName)?>"><span><?=tr('Cover image coming soon','কভার ছবি শিগগিরই আসছে')?></span></div>
<?php endif?>
</div>
<div class="thumbs">
<?php foreach($gallery as $i=>$img):?>
<button class="thumb <?=$i===0?'active':''?>" data-img="<?=e($img)?>">
<img src="<?=e($img)?>" alt="">
</button>
<?php endforeach?>
</div>
</div>
<div>
<div class="eyebrow"><?=tr('Personalized adventure','ব্যক্তিগত গল্পের অভিযান')?></div>
<h1>
<?=e($productTitle)?>
</h1>
<p class="summary">
<?=nl2br(e($productSummary))?>
</p>
<div class="price">
<?=money($product['price'])?>
</div>
<div class="facts">
<div class="fact">
<b><?=tr('16 Pages','১৬ পৃষ্ঠা')?></b>
<br><?=tr('Full-colour story','সম্পূর্ণ রঙিন গল্প')?></div>
<div class="fact">
<b><?=tr('Personalized','ব্যক্তিগতকৃত')?></b>
<br><?=tr('Name, age & gender','নাম, বয়স ও লিঙ্গ')?></div>
<div class="fact">
<b><?=tr('Preview','প্রিভিউ')?></b>
<br><?=tr('Before printing','প্রিন্টের আগে')?></div>
</div>
<div class="actions">
<a class="btn" href="<?=e(store_link(['book'=>$product['slug'],'checkout'=>1]))?>"><?=tr('Personalize & Order','পার্সোনালাইজ ও অর্ডার')?></a>
<a class="btn outline" href="#story"><?=tr('Read full story','সম্পূর্ণ গল্প পড়ুন')?></a>
</div>
</div>
</section>
<section class="reader" id="story">
<div class="wrap">
<div style="text-align:center;margin-bottom:25px">
<div class="eyebrow"><?=tr('Full storyline preview','সম্পূর্ণ গল্পের প্রিভিউ')?></div>
<h2 class="section-title"><?=tr('Read the complete story','সম্পূর্ণ গল্প পড়ুন')?></h2>
<p class="section-sub"><?=tr("Read all 16 pages as simple text. The finished book will use your child's name, age, gender and images.",'সাধারণ লেখায় ১৬টি পৃষ্ঠার গল্প পড়ুন। তৈরি বইয়ে আপনার শিশুর নাম, বয়স, লিঙ্গ ও ছবি ব্যবহার হবে।')?></p>
<div class="actions" style="justify-content:center">
<button class="btn" id="readEnglish">English</button>
<button class="btn outline" id="readBangla">বাংলা</button>
</div>
</div>
<div class="story-text-list" id="storyTextList"></div>
<article id="storyPage" hidden></article>
<div class="reader-controls" hidden>
<button id="storyPrev">← Previous</button>
<span id="storyCount">
</span>
<button id="storyNext">Next →</button>
</div>
</div>
</section>
</main>
<script src="assets/story-engine-v3.3.js">
</script>
<script src="assets/story-engine-v3.4-additions.js">
</script>
<script>if(window.fbq)fbq('track','ViewContent',{content_name:<?=json_encode($product['title'])?>,value:<?=json_encode((float)$product['price'])?>,currency:'BDT'});const imgs=[...document.querySelectorAll('.thumb')],main=document.querySelector('#mainImage img');let gi=0;function showImg(i){if(!imgs.length||!main)return;gi=(i+imgs.length)%imgs.length;main.src=imgs[gi].dataset.img;imgs.forEach((x,j)=>x.classList.toggle('active',j===gi))}imgs.forEach((x,i)=>x.onclick=()=>showImg(i));if(imgs.length>1)setInterval(()=>showImg(gi+1),3500);let language='en',pages=window.StoryEngine.storyPages(<?=json_encode($product['theme'])?>,language),at=0;const prev=document.getElementById('storyPrev'),next=document.getElementById('storyNext'),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));function story(){let p=pages[at];document.getElementById('storyPage').innerHTML=`<div class="storybox">
<h3>${esc(p[0])}</h3>
<p>${esc(p[1]).replaceAll('{name}',language==='bn'?'আপনার শিশু':'Your Child').replaceAll('{age}',language==='bn'?'তার বয়স':'their age')}</p>
</div>`;document.getElementById('storyCount').textContent=`${language==='bn'?'পৃষ্ঠা':'Page'} ${at+1} / ${pages.length}`;prev.disabled=at===0;next.disabled=at===pages.length-1}function setLanguage(l){language=l;pages=window.StoryEngine.storyPages(<?=json_encode($product['theme'])?>,l);at=0;readEnglish.className=l==='en'?'btn':'btn outline';readBangla.className=l==='bn'?'btn':'btn outline';story()}prev.onclick=()=>{if(at){at--;story()}};next.onclick=()=>{if(at<pages.length-1){at++;story()}};readEnglish.onclick=()=>setLanguage('en');readBangla.onclick=()=>setLanguage('bn');story();</script>
<script>(()=>{const box=document.getElementById('storyTextList');const render=l=>{const rows=window.StoryEngine.storyPages(<?=json_encode($product['theme'])?>,l);box.innerHTML=rows.map((p,i)=>`<article class="story-text-page"><span>${l==='bn'?'পৃষ্ঠা':'Page'} ${i+1}</span><h3>${esc(p[0])}</h3><p>${esc(p[1]).replaceAll('{name}',l==='bn'?'আপনার শিশু':'Your Child').replaceAll('{age}',l==='bn'?'শিশুর বয়স':'the child’s age')}</p></article>`).join('');readEnglish.className=l==='en'?'btn':'btn outline';readBangla.className=l==='bn'?'btn':'btn outline'};readEnglish.onclick=()=>render('en');readBangla.onclick=()=>render('bn');render(<?=json_encode($lang)?>)})();</script>
<?php else:?>
<main>
<?php if($sliders):?>
<section class="home-slider" id="homeSlider">
<?php foreach($sliders as $i=>$slide):?>
<article class="home-slide <?=$i===0?'active':''?>">
<picture><?php if($slide['mobile_image']):?><source media="(max-width:600px)" srcset="<?=e($slide['mobile_image'])?>"><?php endif?><img src="<?=e($slide['desktop_image'])?>" alt="<?=e($slide['title'])?>"></picture>
<?php if($slide['title']||$slide['subtitle']||$slide['button_text']):?><div class="slide-shade"></div><div class="slide-content wrap"><?php if($slide['title']):?><h1><?=e($slide['title'])?></h1><?php endif?><?php if($slide['subtitle']):?><p><?=e($slide['subtitle'])?></p><?php endif?><?php if($slide['button_text']):?><a class="btn" href="<?=e($slide['button_url']?:'#books')?>"><?=e($slide['button_text'])?></a><?php endif?></div><?php endif?>
</article>
<?php endforeach?>
<div class="slider-dots"><?php foreach($sliders as $i=>$slide):?><button type="button" aria-label="Slide <?=$i+1?>" data-slide="<?=$i?>" class="<?=$i===0?'active':''?>"></button><?php endforeach?></div>
</section>
<?php else:?>
<section class="hero">
<div class="wrap hero-grid">
<div>
<div class="eyebrow"><?=tr('A book unlike any other','অন্য সব বইয়ের চেয়ে আলাদা')?></div>
<h1><?=tr('Your child becomes the hero.','আপনার শিশুই হবে গল্পের নায়ক।')?></h1>
<p><?=tr("Choose an adventure and personalize it with your child's name, age and gender. We turn their imagination into a keepsake they will want to read again and again.",'একটি অভিযান বেছে নিয়ে শিশুর নাম, বয়স ও লিঙ্গ দিয়ে ব্যক্তিগত করুন। তার কল্পনাকে আমরা এমন একটি স্মৃতির বইয়ে রূপ দেব, যা সে বারবার পড়তে চাইবে।')?></p>
<a class="btn" href="#books"><?=tr('Explore storybooks','গল্পের বই দেখুন')?></a>
</div>
<div class="hero-card">
<?php $hero=$products[0]['cover_image']??'';if($hero):?>
<img src="<?=e($hero)?>" alt="Personalized storybook">
<?php endif?>
</div>
</div>
</section>
<?php endif?>
<section class="section wrap" id="books">
<div class="catalog-heading"><div><div class="eyebrow"><?=tr('50 ready story themes','৫০টি প্রস্তুত গল্প')?></div><h2 class="section-title"><?=tr('Choose their next adventure','শিশুর পরবর্তী অভিযান বেছে নিন')?></h2><p class="section-sub"><?=tr('See the summary and read the complete story before ordering.','অর্ডারের আগে সারাংশ ও সম্পূর্ণ গল্প পড়ে দেখুন।')?></p></div><span class="catalog-count">50 <?=tr('books','টি বই')?></span></div>
<div class="grid">
<?php foreach($products as $p):?>
<article class="product">
<a class="product-img" href="<?=e(store_link(['book'=>$p['slug']]))?>">
<?php if($p['cover_image']):?>
<img src="<?=e($p['cover_image'])?>" alt="<?=e($p['title'])?>">
<?php else:?>
<div class="cover-placeholder"><img src="assets/brand-logo.jpg" alt=""><span><?=tr('Upload cover from Admin','Admin থেকে cover দিন')?></span></div>
<?php endif?>
</a>
<div class="product-body">
<h3>
<?=e($lang==='bn'&&$p['title_bn']?$p['title_bn']:$p['title'])?>
</h3>
<p class="summary">
<?php $ps=$lang==='bn'&&$p['summary_bn']?$p['summary_bn']:$p['summary'];?><?=e(short_text($ps))?>
</p>
<div class="price">
<?=money($p['price'])?>
</div>
<div class="actions">
<a class="btn outline" href="<?=e(store_link(['book'=>$p['slug']]))?>"><?=tr('View book','বইটি দেখুন')?></a>
<a class="btn" href="<?=e(store_link(['book'=>$p['slug'],'checkout'=>1]))?>"><?=tr('Order now','অর্ডার করুন')?></a>
</div>
</div>
</article>
<?php endforeach?>
</div>
</section>
<section class="section" id="how" style="background:#eee5da">
<div class="wrap">
<h2 class="section-title"><?=tr('How it works','কীভাবে কাজ করে')?></h2>
<div class="grid">
<div class="panel">
<b><?=tr('1. Choose a story','১. গল্প বেছে নিন')?></b>
<p class="summary"><?=tr('Read the full storyline and select the perfect adventure.','সম্পূর্ণ গল্প পড়ে পছন্দের অভিযান বেছে নিন।')?></p>
</div>
<div class="panel">
<b><?=tr('2. Personalize it','২. ব্যক্তিগত তথ্য দিন')?></b>
<p class="summary"><?=tr('Add character name, age, gender and delivery information.','চরিত্রের নাম, বয়স, লিঙ্গ ও ডেলিভারি তথ্য দিন।')?></p>
</div>
<div class="panel">
<b><?=tr('3. Approve & receive','৩. দেখে অনুমোদন করুন')?></b>
<p class="summary"><?=tr('Review the personalized book before it goes to print.','প্রিন্টের আগে ব্যক্তিগত বইটির প্রিভিউ দেখে অনুমোদন করুন।')?></p>
</div>
</div>
</div>
</section>
</main>
<?php endif?>
<footer class="footer">
<div class="wrap">© <?=date('Y')?> <?=e($siteName)?></div>
</footer>
<?php $wa=preg_replace('/\D+/','',(string)($settings['whatsapp_number']??''));$messenger=trim((string)($settings['messenger_url']??''));if($wa||$messenger):?><div class="floating-social"><?php if($messenger):?><a class="social messenger" href="<?=e($messenger)?>" target="_blank" rel="noopener" aria-label="Facebook Messenger">m</a><?php endif?><?php if($wa):?><a class="social whatsapp" href="https://wa.me/<?=e($wa)?>" target="_blank" rel="noopener" aria-label="WhatsApp">☎</a><?php endif?></div><?php endif?>
<script>(()=>{const slides=[...document.querySelectorAll('.home-slide')],dots=[...document.querySelectorAll('.slider-dots button')];if(slides.length<2)return;let at=0;const show=i=>{at=(i+slides.length)%slides.length;slides.forEach((s,n)=>s.classList.toggle('active',n===at));dots.forEach((d,n)=>d.classList.toggle('active',n===at))};dots.forEach((d,i)=>d.onclick=()=>show(i));setInterval(()=>show(at+1),5000)})();</script>
</body>
</html>
