<?php
if (session_id() === '') { session_start(); }

function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function asset($p){ return ltrim((string)$p, '/'); }
function current_lang(){
    $lang = 'en';
    if (isset($_GET['lang'])) { $lang = $_GET['lang']; $_SESSION['lang'] = $lang; }
    elseif (isset($_SESSION['lang'])) { $lang = $_SESSION['lang']; }
    if (!in_array($lang, array('ar','en','ku'))) $lang='en';
    return $lang;
}
function is_rtl($lang){ return in_array($lang, array('ar','ku')); }
function lang_url($lang){ $p = $_GET; $p['lang'] = $lang; return strtok($_SERVER['REQUEST_URI'], '?') . '?' . http_build_query($p); }
function t($key){ global $TR; return isset($TR[$key]) ? $TR[$key] : $key; }
function money_iqd($n){ return number_format((float)$n, 0) . ' ' . t('iqd'); }
function table_column_exists($conn,$table,$col){ $table=mysqli_real_escape_string($conn,$table); $col=mysqli_real_escape_string($conn,$col); $q=mysqli_query($conn,"SHOW COLUMNS FROM `$table` LIKE '$col'"); return $q && mysqli_num_rows($q)>0; }
function table_index_exists($conn,$table,$idx){ $table=mysqli_real_escape_string($conn,$table); $idx=mysqli_real_escape_string($conn,$idx); $q=mysqli_query($conn,"SHOW INDEX FROM `$table` WHERE Key_name='$idx'"); return $q && mysqli_num_rows($q)>0; }
function ensure_project_schema($conn){
    static $done=false; if($done) return; $done=true;
    if(!table_column_exists($conn,'categories','parent_id')) @mysqli_query($conn,"ALTER TABLE categories ADD COLUMN parent_id INT DEFAULT 0 AFTER id");
    if(!table_column_exists($conn,'categories','banner_image')) @mysqli_query($conn,"ALTER TABLE categories ADD COLUMN banner_image VARCHAR(255) AFTER image");
    if(!table_column_exists($conn,'orders','province')) @mysqli_query($conn,"ALTER TABLE orders ADD COLUMN province VARCHAR(120) AFTER city");
    if(!table_column_exists($conn,'orders','delivery_fee')) @mysqli_query($conn,"ALTER TABLE orders ADD COLUMN delivery_fee DECIMAL(12,2) DEFAULT 0 AFTER total");
    if(!table_column_exists($conn,'orders','subtotal')) @mysqli_query($conn,"ALTER TABLE orders ADD COLUMN subtotal DECIMAL(12,2) DEFAULT 0 AFTER address");
    if(!table_column_exists($conn,'orders','map_link')) @mysqli_query($conn,"ALTER TABLE orders ADD COLUMN map_link TEXT AFTER address");
    if(!table_index_exists($conn,'products','idx_status_cat')) @mysqli_query($conn,"ALTER TABLE products ADD INDEX idx_status_cat(status,category_id,id)");
    if(!table_index_exists($conn,'products','idx_status_new')) @mysqli_query($conn,"ALTER TABLE products ADD INDEX idx_status_new(status,is_new,id)");
    if(!table_index_exists($conn,'products','idx_status_hot')) @mysqli_query($conn,"ALTER TABLE products ADD INDEX idx_status_hot(status,is_hot,discount_percent,id)");
    if(!table_index_exists($conn,'product_images','idx_product_sort')) @mysqli_query($conn,"ALTER TABLE product_images ADD INDEX idx_product_sort(product_id,sort_order,id)");
    if(!table_index_exists($conn,'categories','idx_parent_status')) @mysqli_query($conn,"ALTER TABLE categories ADD INDEX idx_parent_status(parent_id,status,sort_order,id)");
    if(!table_index_exists($conn,'orders','idx_orders_status_date')) @mysqli_query($conn,"ALTER TABLE orders ADD INDEX idx_orders_status_date(status,created_at,id)");
}
function delivery_zones(){
    return array(
        'mosul_right'=>array('ar'=>'موصل جانب أيمن','en'=>'Mosul Right Side','ku'=>'مووسڵ لای ڕاست','fee'=>3000),
        'mosul_left'=>array('ar'=>'موصل جانب أيسر','en'=>'Mosul Left Side','ku'=>'مووسڵ لای چەپ','fee'=>2000),
        'baghdad'=>array('ar'=>'بغداد','en'=>'Baghdad','ku'=>'بەغدا','fee'=>5000),
        'erbil'=>array('ar'=>'أربيل','en'=>'Erbil','ku'=>'هەولێر','fee'=>5000),
        'duhok'=>array('ar'=>'دهوك','en'=>'Duhok','ku'=>'دهۆک','fee'=>5000),
        'sulaymaniyah'=>array('ar'=>'السليمانية','en'=>'Sulaymaniyah','ku'=>'سلێمانی','fee'=>5000),
        'kirkuk'=>array('ar'=>'كركوك','en'=>'Kirkuk','ku'=>'کەرکووک','fee'=>5000),
        'other'=>array('ar'=>'بقية المحافظات','en'=>'Other provinces','ku'=>'پارێزگاکانی تر','fee'=>5000)
    );
}
function delivery_label($key,$lang){ $z=delivery_zones(); if(!isset($z[$key])) $key='other'; return isset($z[$key][$lang])?$z[$key][$lang]:$z[$key]['en']; }
function delivery_fee_for($key){ $z=delivery_zones(); if(!isset($z[$key])) return 5000; return (float)$z[$key]['fee']; }

function clean_upload_path($p, $fallback='assets/images/products/no-image.svg'){
    $p = trim((string)$p);
    if ($p === '') return $fallback;
    $p = str_replace('\\','/',$p); $p = ltrim($p,'/');
    if (preg_match('#^https?://#i',$p)) return $p;
    if (!file_exists(__DIR__.'/../'.$p)) return $fallback;
    return $p;
}
function localized($row,$field,$lang){ $k=$field.'_'.$lang; return isset($row[$k]) && $row[$k]!=='' ? $row[$k] : (isset($row[$field.'_en'])?$row[$field.'_en']:''); }
function category_name($c,$lang){ return localized($c,'name',$lang); }
function cart_count(){ $c=0; if(isset($_SESSION['cart']) && is_array($_SESSION['cart'])){ foreach($_SESSION['cart'] as $q){ $c += (int)$q; }} return $c; }
function cart_total($conn){
    $total=0;
    if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) return 0;
    foreach($_SESSION['cart'] as $pid=>$qty){
        $pid=(int)$pid; $qty=(int)$qty;
        $q=mysqli_query($conn,"SELECT price,discount_percent FROM products WHERE id=$pid LIMIT 1");
        if($q && mysqli_num_rows($q)){ $p=mysqli_fetch_assoc($q); $price=(float)$p['price']; $d=(float)$p['discount_percent']; if($d>0)$price=$price-($price*$d/100); $total += $price*$qty; }
    }
    return $total;
}
function first_image($conn, $pid){
    $pid=(int)$pid;
    $q=mysqli_query($conn,"SELECT image_path FROM product_images WHERE product_id=$pid ORDER BY sort_order ASC,id ASC LIMIT 1");
    if($q && mysqli_num_rows($q)){ $r=mysqli_fetch_assoc($q); return clean_upload_path($r['image_path']); }
    return 'assets/images/products/no-image.svg';
}
function product_images($conn,$pid){
    $pid=(int)$pid; $arr=array();
    $q=mysqli_query($conn,"SELECT image_path FROM product_images WHERE product_id=$pid ORDER BY sort_order ASC,id ASC");
    if($q){ while($r=mysqli_fetch_assoc($q)){ $arr[]=clean_upload_path($r['image_path']); }}
    if(!$arr) $arr[]='assets/images/products/no-image.svg';
    return $arr;
}
function category_product_image($conn,$category_id){
    $category_id=(int)$category_id;
    $ids=array($category_id);
    $subs=mysqli_query($conn,"SELECT id FROM categories WHERE parent_id=$category_id AND status=1");
    if($subs){ while($s=mysqli_fetch_assoc($subs)) $ids[]=(int)$s['id']; }
    $in=implode(',',array_map('intval',$ids));
    $q=mysqli_query($conn,"SELECT id FROM products WHERE status=1 AND category_id IN ($in) ORDER BY id DESC LIMIT 1");
    if($q && mysqli_num_rows($q)){ $p=mysqli_fetch_assoc($q); return first_image($conn,(int)$p['id']); }
    return 'assets/images/products/no-image.svg';
}
function redirect($url){ header('Location: '.$url); exit; }
function require_admin(){ if(!isset($_SESSION['admin_id'])) redirect('login.php'); }
function require_user(){ if(!isset($_SESSION['user_id'])) redirect('login.php'); }
function slugify($s){ $s=strtolower(trim($s)); $s=preg_replace('/[^a-z0-9]+/','-',$s); return trim($s,'-'); }
function upload_file($field, $dir){
    if(!isset($_FILES[$field]) || $_FILES[$field]['error']!=UPLOAD_ERR_OK) return '';
    $ext=strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
    if(!in_array($ext,array('jpg','jpeg','png','webp','gif','svg'))) return '';
    $name=date('YmdHis').'_'.mt_rand(1000,9999).'.'.$ext;
    $target=$dir.'/'.$name;
    if(!is_dir(__DIR__.'/../'.$dir)) mkdir(__DIR__.'/../'.$dir,0777,true);
    if(move_uploaded_file($_FILES[$field]['tmp_name'], __DIR__.'/../'.$target)) return $target;
    return '';
}
function upload_multi($field,$dir){
    $out=array();
    if(!isset($_FILES[$field]) || !is_array($_FILES[$field]['name'])) return $out;
    for($i=0;$i<count($_FILES[$field]['name']);$i++){
        if($_FILES[$field]['error'][$i]!=UPLOAD_ERR_OK) continue;
        $ext=strtolower(pathinfo($_FILES[$field]['name'][$i], PATHINFO_EXTENSION));
        if(!in_array($ext,array('jpg','jpeg','png','webp','gif','svg'))) continue;
        $name=date('YmdHis').'_'.mt_rand(1000,9999).'_'.$i.'.'.$ext;
        $target=$dir.'/'.$name;
        if(!is_dir(__DIR__.'/../'.$dir)) mkdir(__DIR__.'/../'.$dir,0777,true);
        if(move_uploaded_file($_FILES[$field]['tmp_name'][$i], __DIR__.'/../'.$target)) $out[]=$target;
    }
    return $out;
}


/* ====== Performance image helpers ====== */
function is_svg_path($p){ return preg_match('/\.svg(\?.*)?$/i', (string)$p); }
function thumb_url($path, $w=360, $h=360, $fit='contain'){
    $path = trim((string)$path);
    if ($path === '') return 'assets/images/products/no-image.svg';
    if (is_svg_path($path)) return $path;
    $w=(int)$w; $h=(int)$h; if($w<20)$w=360; if($h<20)$h=360; if($w>1600)$w=1600; if($h>1600)$h=1600;
    return 'thumb.php?src='.rawurlencode($path).'&w='.$w.'&h='.$h.'&fit='.rawurlencode($fit);
}
function img_attrs($path, $w=360, $h=360, $fit='contain'){
    return 'src="'.e(thumb_url($path,$w,$h,$fit)).'" loading="lazy" decoding="async"';
}

?>
