<?php
include '_head.php';
function admin_notice2($type,$msg){ echo '<div class="admin-card" style="border-right:5px solid '.($type==='ok'?'#16a34a':'#ef4444').';margin-bottom:14px"><b>'.($type==='ok'?'تم':'تنبيه').'</b><br>'.e($msg).'</div>'; }
function optimize_one_image_file($rel,$max=1200,$quality=78){
    $rel=str_replace('\\','/',trim($rel)); if($rel==='' || preg_match('#^https?://#i',$rel) || preg_match('/\.svg$/i',$rel)) return array(false,$rel,'skip');
    $full=__DIR__.'/../'.ltrim($rel,'/'); if(!is_file($full)) return array(false,$rel,'missing');
    if(!function_exists('imagecreatefromstring') || !function_exists('imagewebp')) return array(false,$rel,'gd_missing');
    $data=@file_get_contents($full); if(!$data) return array(false,$rel,'read_fail');
    $im=@imagecreatefromstring($data); if(!$im) return array(false,$rel,'decode_fail');
    $w=imagesx($im); $h=imagesy($im); $scale=min(1,$max/max($w,$h)); $nw=(int)round($w*$scale); $nh=(int)round($h*$scale);
    $out=imagecreatetruecolor($nw,$nh); imagesavealpha($out,true); $transparent=imagecolorallocatealpha($out,255,255,255,127); imagefill($out,0,0,$transparent);
    imagecopyresampled($out,$im,0,0,0,0,$nw,$nh,$w,$h);
    $new='uploads/products/opt_'.date('YmdHis').'_'.mt_rand(1000,9999).'.webp'; $newfull=__DIR__.'/../'.$new; if(!is_dir(dirname($newfull))) @mkdir(dirname($newfull),0777,true);
    imagewebp($out,$newfull,$quality); imagedestroy($im); imagedestroy($out);
    if(is_file($newfull) && filesize($newfull)>100){ return array(true,$new,'ok'); }
    return array(false,$rel,'write_fail');
}
$done=0; $skip=0; $msg='';
if($_SERVER['REQUEST_METHOD']==='POST'){
    $limit=isset($_POST['limit'])?(int)$_POST['limit']:20; if($limit<1)$limit=20; if($limit>80)$limit=80;
    $rs=mysqli_query($conn,"SELECT id,image_path FROM product_images WHERE image_path NOT LIKE 'http%' AND image_path NOT LIKE '%.webp' ORDER BY id ASC LIMIT $limit");
    if($rs){ while($r=mysqli_fetch_assoc($rs)){ list($ok,$new,$why)=optimize_one_image_file($r['image_path']); if($ok){ $safe=mysqli_real_escape_string($conn,$new); mysqli_query($conn,"UPDATE product_images SET image_path='$safe' WHERE id=".(int)$r['id']); $done++; } else $skip++; }}
    $msg='تم ضغط '.$done.' صورة، وتخطي '.$skip.'. كرر العملية حتى يصبح العدد 0.';
}
$remain=0; $q=mysqli_query($conn,"SELECT COUNT(*) c FROM product_images WHERE image_path NOT LIKE 'http%' AND image_path NOT LIKE '%.webp' AND image_path NOT LIKE '%.svg'"); if($q){$r=mysqli_fetch_assoc($q);$remain=(int)$r['c'];}
?>
<h1>تسريع وضغط صور المنتجات</h1>
<?php if($msg) admin_notice2('ok',$msg); ?>
<div class="admin-card"><p>الصور PNG/JPG الكبيرة تجعل الموقع ثقيلاً. هذه الأداة تحوّل الصور المحلية إلى WebP خفيفة وتحدّث قاعدة البيانات تلقائياً.</p><p><b>الصور المتبقية للضغط:</b> <?php echo (int)$remain; ?></p></div>
<form method="post" class="admin-card admin-form"><label>عدد الصور في كل دفعة</label><input name="limit" type="number" value="20" min="1" max="80"><button class="primary-btn">ضغط دفعة الآن</button></form>
<?php include '_foot.php'; ?>
