<?php
// ------------------- افزودن یا ویرایش آیتم -------------------
if (isset($_POST['action']) && in_array($_POST['action'], ['addItem','editItem'])) {
    require_once "config.php";
    require_once "functions.php";

    $id       = $_POST['CategoryID'] ?? null;
    $price    = $_POST['Price'] ?? null;
    $desc_fa  = $_POST['Description_fa'] ?? '';
    $desc_en  = $_POST['Description_en'] ?? '';
    $desc_tr  = $_POST['Description_tr'] ?? '';
    $action   = $_POST['action'];

    // مسیر پوشه آپلود
    $uploadDir = __DIR__ . "/uploads/";
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
    $imagePath = null;

    // اگر فایلی آپلود شده
    if (!empty($_FILES['Image']['name'])) {
        $ext = pathinfo($_FILES['Image']['name'], PATHINFO_EXTENSION);
        $fileName = uniqid("img_") . "." . $ext;
        $targetPath = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES['Image']['tmp_name'], $targetPath)) {
            resizeAndCropImage($targetPath, $targetPath);
            $imagePath = "uploads/" . $fileName;
        }
    }

    if ($action === 'addItem') {
        // درج آیتم جدید
        $st = $pdo->prepare("INSERT INTO ItemDetail (CategoryID, Price, Image) VALUES (:c, :p, :i)");
        $st->execute([':c'=>$id, ':p'=>$price, ':i'=>$imagePath]);

        // درج ترجمه‌ها
        $insert = $pdo->prepare("INSERT INTO CategoryTranslation (CategoryID, LanguageCode, Description) VALUES (:c,:l,:d)");
        $insert->execute([':c'=>$id,':l'=>'fa',':d'=>$desc_fa]);
        $insert->execute([':c'=>$id,':l'=>'en',':d'=>$desc_en]);
        $insert->execute([':c'=>$id,':l'=>'tr',':d'=>$desc_tr]);

        echo json_encode(['status'=>'success','msg'=>'آیتم جدید اضافه شد.']);
    }

    if ($action === 'editItem') {
        // ویرایش آیتم
        $sql = "UPDATE ItemDetail SET Price=:p";
        $params = [':p'=>$price, ':c'=>$id];
        if ($imagePath) { 
            $sql .= ", Image=:i"; 
            $params[':i']=$imagePath;
        }
        $sql .= " WHERE CategoryID=:c";
        $st = $pdo->prepare($sql);
        $st->execute($params);

        // بروزرسانی ترجمه‌ها
        $upd = $pdo->prepare("UPDATE CategoryTranslation SET Description=:d WHERE CategoryID=:c AND LanguageCode=:l");
        $upd->execute([':d'=>$desc_fa,':c'=>$id,':l'=>'fa']);
        $upd->execute([':d'=>$desc_en,':c'=>$id,':l'=>'en']);
        $upd->execute([':d'=>$desc_tr,':c'=>$id,':l'=>'tr']);

        echo json_encode(['status'=>'success','msg'=>'آیتم ویرایش شد.']);
    }
    exit;
}

// ------------------- حذف آیتم -------------------
if (isset($_POST['action']) && $_POST['action'] === 'deleteItem') {
    require_once "config.php";

    $id = $_POST['CategoryID'] ?? null;
    if (!$id) exit(json_encode(['status'=>'error','msg'=>'آی‌دی نامعتبر است']));

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

    // حذف آیتم
    $pdo->prepare("DELETE FROM ItemDetail WHERE CategoryID=:c")->execute([':c'=>$id]);
    $pdo->prepare("DELETE FROM CategoryTranslation WHERE CategoryID=:c")->execute([':c'=>$id]);

    echo json_encode(['status'=>'success','msg'=>'آیتم حذف شد.']);
    exit;
}

// ------------------- حذف تصویر آیتم -------------------
if (isset($_POST['action']) && $_POST['action'] === 'deleteImage') {
    require_once "config.php";

    $id = $_POST['CategoryID'] ?? null;
    if (!$id) exit(json_encode(['status'=>'error','msg'=>'آی‌دی نامعتبر است']));

    $st = $pdo->prepare("SELECT Image FROM ItemDetail WHERE CategoryID=:c");
    $st->execute([':c'=>$id]);
    $img = $st->fetchColumn();

    if ($img && file_exists(__DIR__ . "/" . $img)) {
        unlink(__DIR__ . "/" . $img);
    }

    $pdo->prepare("UPDATE ItemDetail SET Image=NULL WHERE CategoryID=:c")->execute([':c'=>$id]);

    echo json_encode(['status'=>'success','msg'=>'تصویر حذف شد.']);
    exit;
}
