<?php
// ذخیره ترتیب
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='save_order') {
    header('Content-Type: application/json; charset=utf-8');
    $level = (int)($_POST['level'] ?? 0);
    $parent_id = $_POST['parent_id']!=='' ? (int)$_POST['parent_id'] : null;
    $order = $_POST['order'] ?? [];

    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("UPDATE Category SET SortOrder=:sort, ParentID=:parent, Level=:level WHERE CategoryID=:id");
        $s=1;
        foreach($order as $id){
            $stmt->execute([':sort'=>$s++, ':parent'=>$parent_id, ':level'=>$level, ':id'=>(int)$id]);
        }
        $pdo->commit();
        echo json_encode(['success'=>true]);
    } catch(Exception $e){
        $pdo->rollBack();
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
    }
    exit;
}

// حذف دسته
function deleteCategory(PDO $pdo, int $id){
    $stmt = $pdo->prepare("SELECT Image FROM ItemDetail WHERE CategoryID=:id");
    $stmt->execute([':id'=>$id]);
    $img = $stmt->fetchColumn();
    if($img && file_exists(__DIR__.'/'.$img)) unlink(__DIR__.'/'.$img);

    $pdo->prepare("DELETE FROM ItemDetail WHERE CategoryID=:id")->execute([':id'=>$id]);
    $pdo->prepare("DELETE FROM CategoryTranslation WHERE CategoryID=:id")->execute([':id'=>$id]);

    $subs = $pdo->prepare("SELECT CategoryID FROM Category WHERE ParentID=:id");
    $subs->execute([':id'=>$id]);
    foreach($subs->fetchAll(PDO::FETCH_COLUMN) as $sub){
        deleteCategory($pdo,(int)$sub);
    }
    $pdo->prepare("DELETE FROM Category WHERE CategoryID=:id")->execute([':id'=>$id]);
}

if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='delete_category'){
    header('Content-Type: application/json; charset=utf-8');
    $id = (int)$_POST['id'];
    try{
        $pdo->beginTransaction();
        deleteCategory($pdo,$id);
        $pdo->commit();
        echo json_encode(['success'=>true]);
    }catch(Exception $e){
        $pdo->rollBack();
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
    }
    exit;
}

// افزودن دسته
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='add_category'){
    header('Content-Type: application/json; charset=utf-8');
    $parent_id = $_POST['parent_id']!=='' ? (int)$_POST['parent_id'] : null;
    $level = (int)$_POST['level'];
    $langs=['fa','en','tr','ar'];

    try{
        $pdo->beginTransaction();
        $stmt=$pdo->prepare("INSERT INTO Category (ParentID,Level,SortOrder) VALUES (:p,:lvl,0)");
        $stmt->execute([':p'=>$parent_id,':lvl'=>$level]);
        $cat_id=$pdo->lastInsertId();

        foreach($langs as $lg){
            $name=$_POST["name_$lg"] ?? '';
            $stmt=$pdo->prepare("INSERT INTO CategoryTranslation (CategoryID,LanguageCode,Name) VALUES (:id,:lg,:name)");
            $stmt->execute([':id'=>$cat_id,':lg'=>$lg,':name'=>$name]);
        }
        $pdo->commit();
        echo json_encode(['success'=>true]);
    }catch(Exception $e){
        $pdo->rollBack();
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
    }
    exit;
}

// ویرایش دسته
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='edit_category'){
    header('Content-Type: application/json; charset=utf-8');
    $id=(int)$_POST['id'];
    $langs=['fa','en','tr','ar'];

    try{
        $pdo->beginTransaction();
        foreach($langs as $lg){
            $name=$_POST["name_$lg"] ?? '';
            $stmt=$pdo->prepare("INSERT INTO CategoryTranslation (CategoryID,LanguageCode,Name)
                                 VALUES (:id,:lg,:name) ON DUPLICATE KEY UPDATE Name=:name");
            $stmt->execute([':id'=>$id,':lg'=>$lg,':name'=>$name]);
        }
        $pdo->commit();
        echo json_encode(['success'=>true]);
    }catch(Exception $e){
        $pdo->rollBack();
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
    }
    exit;
}

// ------------------- افزودن / ویرایش آیتم سطح ۳ -------------------
function resizeAndCropImage($sourcePath,$targetPath,$targetWidth=600,$targetHeight=600){
    $info=getimagesize($sourcePath); if(!$info) return false;
    $width=$info[0]; $height=$info[1]; $mime=$info['mime'];
    switch($mime){
        case 'image/jpeg':$img=imagecreatefromjpeg($sourcePath);break;
        case 'image/png':$img=imagecreatefrompng($sourcePath);break;
        case 'image/gif':$img=imagecreatefromgif($sourcePath);break;
        default:return false;
    }
    $src_ratio=$width/$height; $dst_ratio=$targetWidth/$targetHeight;
    if($src_ratio>$dst_ratio){$new_height=$height;$new_width=$height*$dst_ratio;$src_x=($width-$new_width)/2;$src_y=0;}
    else{$new_width=$width;$new_height=$width/$dst_ratio;$src_x=0;$src_y=($height-$new_height)/2;}
    $dst_img=imagecreatetruecolor($targetWidth,$targetHeight);
    if($mime==='image/png'||$mime==='image/gif'){
        imagecolortransparent($dst_img,imagecolorallocatealpha($dst_img,0,0,0,127));
        imagealphablending($dst_img,false);imagesavealpha($dst_img,true);
    }
    imagecopyresampled($dst_img,$img,0,0,$src_x,$src_y,$targetWidth,$targetHeight,$new_width,$new_height);
    switch($mime){
        case 'image/jpeg':imagejpeg($dst_img,$targetPath,85);break;
        case 'image/png':imagepng($dst_img,$targetPath,6);break;
        case 'image/gif':imagegif($dst_img,$targetPath);break;
    }
    imagedestroy($img); imagedestroy($dst_img); return true;
}

if ($_SERVER['REQUEST_METHOD']==='POST' && in_array($_POST['action']??'',['add_item','edit_item'])){
    header('Content-Type: application/json; charset=utf-8');
    $action=$_POST['action'];
    $parent_id=(int)($_POST['parent_id']??0);
    $id=(int)($_POST['id']??0);
    $langs=['fa','en','tr','ar'];
    $price=$_POST['price']??null;
    $image=null;
    $uploadDir=__DIR__."/uploads/";
    if(!is_dir($uploadDir)) mkdir($uploadDir,0777,true);

    // آپلود تصویر جدید
    if(!empty($_FILES['image']['name'])){
        $file=$_FILES['image'];
        if($file['error']===UPLOAD_ERR_OK){
            $filename=time()."_".rand(1000,9999).".".pathinfo($file['name'],PATHINFO_EXTENSION);
            $target=$uploadDir.$filename;
            if(resizeAndCropImage($file['tmp_name'],$target,600,600)) $image="uploads/".$filename;
            else {echo json_encode(['success'=>false,'message'=>'خطا در پردازش تصویر']); exit;}
        }else{echo json_encode(['success'=>false,'message'=>'خطای آپلود فایل']); exit;}
    }

    try{
        $pdo->beginTransaction();

        if($action==='add_item'){
            // دسته جدید برای آیتم
            $stmt=$pdo->prepare("INSERT INTO Category (ParentID,Level,SortOrder) VALUES (:p,3,0)");
            $stmt->execute([':p'=>$parent_id]); 
            $cat_id=$pdo->lastInsertId();

            foreach($langs as $lg){
                $name=$_POST["name_$lg"]??''; 
                $desc=$_POST["desc_$lg"]??'';
                $stmt=$pdo->prepare("INSERT INTO CategoryTranslation (CategoryID,LanguageCode,Name,Description) VALUES (:id,:lg,:name,:desc)");
                $stmt->execute([':id'=>$cat_id,':lg'=>$lg,':name'=>$name,':desc'=>$desc]);
            }

            $stmt=$pdo->prepare("INSERT INTO ItemDetail (CategoryID,Price,Image,SortOrder) VALUES (:cid,:pr,:img,0)");
            $stmt->execute([':cid'=>$cat_id,':pr'=>$price,':img'=>$image]);

        }elseif($action==='edit_item'){
            foreach($langs as $lg){
                $name=$_POST["name_$lg"]??''; 
                $desc=$_POST["desc_$lg"]??'';
                $stmt=$pdo->prepare("INSERT INTO CategoryTranslation (CategoryID,LanguageCode,Name,Description)
                                     VALUES (:id,:lg,:name,:desc)
                                     ON DUPLICATE KEY UPDATE Name=:name, Description=:desc");
                $stmt->execute([':id'=>$id,':lg'=>$lg,':name'=>$name,':desc'=>$desc]);
            }

            // حذف تصویر
            if(!empty($_POST['delete_image'])){
                $stmt=$pdo->prepare("SELECT Image FROM ItemDetail WHERE CategoryID=:cid");
                $stmt->execute([':cid'=>$id]);
                $oldImg=$stmt->fetchColumn();
                if($oldImg && file_exists(__DIR__.'/'.$oldImg)) unlink(__DIR__.'/'.$oldImg);

                $stmt=$pdo->prepare("UPDATE ItemDetail SET Price=:pr, Image=NULL WHERE CategoryID=:cid");
                $stmt->execute([':cid'=>$id,':pr'=>$price]);
            }
            // اگر تصویر جدید آپلود شده
            elseif($image){
                $stmt=$pdo->prepare("UPDATE ItemDetail SET Price=:pr,Image=:img WHERE CategoryID=:cid");
                $stmt->execute([':cid'=>$id,':pr'=>$price,':img'=>$image]);
            }
            // فقط قیمت تغییر کرده
            else{
                $stmt=$pdo->prepare("UPDATE ItemDetail SET Price=:pr WHERE CategoryID=:cid");
                $stmt->execute([':cid'=>$id,':pr'=>$price]);
            }
        }

        $pdo->commit(); 
        echo json_encode(['success'=>true]);
    }catch(Exception $e){
        $pdo->rollBack(); 
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
    }
    exit;
}
// ------------------- حذف آیتم -------------------
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='delete_item'){
    header('Content-Type: application/json; charset=utf-8');
    $id=(int)$_POST['id'];
    try{
        $pdo->beginTransaction();

        // حذف فایل تصویر
        $stmt=$pdo->prepare("SELECT Image FROM ItemDetail WHERE CategoryID=:id");
        $stmt->execute([':id'=>$id]);
        $img=$stmt->fetchColumn();
        if($img && file_exists(__DIR__.'/'.$img)) unlink(__DIR__.'/'.$img);

        $pdo->prepare("DELETE FROM ItemDetail WHERE CategoryID=:id")->execute([':id'=>$id]);
        $pdo->prepare("DELETE FROM CategoryTranslation WHERE CategoryID=:id")->execute([':id'=>$id]);
        $pdo->prepare("DELETE FROM Category WHERE CategoryID=:id")->execute([':id'=>$id]);

        $pdo->commit(); 
        echo json_encode(['success'=>true]);
    }catch(Exception $e){
        $pdo->rollBack(); 
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
    }
    exit;
}




