<?php

// v2: GitHub private configuration is optional on legacy GoDaddy hosting.
if (is_file(__DIR__ . '/private-config.php')) {
 require_once __DIR__ . '/private-config.php';
}
require_once __DIR__.'/hosting-images.php'; // photos GoDaddy hosting se (Google Drive ki jagah)
// FIX 04-Oct: server ki hosting-images.php purani ho aur usme premImgShareUrl() na ho, to page beech me ruk jata tha.
// Ab function na mile to yahin se photo ka poora (https://...) link ban jata hai.
if(!function_exists('premImgShareUrl')){
 function premImgShareUrl($id,$w=900){
  $u=function_exists('premImgUrl')?(string)premImgUrl($id,$w):'';
  if($u==='')return '';
  if(preg_match('~^https?://~i',$u))return $u;
  if(strpos($u,'//')===0)return 'https:'.$u;
  $https=(!empty($_SERVER['HTTPS'])&&strtolower((string)$_SERVER['HTTPS'])!=='off')||(strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO']??''))==='https');
  $host=(string)($_SERVER['HTTP_HOST']??'www.premkurti.com');
  $base=($https?'https':'http').'://'.$host;
  if($u[0]==='/')return $base.$u;
  $dir=rtrim(str_replace('\\','/',dirname((string)($_SERVER['SCRIPT_NAME']??'/index.php'))),'/');
  return $base.$dir.'/'.$u;
 }
}
// PREM KURTIS - Image Bulk Order Catalogue
// Photos hosting ke "images" folder se aati hain (chhoti photos: image-thumbs, image-cache.php).
// images folder khali ho to pehle ki tarah Google Drive se. Check page: image-check.php
if(isset($_GET['img_thumb'])){http_response_code(404);exit;} // purana thumbnail link, ab use nahi hota
// Category-wise manual sorting: Women Kurtis and Two Pc Sets keep independent positions.
session_start();
header('Cache-Control: private, max-age=30, stale-while-revalidate=60');
require __DIR__.'/order-config.php';
require_once __DIR__.'/customer-salesman-lib.php';
if(empty($_SESSION['customer_lookup_token'])) $_SESSION['customer_lookup_token']=bin2hex(random_bytes(24));
$savedCustomer=!empty($_SESSION['customer'])?$_SESSION['customer']:array();
require_once __DIR__.'/customer-intl-lib.php';
function pkIntlShowOrSame($m){try{$v=pkIntlShow(orderDb(),$m);return $v!==''?$v:$m;}catch(Throwable $e){return $m;}}
$driveFolderId='1Fch6OWEPJ0WnZZSVpFgz-T-DSR5IFKkO';
// Hosting images do not require a Google API key. Keep Drive fallback optional.
$googleApiKey=(string)(getenv('GOOGLE_API_KEY') ?: '');
if(function_exists('pkRequiredEnv')){
 try{$googleApiKey=pkRequiredEnv('GOOGLE_API_KEY');}
 catch(RuntimeException $e){$googleApiKey='';}
}
$allowed=array('jpg','jpeg','png','webp','gif','avif');
$sizes=array('M','L','XL','XXL','3XL','4XL');
// Customer Details ka "Salesman" box. Salesman ki list customer-salesman-lib.php me hai.
// Customer pehli baar jo salesman chunta hai wahi fix ho jata hai; badalna sirf admin kar sakta hai.
$salesmanChoices=pkSalesmanList();
function h($s){return htmlspecialchars($s,ENT_QUOTES,'UTF-8');}
function pkIsPkDesign($d){return stripos(ltrim((string)$d),'PK')===0;}
function pkSizeRate($s){return in_array($s,array('3XL','4XL'),true)?650:(in_array($s,array('XL','XXL'),true)?550:450);}
function pkCategoryOf($d){$d=ltrim((string)$d);if(stripos($d,'PK')===0)return 'pk';if(stripos($d,'PG')===0)return 'two-piece';if(stripos($d,'K')===0)return 'kurti';return 'other';}
function displayDesign($s){return trim((string)preg_replace('/\s+NA\b.*$/iu','',(string)$s));}
function driveImageUrl($id){return 'https://drive.google.com/thumbnail?id='.rawurlencode($id).'&sz=w900';} // sirf un photos ke liye jo hosting par nahi hain
function catalogueImageUrl($name,$id){return premImgUrl($id,900);}
// ---- SPEED: display-size images ----
function premThumbWidth(){return 600;}
function catalogueDisplayUrl($name,$id){return premImgUrl($id,premThumbWidth());}
function productImageDownloadUrl($id,$design){$script=basename((string)($_SERVER['SCRIPT_NAME']??'index.php'));return $script.'?download_product_image='.rawurlencode((string)$id).'&name='.rawurlencode((string)$design);}
function safeProductImageFilename($name){$name=displayDesign((string)preg_replace('/\.(jpe?g|png|webp|gif|avif)$/i','',(string)$name));$name=preg_replace('/[^A-Za-z0-9_-]+/','-',$name);$name=trim((string)$name,'-');return ($name!==''?$name:'product-image').'.jpg';}
function outputProductImageDownload($id,$name){
 $id=preg_replace('/[^A-Za-z0-9_-]/','',(string)$id);
 if($id===''){http_response_code(400);exit('Image ID missing.');}
 premHostDownload($id,safeProductImageFilename($name),900); // hosting wali photo (ho to) yahin se download
 $url=driveImageUrl($id);
 $data=false;$type='image/jpeg';
 {
  if(function_exists('curl_init')){
   $c=curl_init($url);curl_setopt($c,CURLOPT_RETURNTRANSFER,true);curl_setopt($c,CURLOPT_FOLLOWLOCATION,true);curl_setopt($c,CURLOPT_CONNECTTIMEOUT,8);curl_setopt($c,CURLOPT_TIMEOUT,30);$data=curl_exec($c);$ct=(string)curl_getinfo($c,CURLINFO_CONTENT_TYPE);if($ct!=='')$type=$ct;curl_close($c);
  }elseif(ini_get('allow_url_fopen')){$data=@file_get_contents($url);}
 }
 if($data===false||$data===''){header('Location: '.$url);exit;}
 header('Content-Type: '.$type);header('Content-Disposition: attachment; filename="'.safeProductImageFilename($name).'"');header('Content-Length: '.strlen($data));echo $data;exit;
}
if(isset($_GET['download_product_image'])) outputProductImageDownload((string)$_GET['download_product_image'],(string)($_GET['name']??'product-image'));
function isNaAll($n){return preg_match('/(?:^|[\s_-])NA\s*[:=_-]?\s*ALL\s*$/i',pathinfo($n,PATHINFO_FILENAME))===1;}
function naSizes($n,$sizes){
 $out=array(); $base=pathinfo($n,PATHINFO_FILENAME);
 if(preg_match('/(?:^|[\s_-])NA\s*[:=_-]?\s*(.+)$/i',$base,$m)){
  foreach($sizes as $s) if(preg_match('/(?<![A-Z0-9])'.preg_quote($s,'/').'(?![A-Z0-9])/i',$m[1])) $out[]=$s;
 }
 return $out;
}
function driveFiles($folder,$key,&$apiError){
 require_once __DIR__.'/drive-cache.php';
 $apiError='';
 // SPEED: ab catalogue photos hosting par hain. Normal page load par Google Drive API
 // wait nahi karega. Agar kabhi Drive fallback chahiye ho to ?use_drive=1 lagaye.
 if(function_exists('premHostHasImages')&&premHostHasImages($folder)&&empty($_GET['use_drive'])){
  return premHostFiles($folder);
 }
 $cached=premDriveFilesCached((string)$folder,(string)$key,$apiError);
 if(is_array($cached)&&count($cached))return premHostMergeFiles((string)$folder,$cached);
 $cacheError=$apiError;
 $apiError='';
 $q="'".$folder."' in parents and trashed=false";
 $url='https://www.googleapis.com/drive/v3/files?q='.rawurlencode($q).'&fields='.rawurlencode('files(id,name,mimeType)').'&pageSize=1000&key='.rawurlencode($key);
 $json=false;
 if(function_exists('curl_init')){
   $c=curl_init($url);
   curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
   curl_setopt($c,CURLOPT_CONNECTTIMEOUT,8);
   curl_setopt($c,CURLOPT_TIMEOUT,20);
   curl_setopt($c,CURLOPT_SSL_VERIFYPEER,true);
   $json=curl_exec($c);
   if($json===false) $apiError='Server cURL error: '.curl_error($c);
   curl_close($c);
 } elseif(ini_get('allow_url_fopen')){
   $json=@file_get_contents($url);
   if($json===false) $apiError='Server could not connect to Google Drive API.';
 } else {
   $apiError='Server has neither cURL nor allow_url_fopen enabled.';
 }
 if(!$json) return array();
 $d=json_decode($json,true);
 if(isset($d['error']['message'])) {$apiError=$d['error']['message']; return array();}
 if(!isset($d['files'])) {$apiError='Google Drive API returned an unexpected response.'; return array();}
 if(!count($d['files'])&&$cacheError!=='')$apiError=$cacheError;
 return premHostMergeFiles((string)$folder,$d['files']);
}
function productSortRows(){
 $path=__DIR__.'/product-sorting.json';
 if(is_file($path)){$rows=json_decode((string)@file_get_contents($path),true);if(is_array($rows))return $rows;}
 try{$pdo=orderDb();$rows=array();foreach($pdo->query('SELECT file_id,sort_order,is_pinned FROM product_display_order')->fetchAll() as $r)$rows[$r['file_id']]=$r;return $rows;}catch(Throwable $e){return array();}
}
require_once __DIR__.'/godown-availability.php';
// SPEED: Drive list + godown stock + sorting is cached for 60 seconds.
// Stock/sorting changes show on the site within 1 minute. Add ?refresh=1 to rebuild now.
$catalogueCacheFile=__DIR__.'/catalogue-cache/items-v2.json';
$catalogueCacheTtl=60;
$items=array(); $driveError=''; $cachedItems=null;
if(empty($_GET['refresh'])&&is_file($catalogueCacheFile)&&(time()-(int)@filemtime($catalogueCacheFile))<$catalogueCacheTtl){
 $cachedItems=json_decode((string)@file_get_contents($catalogueCacheFile),true);
}
// SPEED: cache purana ho jaye to sirf ek visitor list dobara banata hai; baaki sab ko purani list turant mil jati hai (sab ek saath rebuild nahi karte).
$premLock=null;
if(!(is_array($cachedItems)&&count($cachedItems))&&empty($_GET['refresh'])&&is_file($catalogueCacheFile)){
 $premLock=@fopen($catalogueCacheFile.'.lock','c');
 if($premLock&&!@flock($premLock,LOCK_EX|LOCK_NB)){
  $staleItems=json_decode((string)@file_get_contents($catalogueCacheFile),true);
  if(is_array($staleItems)&&count($staleItems))$cachedItems=$staleItems;
 }
}
if(is_array($cachedItems)&&count($cachedItems)){
 $items=$cachedItems;
}else{
try{$godownRows=pgGodownRows();}catch(Throwable $e){http_response_code(503);exit('Availability data unavailable. Please contact admin.');}
$productSort=productSortRows();
$premHasHostingImages=function_exists('premHostHasImages') && premHostHasImages($driveFolderId) && empty($_GET['use_drive']);
if(!$premHasHostingImages && (trim($googleApiKey)==='' || strpos($googleApiKey,'PASTE_')===0)) $driveError='Server images are unavailable. Please check the images folder.';
else{
 $apiError='';
 $driveList=driveFiles($driveFolderId,$googleApiKey,$apiError);
 $godownRows=pgSharedRows($godownRows,$driveList);
 if($apiError!=='') $driveError=$apiError;
 foreach($driveList as $f){
  if(!isset($f['id'],$f['name']))continue;
  if(preg_match('/^DELETED\s/i',$f['name']))continue; // hatayi gayi photos par stock/size ka kaam bekar
  $ext=strtolower(pathinfo($f['name'],PATHINFO_EXTENSION));
  if(!in_array($ext,$allowed,true))continue;
   $visibleSizes=pgVisibleSizes($godownRows,$f['id'],$f['name'],$sizes,false);
   if(!count($visibleSizes))continue;
   $naForCustomer=array_values(array_diff($sizes,array_keys($visibleSizes)));
  $s=isset($productSort[$f['id']])?$productSort[$f['id']]:array('sort_order'=>0,'is_pinned'=>0);
  $category=pkIsPkDesign(pathinfo($f['name'],PATHINFO_FILENAME))?'pk':(stripos(pathinfo($f['name'],PATHINFO_FILENAME),'PG')===0?'two-piece':'kurti');
  $items[]=array('file_id'=>$f['id'],'design'=>pathinfo($f['name'],PATHINFO_FILENAME),'filename'=>$f['name'],'category'=>$category,'url'=>catalogueDisplayUrl($f['name'],$f['id']),'display'=>catalogueDisplayUrl($f['name'],$f['id']),'na'=>$naForCustomer,'sort_order'=>(int)$s['sort_order'],'is_pinned'=>(int)$s['is_pinned']);
 }
 usort($items,function($x,$y){
  if($x['category']!==$y['category']){$rank=array('kurti'=>1,'two-piece'=>2,'pk'=>3);return (isset($rank[$x['category']])?$rank[$x['category']]:99)<=>(isset($rank[$y['category']])?$rank[$y['category']]:99);}
  if($x['is_pinned']!==$y['is_pinned'])return $y['is_pinned']<=>$x['is_pinned'];
  if($x['sort_order']>0&&$y['sort_order']>0&&$x['sort_order']!==$y['sort_order'])return $x['sort_order']<=>$y['sort_order'];
  if($x['sort_order']>0&&$y['sort_order']<=0)return -1;
  if($x['sort_order']<=0&&$y['sort_order']>0)return 1;
  return strnatcasecmp($x['filename'],$y['filename']);
 });
}
if($driveError===''&&count($items)){
 $cacheDir=dirname($catalogueCacheFile);
 if(!is_dir($cacheDir))@mkdir($cacheDir,0755,true);
 $tmpCache=$catalogueCacheFile.'.tmp-'.mt_rand(1000,999999);
 if(@file_put_contents($tmpCache,json_encode($items))!==false)@rename($tmpCache,$catalogueCacheFile);
 if(is_file($tmpCache))@unlink($tmpCache);
}
}
$kurtiThumb='';$pgThumb='';$pkThumb='';$pkBest='';$pkCount=0;
foreach($items as $item){
 $isPkItem=pkIsPkDesign($item['design']);
 if(!$isPkItem&&$item['category']==='kurti'&&$kurtiThumb==='')$kurtiThumb=$item['display'];
 if(!$isPkItem&&$item['category']==='two-piece'&&$pgThumb==='')$pgThumb=$item['display'];
 if($isPkItem){$pkCount++;if($pkBest===''||strnatcasecmp((string)$item['design'],$pkBest)>0){$pkBest=(string)$item['design'];$pkThumb=$item['display'];}}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php if(isset($items[0]['display'])&&strpos((string)$items[0]['display'],'https://drive.google.com')===0): ?>
<link rel="preconnect" href="https://drive.google.com">
<link rel="preconnect" href="https://lh3.googleusercontent.com">
<?php endif; ?>
<title>PREM KURTIS ORDER CATALOGUE</title>
<meta name="description" content="Prem Garments Pvt. Ltd. — Manufacturers of Ladies Kurtis &amp; Short Tops. View our latest Prem Kurtis catalogue and place your order online.">

<!-- WhatsApp / Facebook link preview -->
<meta property="og:type" content="website">
<meta property="og:site_name" content="Prem Garments Pvt. Ltd.">
<meta property="og:title" content="Prem Garments Pvt. Ltd. | Prem Kurtis">
<meta property="og:description" content="Manufacturers of Ladies Kurtis &amp; Short Tops. View our latest catalogue and place your order online.">
<meta property="og:url" content="https://www.premgarments.net/">
<meta property="og:image" content="https://www.premgarments.net/visitingcard.jpg">
<meta property="og:image:secure_url" content="https://www.premgarments.net/visitingcard.jpg">
<meta property="og:image:type" content="image/jpeg">
<meta property="og:image:width" content="1635">
<meta property="og:image:height" content="962">
<meta property="og:image:alt" content="Prem Garments Pvt. Ltd. visiting card">

<!-- X / Twitter link preview -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Prem Garments Pvt. Ltd. | Prem Kurtis">
<meta name="twitter:description" content="Manufacturers of Ladies Kurtis &amp; Short Tops. View our latest catalogue and place your order online.">
<meta name="twitter:image" content="https://www.premgarments.net/visitingcard.jpg">
<link rel="stylesheet" href="prem-index-1.css?v=<?php echo (int)@filemtime(__DIR__.'/prem-index-1.css'); ?>">
<link rel="stylesheet" href="prem-theme.css?v=20260922">
<link rel="stylesheet" href="prem-index-2.css?v=<?php echo (int)@filemtime(__DIR__.'/prem-index-2.css'); ?>">
<style id="prem-left-ad-v7">
/* v6: large, continuous left-moving wording between 2 Pc and Videos. */
header .quickBar{flex-wrap:nowrap!important}
header .quickBar .categoryNav{flex:0 0 auto!important;min-width:0;justify-content:flex-start!important}
header .quickBar .premLeftAd{display:flex;align-items:center;flex:1 1 0;min-width:0;align-self:stretch;margin:0 2px;overflow:hidden;border-radius:10px;background:linear-gradient(115deg,#234451,#365d69);border:1px solid #d4b97a;color:#f4d89d;text-decoration:none;line-height:1.2}
header .quickBar .premLeftWindow{display:block;overflow:hidden;width:100%;min-width:0;padding:12px 0}
header .quickBar .premLeftTrack{display:flex;width:max-content;white-space:nowrap;will-change:transform;animation:premLeftAdRoll 105s linear infinite}
header .quickBar .premLeftCopy{display:block;flex:0 0 auto;padding-right:60px;font-size:clamp(26px,2.3vw,36px);font-weight:900;letter-spacing:.2px;line-height:1.2}
header .quickBar .videoTile{flex:0 0 auto!important;margin-left:auto!important}
header .quickBar .premLeftAd:focus-visible{outline:3px solid #f4d89d;outline-offset:2px}
@keyframes premLeftAdRoll{from{transform:translateX(0)}to{transform:translateX(-50%)}}
@media(max-width:650px){header .quickBar .premLeftAd{border-radius:7px;margin:0 1px}header .quickBar .premLeftWindow{padding:10px 0}header .quickBar .premLeftCopy{font-size:22px;padding-right:40px}}
@media(prefers-reduced-motion:reduce){header .quickBar .premLeftTrack{animation:none;transform:none}header .quickBar .premLeftWindow{overflow-x:auto}}
@media print{header .quickBar .premLeftAd{display:none}}

/* v7: mobile-only compact tiles, matching the animated ad height. */
@media(max-width:650px){
 header .quickBar{gap:4px!important;padding:6px!important;align-items:center!important}
 header .quickBar .categoryNav{gap:4px!important;align-items:center!important}
 header .quickBar .categoryBtn,header .quickBar .videoTile{width:38px!important;height:44px!important;min-width:38px!important;max-width:38px!important;min-height:44px!important;padding:2px!important;border-radius:7px!important;flex:0 0 38px!important;overflow:hidden!important;box-sizing:border-box}
 header .quickBar .categoryBtn img,header .quickBar .videoTile img{width:32px!important;height:38px!important;flex:0 0 32px!important;object-fit:cover!important;border-radius:4px!important}
 header .quickBar .categoryBtn .tileLabel,header .quickBar .videoTile .tileLabel{left:2px!important;right:2px!important;bottom:2px!important;height:13px!important;line-height:13px!important;font-size:8px!important;border-radius:0 0 4px 4px!important}
 header .quickBar .videoTile .playBadge{width:19px!important;height:19px!important;font-size:10px!important;top:42%!important}
 header .quickBar .premLeftAd{height:44px!important;min-height:44px!important;align-self:center!important;margin:0!important;max-width:none!important;box-sizing:border-box}
 header .quickBar .premLeftWindow{padding:0!important}
 header .quickBar .premLeftCopy{font-size:22px!important;line-height:1.2!important}
 header .quickBar .pkTileWrap{width:38px!important;flex:0 0 38px!important}
}
/* v8: Kurtis / Plazo Sets - do chaude button (photo + bada naam); Videos ka apna play icon (2 Pc ki photo nahi). */
header .quickBar .categoryBtn{flex:0 0 190px!important;width:190px!important;max-width:none!important;min-width:0!important;height:50px!important;min-height:50px!important;flex-direction:row!important;justify-content:flex-start!important;gap:8px!important;padding:4px 10px 4px 5px!important;border-radius:14px!important;text-align:left!important}
header .quickBar .categoryBtn img{width:40px!important;height:40px!important;flex:0 0 40px!important;border-radius:9px!important;object-fit:cover!important;object-position:top!important}
header .quickBar .categoryBtn .tileLabel{position:static!important;left:auto!important;right:auto!important;bottom:auto!important;height:auto!important;line-height:1.1!important;background:transparent!important;border-radius:0!important;font-size:15px!important;font-weight:900!important;text-transform:uppercase!important;letter-spacing:.3px!important;text-align:left!important;white-space:normal!important;text-shadow:none!important;flex:1 1 auto;color:#29465e!important}
header .quickBar .categoryBtn.active .tileLabel{background:transparent!important;color:#fff!important}
header .quickBar .categoryBtn.pkTile{flex:0 0 64px!important;width:64px!important;padding:4px 6px 4px 4px!important}
header .quickBar .categoryBtn.pkTile img{width:32px!important;height:32px!important;flex:0 0 32px!important}
header .quickBar .categoryBtn.pkTile .tileLabel{font-size:13px!important}
header .quickBar .pkTileWrap{flex:0 0 auto!important;width:auto!important}
header .quickBar .videoTile{width:62px!important;min-width:62px!important;max-width:62px!important;height:50px!important;min-height:50px!important;flex:0 0 62px!important;background:linear-gradient(135deg,#234451,#365d69)!important;border:1px solid #d4b97a!important;box-shadow:none!important;overflow:hidden!important}
header .quickBar .videoTile .playBadge{width:24px!important;height:24px!important;font-size:12px!important;top:40%!important}
header .quickBar .videoTile .tileLabel{background:transparent!important;color:#fff!important;text-shadow:none!important;font-size:10px!important;height:14px!important;line-height:14px!important;bottom:2px!important;left:0!important;right:0!important;border-radius:0!important}
@media(max-width:650px){
 header .quickBar{flex-wrap:nowrap!important}
 header .quickBar .categoryNav{flex:1 1 0!important;width:auto!important;min-width:0!important;gap:6px!important}
 header .quickBar .categoryBtn{flex:1 1 0!important;width:auto!important;height:48px!important;min-height:48px!important;padding:4px 8px 4px 4px!important}
 header .quickBar .categoryBtn img{width:38px!important;height:38px!important;flex:0 0 38px!important}
 header .quickBar .categoryBtn .tileLabel{font-size:14px!important}
 header .quickBar.hasPk .categoryBtn:not(.pkTile) .tileLabel{font-size:12.5px!important}
 header .quickBar .pkTileWrap{flex:0 0 58px!important;width:58px!important}
 header .quickBar .categoryBtn.pkTile{flex:0 0 100%!important;width:100%!important;padding:4px 5px 4px 3px!important;gap:4px!important}
 header .quickBar .categoryBtn.pkTile img{width:26px!important;height:26px!important;flex:0 0 26px!important}
 header .quickBar.hasPk .categoryBtn:not(.pkTile){padding-right:4px!important;gap:6px!important}
 header .quickBar.hasPk .categoryBtn:not(.pkTile) img{width:34px!important;height:34px!important;flex:0 0 34px!important}
 header .quickBar .videoTile{width:56px!important;min-width:56px!important;max-width:56px!important;height:44px!important;min-height:44px!important;flex:0 0 56px!important}
 header .quickBar .premLeftAd{flex:1 1 0!important}
}
</style>
</head>
<body>
<?php $cuBarMode='inline';$cuBarHtml='';if(is_file(__DIR__.'/customer-bar.php'))include __DIR__.'/customer-bar.php'; ?>

<style>.brokerLink{flex:0 0 auto;align-self:center;background:#fff;color:#8a5a00;border:1.5px solid #e0b24a;border-radius:9px;padding:5px 7px;margin-right:6px;font-weight:800;font-size:11px;text-decoration:none;line-height:1.1}</style><header>
<div class="head">
<div class="headRow">
<a class="brokerLink" href="broker.php" title="Broker Login">Broker</a><img class="brandLogo" src="logo.jpg" alt="Prem Garments PG Logo">
<div class="brandText">
<h1>PREM GARMENTS PVT LTD</h1>
</div>
<?php $pkStaffRole=(!empty($_SESSION['order_user'])&&is_array($_SESSION['order_user']))?(string)($_SESSION['order_user']['role']??''):''; ?><div class="headActions"><?php if($pkStaffRole==='admin'||$pkStaffRole==='salesman'): ?><a class="videosLink accountLink" href="reports.php">Reports</a><a class="videosLink accountLink" href="admin.php">Admin</a><?php elseif($pkStaffRole==='staff'): ?><a class="videosLink accountLink" href="order-report.php">Staff</a><?php elseif(!empty($_SESSION['customer'])&&empty($_SESSION['customer']['must_change'])): ?><a class="videosLink detailsLink" href="customer-account.php?logout=1" style="display:inline-flex;background:#516d83;border-color:#435c70;color:#fff">Logout</a><?php else: ?><a class="videosLink accountLink" href="customer-account.php">Customer Login</a><?php endif; ?></div>
</div>
<?php if(!empty($cuBarHtml))echo $cuBarHtml;else include __DIR__."/prem-info-nav.php"; ?>
<div class="quickBar<?php echo $pkCount>0?' hasPk':''; ?>">
<div class="categoryNav" aria-label="Product Categories">
<button type="button" class="categoryBtn active" data-category="kurti" aria-label="Women Kurtis" title="Women Kurtis"><?php if($kurtiThumb!==''): ?><img src="<?php echo h($kurtiThumb); ?>" alt="" loading="eager"><?php endif; ?><span class="tileLabel">Kurtis</span></button>
<button type="button" class="categoryBtn" data-category="two-piece" aria-label="Plazo Sets" title="Plazo Sets"><?php if($pgThumb!==''): ?><img src="<?php echo h($pgThumb); ?>" alt="" loading="eager"><?php endif; ?><span class="tileLabel">Plazo Sets</span></button>
<?php if($pkCount>0): ?><span class="pkTileWrap"><button type="button" class="categoryBtn pkTile" data-category="pk" aria-label="PK Economy Kurtis" title="PK Economy Kurtis"><?php if($pkThumb!==''): ?><img src="<?php echo h($pkThumb); ?>" alt="" loading="eager"><?php endif; ?><span class="tileLabel">PK</span></button><span class="pkEconomy">Economy</span></span><?php endif; ?>
</div>

<a class="videosLink videoTile" href="videos.php" aria-label="Download Videos" title="Download Videos"><span class="playBadge" aria-hidden="true">&#9654;</span><span class="tileLabel">Videos</span></a>
</div>
</div>
</header>



<div class="controls">
<div class="searchWrap">
<input type="search" id="search" placeholder="Search: K26-14, K2614 or 2614... ya likhiye: 3xl 400 to 500, M L XL available" autocomplete="off">
</div>
</div>
<div id="smartBar" style="display:none;align-items:center;gap:10px;flex-wrap:wrap;margin:8px 12px;padding:9px 12px;border:1px solid #bfe3cc;background:#f1fbf5;border-radius:10px;font-size:14px;color:#1f5f3a"><span id="smartText" style="flex:1 1 200px;font-weight:700"></span><button type="button" id="smartWa" onclick="smartSendWa()" style="border:0;border-radius:8px;background:#18964d;color:#fff;font-weight:800;font-size:14px;padding:9px 14px;cursor:pointer">WhatsApp par bhejo</button></div>

<?php if($pkCount>0): ?><div id="pkRateBar" class="pkRateBar" style="display:none">PK Economy MRP: M, L &#8377;450 &nbsp;|&nbsp; XL, XXL &#8377;550 &nbsp;|&nbsp; 3XL, 4XL &#8377;650</div><?php endif; ?>
<?php if ($driveError): ?>
<div class="empty"><h2>Images Folder Setup Required</h2><p><?php echo h($driveError); ?></p></div>
<?php elseif (count($items) === 0): ?>
<div class="empty">
<h2>No images found</h2>
<p>No supported images found in the images folder.</p>
</div>
<?php else: ?>

<div class="grid" id="premCatalogueProducts" style="scroll-margin-top:220px">
<?php foreach($items as $item): $mrp=preg_match('/\bMRP\s*[:=-]?\s*(\d+)/i',$item['design'],$mrpMatch)?(int)$mrpMatch[1]:0; $isPk=pkIsPkDesign($item['design']); if($isPk)$mrp=450; ?>
<article class="card" data-sizes="<?php echo h(implode(',',array_values(array_diff($sizes,$item['na'])))); ?>" data-img="<?php echo h(premImgShareUrl($item['file_id'],900)); ?>" data-dl="<?php echo h(productImageDownloadUrl($item['file_id'],$item['filename'])); ?>"
 data-search="<?php echo h(strtolower($item['filename'])); ?>"
 data-category="<?php echo pkCategoryOf($item['design']); ?>"
 data-design="<?php echo h($item['design']); ?>" data-mrp="<?php echo $mrp; ?>" data-pk="<?php echo $isPk?1:0; ?>">

<div class="productMedia">
<div class="imageBox">
<img class="lazy-product-img" data-preview-src="<?php echo h(catalogueImageUrl($item['filename'],$item['file_id'])); ?>" src="data:image/gif;base64,R0lGODlhAQABAAAAACw=" data-src="<?php echo h($item['display']); ?>" alt="<?php echo h(displayDesign($item['design'])); ?>" loading="lazy" decoding="async">
<noscript><img src="<?php echo h($item['display']); ?>" alt="<?php echo h(displayDesign($item['design'])); ?>"></noscript>
</div>
<div class="productActions" aria-label="Product image actions">
<a class="downloadLink" href="<?php echo h(productImageDownloadUrl($item['file_id'],$item['filename'])); ?>">Download Image</a>
<span class="divider">|</span>
<a class="waLink" target="_blank" rel="noopener" href="https://wa.me/?text=<?php echo rawurlencode(displayDesign($item['design'])."\nImage: ".premImgShareUrl($item['file_id'],900)); ?>">Share on WhatsApp</a>
</div>
</div>

<div class="info">
<div class="design"><?php echo h(displayDesign($item['design'])); ?></div>
<div class="sizeTitle">SIZE-WISE QUANTITY</div>

<div class="sizes">
<?php foreach($sizes as $size): $na=in_array($size,$item['na'],true); $sizeMrp=$isPk?pkSizeRate($size):$mrp+(in_array($size,array('3XL','4XL'),true)?100:0); ?>
<div class="size<?php echo $na?'':' available'; ?>"<?php echo $na?' style="background:#eee;opacity:.65"':'';?>>
<label><?php echo h($size); ?></label>
<?php if($mrp>0): ?><span class="sizeRate">MRP ₹<?php echo $sizeMrp; ?></span><?php endif; ?>
<?php if($na): ?><input disabled placeholder="-" style="background:#ddd"><?php else: ?>
<input class="qty" data-size="<?php echo h($size); ?>" type="number" min="0" step="1" value="0" readonly tabindex="-1">
<?php endif; ?></div>
<?php endforeach; ?>
</div>

<div class="pieces">Design Total: <span class="designTotal">0</span> pcs<?php if($mrp>0): ?> · MRP ₹<span class="designMrpTotal">0</span><?php endif; ?></div>
<p class="size-help">Tap a size box to add 1 &middot; Tap &minus; to remove 1</p>
</div>
</article>
<?php endforeach; ?>
</div>

<div id="productLoadMore" aria-hidden="true" style="height:2px"></div>
<div class="customer">
<div class="customerBox">
<h2>Customer Details</h2>
<div class="fields">
<input id="party" value="<?php echo h(isset($savedCustomer['name'])?$savedCustomer['name']:''); ?>" placeholder="Party / Customer Name" autocomplete="name" required>
<input id="mobile" value="<?php echo h(!empty($savedCustomer['mobile'])?pkIntlShowOrSame($savedCustomer['mobile']):''); ?>" inputmode="numeric" maxlength="16" placeholder="10-digit Mobile Number (videsh: country code ke saath)" autocomplete="tel" required>
<select id="salesman" aria-label="Salesman (optional)">
<option value="">Salesman select kare (optional)</option>
<?php foreach($salesmanChoices as $choiceSlug=>$choice): ?><option value="<?php echo h($choiceSlug); ?>"><?php echo h($choice['name']); ?></option>
<?php endforeach; ?>
</select>
<div id="customerLookupStatus" style="grid-column:1/-1;font-size:13px;color:#168b45"></div>
<div id="salesmanStatus"></div>
</div>
</div>
</div>




<div class="bottom">
<div class="bottomInner">
<div class="total">Total Pieces: <span id="grandTotal">0</span><small class="mrpGrand" id="grandMrp">MRP Total: ₹0</small></div>
<button class="view" onclick="showOrder()">View Order</button>
<button class="whatsapp" onclick="pkPrepareWhatsApp()">Prepare WhatsApp Order</button>
</div>
</div>

<style>
#pkLoginPop{display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:60;padding:20px;overflow:auto}
#pkLoginPop .pkBox{background:#fff;max-width:420px;margin:8vh auto 0;border-radius:16px;padding:20px 18px}
#pkLoginPop h3{margin:0 0 6px;font-size:20px;color:#29465e}
#pkLoginPop p{margin:0 0 12px;font-size:13px;color:#555}
#pkLoginPop input{width:100%;box-sizing:border-box;padding:13px;margin:0 0 10px;border:1px solid #cfd3d7;border-radius:10px;font-size:16px}
#pkLoginPop .pkGo{width:100%;padding:14px;border:0;border-radius:10px;background:#18964d;color:#fff;font-size:16px;font-weight:800}
#pkLoginPop .pkSkip{display:block;width:100%;margin-top:10px;padding:10px;border:0;background:none;color:#29465e;font-size:14px;text-decoration:underline}
#pkLoginPop .pkOut{width:100%;margin-top:10px;padding:14px;border:2px solid #18964d;border-radius:10px;background:#fff;color:#18964d;font-size:16px;font-weight:800}
#pkLoginPop .pkOr{display:flex;align-items:center;gap:10px;margin:12px 0 2px;color:#7a838a;font-size:13px}#pkLoginPop .pkOr:before,#pkLoginPop .pkOr:after{content:'';flex:1;height:1px;background:#d9dde1}
#pkLoginPop .pkGoogle{width:100%;margin-top:10px;padding:13px;border:1px solid #cfd3d7;border-radius:10px;background:#fff;color:#2b2f33;font-size:16px;font-weight:700;display:flex;align-items:center;justify-content:center;gap:10px;cursor:pointer}#pkLoginPop .pkGoogle:active{background:#f3f5f6}
#pkGoogleBack{display:none;position:fixed;left:12px;right:12px;bottom:84px;z-index:70;background:#18964d;color:#fff;padding:12px 14px;border-radius:12px;font-size:14px;font-weight:700;box-shadow:0 6px 20px rgba(0,0,0,.25);text-align:center}
#pkLoginPop .pkErr{color:#c62828;font-size:13px;min-height:16px;margin:0 0 6px}
</style>
<div id="pkLoginPop"><div class="pkBox">
<h3>Customer Login</h3>
<p>Login karke order seedha WhatsApp par bhejiye.</p>
<input id="pkLoginMobile" inputmode="numeric" maxlength="16" placeholder="Mobile Number / User ID" autocomplete="username">
<input id="pkLoginPass" type="password" placeholder="Password" autocomplete="current-password">
<div class="pkErr" id="pkLoginErr"></div>
<button type="button" class="pkGo" id="pkLoginBtn" onclick="pkDoLogin()">LOGIN &amp; SEND ORDER</button>
<div class="pkOr"><span>ya</span></div>
<button type="button" class="pkGoogle" id="pkGoogleBtn" onclick="pkGoogleLogin()"><svg width="20" height="20" viewBox="0 0 48 48" aria-hidden="true"><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.8 2.4 30.3 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.9 6.1C12.4 13.6 17.7 9.5 24 9.5z"/><path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4.1 7.1-10.1 7.1-17.5z"/><path fill="#FBBC05" d="M10.5 28.7A14.5 14.5 0 0 1 9.5 24c0-1.6.3-3.2.8-4.7l-7.9-6.1A24 24 0 0 0 0 24c0 3.9.9 7.5 2.6 10.8l7.9-6.1z"/><path fill="#34A853" d="M24 48c6.5 0 11.9-2.1 15.9-5.8l-7.5-5.8c-2.1 1.4-4.9 2.3-8.4 2.3-6.3 0-11.6-4.1-13.5-9.8l-7.9 6.1C6.5 42.6 14.6 48 24 48z"/></svg><span>Continue with Google</span></button>
<button type="button" class="pkOut" onclick="pkForgot()">PASSWORD BANAYEIN / BHOOL GAYE (WhatsApp OTP)</button>
<button type="button" class="pkSkip" onclick="pkCloseLogin()">Cancel</button>
</div></div>
<div id="pkGoogleBack"></div>
<div class="modal" id="modal">
<div class="modalBox">
<div class="modalTop">
<h2>Order Summary</h2>
<button class="close" onclick="closeModal()">Close</button>
</div>
<div id="summary"></div>
<button class="whatsapp" id="sendOrderBtn" style="width:100%" onclick="sendOrder()">Send Order to Bachchan Bhai - 0000000020</button>
</div>
</div>

<script>
function premLoadLazyImage(img){
  if(img.dataset.loaded==='1')return;
  img.dataset.loaded='1';
  img.addEventListener('load',function(){img.classList.add('is-loaded');},{once:true});
  img.src=img.getAttribute('data-src');
}
document.querySelectorAll('img.lazy-product-img').forEach(function(img){
 if('IntersectionObserver' in window){
  if(!window.premLazyImageObserver){
   window.premLazyImageObserver=new IntersectionObserver(function(entries){
    entries.forEach(function(entry){
     if(entry.isIntersecting){
      premLoadLazyImage(entry.target);
      window.premLazyImageObserver.unobserve(entry.target);
     }
    });
   },{rootMargin:'450px 0px'});
  }
  window.premLazyImageObserver.observe(img);
 } else {
  premLoadLazyImage(img);
 }
});

var cards = Array.prototype.slice.call(document.querySelectorAll('.card'));
var qtys = Array.prototype.slice.call(document.querySelectorAll('.qty'));
var activeCategory='kurti';
var PK_RATES={'M':450,'L':450,'XL':550,'XXL':550,'3XL':650,'4XL':650};
function pkCardRate(card,size,baseMrp){if(card.getAttribute('data-pk')==='1')return PK_RATES[size]||450;return baseMrp+(size==='3XL'||size==='4XL'?100:0);}
var visibleProductLimit=6;
var productLoadMore=document.getElementById('productLoadMore');

/* ---- SMART SEARCH (v156): "M L XL available", "400 to 500 3xl" jaise sawaal ---- */
var SMART_SIZE={'m':'M','l':'L','xl':'XL','xxl':'XXL','2xl':'XXL','3xl':'3XL','xxxl':'3XL','4xl':'4XL','xxxxl':'4XL'};
var SMART_FILL={me:1,mein:1,main:1,kaunse:1,kaun:1,kaunsa:1,kya:1,kon:1,konse:1,items:1,item:1,available:1,avilable:1,hai:1,hain:1,he:1,dikhao:1,dikhaye:1,dikhaiye:1,batao:1,bataye:1,show:1,size:1,sizes:1,design:1,designs:1,range:1,between:1,to:1,se:1,tak:1,rs:1,rupees:1,rupaye:1,rate:1,price:1,mrp:1,in:1,stock:1,the:1,and:1,aur:1,ka:1,ki:1,ke:1,wale:1,wali:1,wala:1,under:1,below:1,above:1,over:1,upar:1,kam:1,zyada:1,jyada:1,andar:1,niche:1,sab:1,all:1,wo:1,ye:1,mujhe:1,chahiye:1,dena:1,do:1,please:1,pls:1,for:1,of:1,with:1,up:1,less:1,more:1,than:1,min:1,max:1,upto:1};
function smartParse(raw){
 var q=String(raw||'').toLowerCase().replace(/₹/g,' rs ').replace(/\s+/g,' ').trim();
 if(q.length<2)return null;
 var toks=q.split(/[^a-z0-9]+/).filter(Boolean),sizes=[],bigSize=false,smallCnt=0;
 toks.forEach(function(t){var s=SMART_SIZE[t];if(!s)return;if(sizes.indexOf(s)<0)sizes.push(s);if(t==='m'||t==='l')smallCnt++;else bigSize=true;});
 var lo=null,hi=null,m,priceCue=false;
 if((m=q.match(/(?:^|[^a-z0-9])(\d{3,4})\s*(?:to|se|and|aur|-|–|—)\s*(\d{3,4})(?![a-z0-9])/))){var a=+m[1],b=+m[2];if(a>=100&&b<=1500&&a<=1500&&b>=100){lo=Math.min(a,b);hi=Math.max(a,b);priceCue=true;}}
 if(!priceCue){
  if((m=q.match(/(?:under|below|less than|upto|up to|max|kam|tak)\s*(?:rs\.?)?\s*(\d{3,4})/))||(m=q.match(/(\d{3,4})\s*(?:tak|se kam|ke andar|ke niche|below|under)/))){hi=+m[1];priceCue=true;}
  if((m=q.match(/(?:above|over|more than|min|upar)\s*(?:rs\.?)?\s*(\d{3,4})/))||(m=q.match(/(\d{3,4})\s*(?:se zyada|se jyada|se upar|above|plus|\+)/))){lo=+m[1];priceCue=true;}
  if(!priceCue&&(m=q.match(/(?:rs\.?|rate|price|mrp)\s*(\d{3,4})\b|\b(\d{3,4})\s*(?:rs|rupees|rupaye)\b/))){var v=+(m[1]||m[2]);if(v>=100&&v<=1500){lo=v;hi=v;priceCue=true;}}
 }
 var word=/\b(size|sizes|available|avilable|stock)\b/.test(q);
 var smart=bigSize||smallCnt>=2||(smallCnt>=1&&(priceCue||word))||(priceCue&&toks.length>=2);
 if(!smart)return null;
 var rem=toks.filter(function(t){return !SMART_SIZE[t]&&!SMART_FILL[t]&&!/^\d{1,4}$/.test(t)&&/\d/.test(t)&&t.length>=3;});
 return {sizes:sizes,lo:lo,hi:hi,rem:rem};
}
function smartRate(card,size){var base=Number(card.getAttribute('data-mrp'))||0;if(base<=0)return 0;return pkCardRate(card,size,base);}
function smartMatch(card,p,strict){
 var avail=(card.getAttribute('data-sizes')||'').split(',').filter(Boolean);
 if(!avail.length)return false;
 if(p.sizes.length){
  if(strict){if(!p.sizes.every(function(s){return avail.indexOf(s)>-1;}))return false;}
  else if(!p.sizes.some(function(s){return avail.indexOf(s)>-1;}))return false;
 }
 if(p.lo!==null||p.hi!==null){
  var chk=p.sizes.length?p.sizes.filter(function(s){return avail.indexOf(s)>-1;}):[avail[0]];
  for(var i=0;i<chk.length;i++){var r=smartRate(card,chk[i]);if(!r)return false;if(p.lo!==null&&r<p.lo)return false;if(p.hi!==null&&r>p.hi)return false;}
 }
 if(p.rem.length){var cs=(card.getAttribute('data-search')||'').toLowerCase().replace(/[^a-z0-9]/g,'');for(var j=0;j<p.rem.length;j++){if(cs.indexOf(p.rem[j].replace(/[^a-z0-9]/g,''))<0)return false;}}
 return true;
}
function smartDesc(p,relaxed){
 var t=[];
 if(p.sizes.length)t.push('Size '+p.sizes.join(', ')+(p.sizes.length>1?(relaxed?' (koi bhi)':' (sab available)'):''));
 if(p.lo!==null||p.hi!==null)t.push(p.lo!==null&&p.hi!==null&&p.lo!==p.hi?'Rate ₹'+p.lo+' se ₹'+p.hi:(p.lo!==null&&p.hi!==null?'Rate ₹'+p.lo:(p.hi!==null?'Rate ₹'+p.hi+' tak':'Rate ₹'+p.lo+' se upar')));
 return t.join(' · ');
}
var smartState={p:null,cards:[],relaxed:false};
function smartBar(p,matches,relaxed){
 var bar=document.getElementById('smartBar');if(!bar)return;
 smartState={p:p,cards:matches,relaxed:relaxed};
 if(!p){bar.style.display='none';return;}
 bar.style.display='flex';
 document.getElementById('smartText').textContent=(smartDesc(p,relaxed)||'Smart search')+' — '+(matches.length?matches.length+' design mile':'koi design nahi mili');
 document.getElementById('smartWa').style.display=matches.length?'':'none';
}
function smartMessage(){
 var s=smartState,list=s.cards.slice(0,15),L=['Prem Kurtis — '+(smartDesc(s.p,s.relaxed)||'designs')+' ('+s.cards.length+' design)',''];
 list.forEach(function(c,i){
  var avail=(c.getAttribute('data-sizes')||'').split(',').filter(Boolean),base=Number(c.getAttribute('data-mrp'))||0;
  var rates=base>0?avail.map(function(z){return z+' ₹'+pkCardRate(c,z,base);}).join(', '):avail.join(', ');
  var img=c.getAttribute('data-img')||'';
  L.push((i+1)+') '+cleanDesignName(c.getAttribute('data-design')||'')+' — '+rates+(img?'\nPhoto: '+img:''));
 });
 if(s.cards.length>list.length)L.push('','…aur '+(s.cards.length-list.length)+' designs: '+location.href.split('#')[0]);
 return L.join('\n');
}
function smartSendWa(){
 var s=smartState;if(!s.cards.length)return;
 var text=smartMessage(),go=function(){window.open('https://wa.me/?text='+encodeURIComponent(text),'_blank');};
 var files=s.cards.slice(0,8);
 if(navigator.canShare&&navigator.share&&window.fetch){
  Promise.all(files.map(function(c,i){var u=c.getAttribute('data-dl');if(!u)return null;return fetch(u,{credentials:'same-origin'}).then(function(r){if(!r.ok)throw 0;return r.blob();}).then(function(b){return new File([b],'design-'+(i+1)+'.jpg',{type:b.type||'image/jpeg'});});}))
  .then(function(fs){fs=fs.filter(Boolean);var d={files:fs,text:text};if(fs.length&&navigator.canShare(d))return navigator.share(d);go();})
  .catch(function(e){if(e&&e.name==='AbortError')return;go();});
 }else go();
}

function filterProducts(){
 var pkBar=document.getElementById('pkRateBar');if(pkBar)pkBar.style.display=activeCategory==='pk'?'block':'none';
 var q=document.getElementById('search').value.trim().toLowerCase();
 var compactQ=q.replace(/[^a-z0-9]/g,''); if(/^9[0-9]{4}$/.test(compactQ))compactQ='pg'+compactQ.slice(1); /* PG alias: 90101 = PG0101 = PG01-01 */
 var matches=[];
 var sp=smartParse(q),spRelaxed=false;
 if(sp){
  var inCat=cards.filter(function(card){return card.getAttribute('data-category')===activeCategory;});
  var strictHits=inCat.filter(function(card){return smartMatch(card,sp,true);});
  if(!strictHits.length&&sp.sizes.length>1){strictHits=inCat.filter(function(card){return smartMatch(card,sp,false);});spRelaxed=strictHits.length>0;}
  cards.forEach(function(card){if(strictHits.indexOf(card)>-1)matches.push(card);else card.style.display='none';});
 }else
 cards.forEach(function(card){
  var categoryMatch=card.getAttribute('data-category')===activeCategory;
  var searchable=card.getAttribute('data-search').toLowerCase();
  var compactSearchable=searchable.replace(/[^a-z0-9]/g,'');
  var searchMatch=q===''||searchable.indexOf(q)!==-1||(compactQ!==''&&compactSearchable.indexOf(compactQ)!==-1);
  if(categoryMatch&&searchMatch)matches.push(card);
  else card.style.display='none';
 });
 smartBar(sp,matches,spRelaxed);
 matches.forEach(function(card,index){card.style.display=index<visibleProductLimit?'':'none';});
 if(productLoadMore)productLoadMore.style.display=matches.length>visibleProductLimit?'block':'none';
}
function revealMoreProducts(){
 if(!productLoadMore||productLoadMore.style.display==='none')return;
 visibleProductLimit+=10;
 filterProducts();
}
if(productLoadMore){
 if('IntersectionObserver' in window){
  var productObserver=new IntersectionObserver(function(entries){
   if(entries[0].isIntersecting)revealMoreProducts();
  },{rootMargin:'0px 0px 100px 0px'});
  productObserver.observe(productLoadMore);
 }else window.addEventListener('scroll',function(){
  if(productLoadMore.style.display!=='none'&&productLoadMore.getBoundingClientRect().top<window.innerHeight+100)revealMoreProducts();
 },{passive:true});
}

document.querySelectorAll('.categoryBtn').forEach(function(button){
 button.addEventListener('click',function(){
  activeCategory=button.getAttribute('data-category');
  visibleProductLimit=document.getElementById('search').value.trim()?Number.MAX_SAFE_INTEGER:6;
  document.querySelectorAll('.categoryBtn').forEach(function(btn){btn.classList.remove('active');});
  button.classList.add('active');
  filterProducts();
  document.getElementById('search').focus();
 });
});

document.querySelectorAll('.size.available').forEach(function(box){
 box.addEventListener('click',function(){
  var input=box.querySelector('.qty');
  input.value=(parseInt(input.value,10)||0)+1;
  updateTotals();
 });
});

document.querySelectorAll('.clearItem').forEach(function(button){
 button.addEventListener('click',function(){
  var card=button.closest('.card');
  card.querySelectorAll('.qty').forEach(function(input){input.value=0;});
  updateTotals();
 });
});

function updateTotals(){
 var grand=0,grandMrp=0,missingRate=false;
 cards.forEach(function(card){
  var total=0,amount=0,baseMrp=Number(card.getAttribute('data-mrp'))||0;
  card.querySelectorAll('.qty').forEach(function(input){
   var count=Math.max(0,parseInt(input.value,10)||0);
   total += count;
   if(count>0){
    if(baseMrp>0)amount+=count*pkCardRate(card,input.getAttribute('data-size'),baseMrp);
    else missingRate=true;
   }
   var minus=input.parentElement.querySelector('.qty-minus');
   if(minus){minus.classList.toggle('visible',count>0);minus.disabled=count===0;}
  });
  card.querySelector('.designTotal').textContent=total;
  var designMrp=card.querySelector('.designMrpTotal');
  if(designMrp)designMrp.textContent=amount.toLocaleString('en-IN');
  grand+=total;
  grandMrp+=amount;
 });
 document.getElementById('grandTotal').textContent=grand;
 document.getElementById('grandMrp').textContent=missingRate?'MRP Total: rate missing':'MRP Total: ₹'+grandMrp.toLocaleString('en-IN');
}
qtys.forEach(function(input){input.addEventListener('input',updateTotals);});

document.getElementById('search').addEventListener('input',function(){
 visibleProductLimit=this.value.trim()?Number.MAX_SAFE_INTEGER:6;
 filterProducts();
});

filterProducts();

function cleanDesignName(name){
 return String(name||'').replace(/\s+NA\b.*$/i,'').trim();
}

function buildOrder(){
 var party=document.getElementById('party').value.trim();
 var mobile=document.getElementById('mobile').value.trim();
 var lines=[],grand=0,designCount=0,grandMrp=0,missingRate=false;

 cards.forEach(function(card){
  var parts=[],total=0,amount=0,baseMrp=Number(card.getAttribute('data-mrp'))||0;
  card.querySelectorAll('.qty').forEach(function(input){
   var q=Math.max(0,parseInt(input.value,10)||0);
   if(q>0){
    var size=input.getAttribute('data-size');
    var rate=pkCardRate(card,size,baseMrp);
    parts.push(size+'-'+q+(baseMrp>0?' @ MRP ₹'+rate:''));
    total+=q;
    if(baseMrp>0)amount+=q*rate;
    else missingRate=true;
   }
  });
  if(total>0){
   designCount++;
   grand+=total;
   grandMrp+=amount;
   lines.push(cleanDesignName(card.getAttribute('data-design'))+' : '+parts.join(', ')+' | Total '+total+(baseMrp>0?' | MRP ₹'+amount.toLocaleString('en-IN'):''));
  }
 });

 if(lines.length===0) return '';

 var text='*PREM KURTIS - BULK ORDER*\n';
 if(party) text+='Party: '+party+'\n';
 if(mobile) text+='Mobile: '+mobile+'\n';
 var chosenSalesman=selectedSalesman();
 if(chosenSalesman.chosen) text+='Salesman: '+chosenSalesman.name+'\n';

 text+='\n*SIZE-WISE ORDER*\n\n';
 text+=lines.join('\n');
 text+='\n\nDesigns: '+designCount;
 text+='\n*TOTAL PIECES: '+grand+'*';
 if(!missingRate)text+='\n*TOTAL MRP: ₹'+grandMrp.toLocaleString('en-IN')+'*';
 return text;
}

// Optional Salesman box: select kiya to order usi salesman ko, warna Bachchan Bhai ko.
var premSalesmen=<?php echo json_encode($salesmanChoices); ?>;
var premDefaultSalesman={slug:'direct',name:'Bachchan Bhai',mobile:'0000000020',chosen:false};
function selectedSalesman(){
 var box=document.getElementById('salesman'),slug=box?box.value:'';
 if(slug&&premSalesmen[slug]) return {slug:slug,name:premSalesmen[slug].name,mobile:premSalesmen[slug].mobile,chosen:true};
 return premDefaultSalesman;
}
// Customer ka fixed salesman (server se aata hai). Khali = abhi fix nahi hai, customer chun sakta hai.
var fixedSalesmanSlug='';
function updateSalesmanUi(){
 var salesman=selectedSalesman();
 var status=document.getElementById('salesmanStatus'),button=document.getElementById('sendOrderBtn');
 var message='Salesman select karna zaroori nahi hai. Select nahi kiya to order Bachchan Bhai (0000000020) ko WhatsApp hoga.';
 if(fixedSalesmanSlug&&salesman.chosen) message='Aapke salesman '+salesman.name+' ('+salesman.mobile+') hain. Aapka har order inhi ko WhatsApp hoga. Salesman badalne ke liye Prem Garments se sampark kare.';
 else if(salesman.chosen) message='Aapka order '+salesman.name+' ('+salesman.mobile+') ko WhatsApp hoga. Dhyan de: order save hone ke baad yahi salesman aapke liye fix ho jayega.';
 if(status) status.textContent=message;
 if(button) button.textContent='Send Order to '+salesman.name+' - '+salesman.mobile;
}
// slug mila to box me wahi salesman lagakar box lock; khali mila to lock hata do.
function applyFixedSalesman(slug){
 var box=document.getElementById('salesman');
 if(!box) return;
 if(slug&&premSalesmen[slug]){fixedSalesmanSlug=slug;box.value=slug;box.disabled=true;}
 else if(fixedSalesmanSlug){fixedSalesmanSlug='';box.value='';box.disabled=false;}
 updateSalesmanUi();
}
document.getElementById('salesman').addEventListener('change',updateSalesmanUi);
updateSalesmanUi();

function orderData(){
 var items=[],grand=0;
 cards.forEach(function(card){
  var sizes=[],total=0;
  card.querySelectorAll('.qty').forEach(function(input){
   var q=Math.max(0,parseInt(input.value,10)||0);
   if(q>0){sizes.push(input.getAttribute('data-size')+'-'+q);total+=q;}
  });
  if(total>0){items.push({design:card.getAttribute('data-design'),sizes:sizes,total:total});grand+=total;}
 });
 var salesman=selectedSalesman();
 return {party:document.getElementById('party').value.trim(),mobile:document.getElementById('mobile').value.trim(),salesmanName:salesman.chosen?salesman.name:'Website / Direct',salesmanMobile:salesman.mobile,salesmanSlug:salesman.slug,salesmanPicker:true,items:items,totalPieces:grand};
}

var lookupToken=<?php echo json_encode($_SESSION['customer_lookup_token']); ?>;
var savedOrderNo='';
var savedOrderSignature='';
var savedOrderResult=null;

function pkNormMob(v){var d=String(v||'').replace(/\D/g,'');if(d.length===12&&d.slice(0,2)==='91')d=d.slice(2);else if(d.length===11&&d[0]==='0')d=d.slice(1);return d.slice(0,15);}
var lookupTimer=null,lastLookupMobile='';
document.getElementById('mobile').addEventListener('input',function(){
 this.value=pkNormMob(this.value);
 clearTimeout(lookupTimer);
 var mobile=this.value,status=document.getElementById('customerLookupStatus');
 status.textContent='';
 if(mobile.length<10){lastLookupMobile='';applyFixedSalesman('');}
 if(mobile.length>=10)lookupTimer=setTimeout(function(){lookupCustomer(mobile);},350);
});
document.getElementById('mobile').addEventListener('blur',function(){if(this.value.length>=8)lookupCustomer(this.value);});
async function lookupCustomer(mobile){
 if(mobile===lastLookupMobile)return;
 lastLookupMobile=mobile;
 var status=document.getElementById('customerLookupStatus');
 try{
  var body=new URLSearchParams();body.set('mobile',mobile);body.set('token',lookupToken);
  var response=await fetch('customer-lookup.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},body:body.toString(),cache:'no-store'});
  var result=await response.json();
  if(result.ok&&mobile===document.getElementById('mobile').value)applyFixedSalesman(result.salesman||'');
  if(result.ok&&result.found){document.getElementById('party').value=result.name;status.textContent='Existing customer found. Name filled automatically.';}
  else if(result.ok&&!/^[6-9][0-9]{9}$/.test(mobile)){status.textContent='Ye videsh number abhi registered nahi hai. Prem Garments se sampark karke account banwaiye.';}
  else if(result.ok){status.textContent='New customer: account will be created after first successful order.';}
 }catch(e){status.textContent='';lastLookupMobile='';}
}
// Login kiye hue customer ka mobile pehle se bhara hota hai: uska fixed salesman turant laga do.
if(document.getElementById('mobile').value.length>=8)lookupCustomer(document.getElementById('mobile').value);

async function saveCurrentOrder(){
 var data=orderData();
 var signature=JSON.stringify(data);
 if(savedOrderResult && signature===savedOrderSignature) return savedOrderResult;
 var body=new URLSearchParams();
 body.set('payload',signature);
 var response=await fetch('save-customer-order.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},body:body.toString(),cache:'no-store'});
 var raw=await response.text(),result;
 try{result=JSON.parse(raw);}catch(e){throw new Error('Server response: '+raw.substring(0,150));}
 if(!response.ok||!result.ok) throw new Error(result.message||'Order could not be saved.');
 savedOrderNo=result.orderNo;
 savedOrderResult=result;
 // Server batata hai ki is customer ka fixed salesman kaun hai; box me wahi lagakar lock kar do.
 if(result.fixedSalesman)applyFixedSalesman(result.fixedSalesman);
 savedOrderSignature=JSON.stringify(orderData());
 return result;
}

function pkGoCustomer(id){
 var box=document.querySelector('.customerBox'),el=document.getElementById(id);
 var go=function(b){if(box)box.scrollIntoView({behavior:b,block:'center'});};
 go('auto');
 setTimeout(function(){go('auto');},250);
 setTimeout(function(){go('auto');},700);
 if(el){
  el.style.outline='2px solid #d32f2f';
  el.addEventListener('input',function(){el.style.outline='';},{once:true});
  setTimeout(function(){try{el.focus({preventScroll:true});}catch(e){el.focus();}},900);
 }
}
var pkLoggedIn=<?php echo !empty($savedCustomer['mobile'])?'true':'false'; ?>;
function pkOpenLogin(){document.getElementById('pkLoginErr').textContent='';document.getElementById('pkLoginPop').style.display='block';setTimeout(function(){document.getElementById('pkLoginMobile').focus();},100);}
function pkCloseLogin(){document.getElementById('pkLoginPop').style.display='none';}
function pkPrepareWhatsApp(){
 if(!buildOrder()){alert('Please enter quantity for at least one design.');return;}
 if(pkLoggedIn){sendOrder();return;}
 pkOpenLogin();
}
function pkForgot(){var f=(location.pathname.split('/').pop()||'index.php');if(!/\.php$/.test(f))f=/^[A-Za-z0-9_-]+$/.test(f)?f+'.php':'index.php';location.href='customer-password-wa.php?back='+encodeURIComponent(f);}
function pkSkipLogin(){document.getElementById('pkLoginErr').textContent='Order ke liye login (mobile + password) zaroori hai.';return;
 var m=pkNormMob(document.getElementById('pkLoginMobile').value),n=document.getElementById('pkLoginParty').value.trim();
 var err=document.getElementById('pkLoginErr');
 if(!n){err.textContent='Party / Customer Name daliye.';document.getElementById('pkLoginParty').focus();return;}
 if(!/^[6-9][0-9]{9}$/.test(m)&&!/^[1-9][0-9]{7,14}$/.test(m)){err.textContent='Sahi 10-digit Mobile Number daliye (videsh ho to country code ke saath).';document.getElementById('pkLoginMobile').focus();return;}
 document.getElementById('party').value=n;document.getElementById('mobile').value=m;
 try{if(typeof lookupCustomer==='function')lookupCustomer(m);}catch(e){}
 pkCloseLogin();sendOrder();
}

/* ---- Google se login: order (quantity) bachakar Google par bhejna, wapas aane par order waisa hi laut aata hai ---- */
function pkGoogleLogin(){
 try{
  var saved={};
  cards.forEach(function(card){
   var d=card.getAttribute('data-design');
   card.querySelectorAll('.qty').forEach(function(input){
    var q=Math.max(0,parseInt(input.value,10)||0);
    if(q>0)saved[d+'|'+input.getAttribute('data-size')]=q;
   });
  });
  sessionStorage.setItem('pkGoogleCart',JSON.stringify(saved));
 }catch(e){}
 window.location.href='google-login.php?return=order';
}
(function(){
 try{
  var raw=sessionStorage.getItem('pkGoogleCart');
  if(raw===null)return;
  sessionStorage.removeItem('pkGoogleCart');
  if(!pkLoggedIn)return; // login poora nahi hua to kuch mat karo
  var saved=JSON.parse(raw)||{},n=0;
  cards.forEach(function(card){
   var d=card.getAttribute('data-design');
   card.querySelectorAll('.qty').forEach(function(input){
    var k=d+'|'+input.getAttribute('data-size');
    if(saved[k]){input.value=saved[k];n++;}
   });
  });
  updateTotals();
  var t=document.getElementById('pkGoogleBack');
  if(t){t.textContent='Google se login ho gaya'+(n?'. Aapka order wapas aa gaya: ab "Prepare WhatsApp Order" dabaiye.':'.');t.style.display='block';setTimeout(function(){t.style.display='none';},9000);}
 }catch(e){}
})();
async function pkDoLogin(){
 var m=pkNormMob(document.getElementById('pkLoginMobile').value),p=document.getElementById('pkLoginPass').value;
 var err=document.getElementById('pkLoginErr'),btn=document.getElementById('pkLoginBtn');
 if(!m||!p){err.textContent='Mobile number aur password dono daliye (login ke liye).';return;}
 btn.disabled=true;err.textContent='';
 try{
  var body=new URLSearchParams();body.set('mobile',m);body.set('password',p);body.set('token',lookupToken);
  var r=await fetch('customer-login-popup.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},body:body.toString(),cache:'no-store'});
  var res=await r.json();
  if(!res.ok)throw new Error(res.message||'Login failed.');
  pkLoggedIn=true;
  document.getElementById('party').value=res.name||'';
  document.getElementById('mobile').value=res.mobile||m;
  try{if(typeof lookupCustomer==='function')await lookupCustomer(document.getElementById('mobile').value);}catch(e){}
  pkCloseLogin();
  sendOrder();
 }catch(e){err.textContent=e.message;}
 btn.disabled=false;
}
async function showOrder(){
 var party=document.getElementById('party').value.trim();
 var mobile=document.getElementById('mobile').value.trim();
 if(!party){pkGoCustomer('party');return;}
 if(!mobile){pkGoCustomer('mobile');return;}
 var text=buildOrder();
 if(!text){alert('Please enter quantity for at least one design.');return;}
 try{
  var result=await saveCurrentOrder(),orderNo=result.orderNo;
  text=buildOrder();
  var loginInfo='\n\nMY ORDERS LOGIN\nUser ID: '+result.userId;
  if(result.accountCreated)loginInfo+='\nDefault Password: CONFIGURED_TEMP_PASSWORD\nFirst login par password change compulsory hai.';
  else loginInfo+='\nUse your changed password.';
  document.getElementById('summary').textContent=('ORDER SAVED: '+orderNo+'\n\n'+text+loginInfo).replace(/\*/g,'');
  document.getElementById('modal').style.display='block';
  alert('Order Saved Successfully: '+orderNo);
 }catch(e){alert('ORDER NOT SAVED: '+e.message);}
}
function closeModal(){
 document.getElementById('modal').style.display='none';
}
async function sendOrder(){
 var party=document.getElementById('party').value.trim();
 var mobile=document.getElementById('mobile').value.trim();
 if(!party){pkGoCustomer('party');return;}
 if(!mobile){pkGoCustomer('mobile');return;}
 var text=buildOrder();
 if(!text){alert('Please enter quantity for at least one design.');return;}
 try{
  var result=await saveCurrentOrder(),orderNo=result.orderNo;
  text=buildOrder();
  text+='\nOrder No: '+orderNo;
  if(result.accountCreated)text+='\nMy Orders User ID: '+result.userId+'\nDefault Password: CONFIGURED_TEMP_PASSWORD';
  // Number server se aata hai (save-customer-order.php), taki order jis salesman ke naam save hua usi ko jaye.
  var waMobile=String(result.salesmanMobile||selectedSalesman().mobile).replace(/\D/g,'').slice(-10);
  if(waMobile.length!==10) waMobile='0000000020';
  window.location.href='https://wa.me/91'+waMobile+'?text='+encodeURIComponent(text);
 }catch(e){alert('Order save failed: '+e.message);}
}
document.getElementById('modal').addEventListener('click',function(e){
 if(e.target.id==='modal') closeModal();
});
</script>
<?php endif; ?>

<script id="prem-qty-controls-js-v46">
(function(){
 document.querySelectorAll('.size.available').forEach(function(box){
  var input=box.querySelector('input.qty');
  if(!input||box.querySelector('.qty-minus'))return;
  var minus=document.createElement('button');
  minus.type='button';minus.className='qty-minus';minus.textContent='−';
  minus.setAttribute('aria-label','Reduce '+(input.getAttribute('data-size')||'size')+' quantity');
  minus.addEventListener('click',function(event){
   event.preventDefault();event.stopPropagation();
   input.value=Math.max(0,(parseInt(input.value,10)||0)-1);
   if(typeof updateTotals==='function')updateTotals();
   else input.dispatchEvent(new Event('input',{bubbles:true}));
  });
  box.appendChild(minus);
 });
 if(typeof updateTotals==='function')updateTotals();
})();
</script>

<style id="prem-wa-float">
/* Floating WhatsApp chat button: "Prepare WhatsApp Order" ke theek upar, right side. */
.waFloat{position:fixed;right:12px;bottom:82px;z-index:31;display:flex;align-items:center;gap:7px;padding:10px 15px 10px 11px;border-radius:999px;background:#25d366;color:#fff!important;text-decoration:none;font-size:13px;font-weight:900;line-height:1;box-shadow:0 4px 14px rgba(0,0,0,.3);border:2px solid #fff;-webkit-tap-highlight-color:transparent}
.waFloat svg{width:22px;height:22px;flex:0 0 22px;display:block}
.waFloat:active{transform:scale(.96)}
@media(max-width:650px){.waFloat{right:8px;bottom:70px;padding:9px 13px 9px 10px;font-size:12px}.waFloat svg{width:20px;height:20px;flex-basis:20px}}
@media print{.waFloat{display:none!important}}
</style>
<a class="waFloat" id="waFloat" href="https://wa.me/910000000020?text=Hello%20Prem%20Kurtis" target="_blank" rel="noopener" aria-label="Any Questions - WhatsApp par poochhiye" title="Any Questions"><svg viewBox="0 0 24 24" aria-hidden="true"><path fill="#fff" d="M12 2.5C6.8 2.5 2.6 6.4 2.6 11.2c0 1.8.6 3.5 1.7 4.9L3.2 21l4.3-1.3c1.4.7 2.9 1.1 4.5 1.1 5.2 0 9.4-3.9 9.4-8.6S17.200 2.500 12 2.500z"/><path fill="#25d366" d="M8.700 7.600c.3-.3.7-.3.9 0l.9 1.700c.1.300.1.600-.1.800l-.5.600c.7 1.300 1.700 2.300 3 3l.6-.6c.2-.2.500-.3.800-.1l1.700.9c.3.2.4.600.1.900-.6.800-1.600 1.100-2.600.8-3-.9-5-3-5.800-5.600-.2-.9.1-1.800 1-2.400z"/></svg><span>Any Questions</span></a>
<script id="prem-wa-float-js">
// Click par number chuna jata hai: customer ka salesman (chosen/fixed) ho to usi ko, warna 0000000020.
(function(){
 var a=document.getElementById('waFloat');
 if(!a)return;
 function setHref(){
  var num='0000000020';
  try{
   if(typeof selectedSalesman==='function'){
    var s=selectedSalesman();
    if(s&&s.mobile)num=String(s.mobile).replace(/\D/g,'').slice(-10);
   }
  }catch(e){}
  if(num.length!==10)num='0000000020';
  a.href='https://wa.me/91'+num+'?text='+encodeURIComponent('Hello Prem Kurtis');
 }
 a.addEventListener('click',setHref);
 a.addEventListener('touchstart',setHref,{passive:true});
})();
</script>
<script src="product-hold-preview.js?v=83"></script>
</body>
</html>

