<?php
header("Content-Type: application/json; charset=utf-8");

// اتصال به دیتابیس با PDO
$dsn = "mysql:host=localhost;dbname=asiashop;charset=utf8";
$user = "root";
$pass = "";

try {
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
} catch (PDOException $e) {
    echo json_encode(["error" => $e->getMessage()]);
    exit;
}

// بررسی وجود id محصول
if (!isset($_GET['id'])) {
    echo json_encode(["error" => "Product ID required"]);
    exit;
}

$productId = intval($_GET['id']);
$uploadDir = __DIR__ . "/uploads/";

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// بررسی فایل‌ها
if (!isset($_FILES['photos'])) {
    echo json_encode(["error" => "No files uploaded"]);
    exit;
}

$newFiles = [];

foreach ($_FILES['photos']['tmp_name'] as $key => $tmpName) {
    if (!empty($tmpName) && is_uploaded_file($tmpName)) {
        $originalName = basename($_FILES['photos']['name'][$key]);
        $uniqueName = time() . "_" . uniqid() . "_" . $originalName;
        $targetPath = $uploadDir . $uniqueName;

        if (move_uploaded_file($tmpName, $targetPath)) {
            $newFiles[] = $uniqueName;
        }
    }
}

// واکشی رکورد محصول از دیتابیس
$stmt = $pdo->prepare("SELECT albums FROM products WHERE id = ?");
$stmt->execute([$productId]);

if ($stmt->rowCount() === 0) {
    echo json_encode(["error" => "Product not found"]);
    exit;
}

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$albums = [];

if (!empty($row['albums'])) {
    $decoded = json_decode($row['albums'], true);
    if (is_array($decoded)) {
        $albums = $decoded;
    }
}

// ادغام عکس‌های جدید با قبلی‌ها
$albums = array_merge($albums, $newFiles);
$albumsJson = json_encode($albums, JSON_UNESCAPED_UNICODE);

// بروزرسانی فیلد albums در دیتابیس
$update = $pdo->prepare("UPDATE products SET albums = ? WHERE id = ?");
$update->execute([$albumsJson, $productId]);

echo json_encode([
    "success" => true,
    "message" => "Albums updated successfully",
    "albums" => $albums
], JSON_UNESCAPED_UNICODE);
