<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: POST");

$host = "localhost";
$user = "wanywebc_baski";
$pass = "Adgebs123.";
$db   = "wanywebc_baski";

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
  echo json_encode(["success" => false, "message" => "Veritabanı bağlantı hatası"]);
  exit;
}

$id = intval($_POST["id"] ?? 0);
if ($id <= 0) {
  echo json_encode(["success" => false, "message" => "Geçersiz ürün ID"]);
  exit;
}

$ad         = $_POST["ad"] ?? "";
$aciklama   = $_POST["aciklama"] ?? "";
$spot       = $_POST["spot_aciklama"] ?? "";
$yeni_fiyat = floatval($_POST["yeni_fiyat"] ?? 0);
$kapakIndex = intval($_POST["kapakIndex"] ?? 0);

// Mevcut görselleri JSON'dan diziye dönüştür
$mevcutGorseller = [];
if (isset($_POST["mevcutGorseller"])) {
  $decoded = json_decode($_POST["mevcutGorseller"], true);
  if (is_array($decoded)) {
    $mevcutGorseller = $decoded;
  }
}

// Yeni görseller yüklenirse ekle
$uploadDir = "../uploads/";
if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);

$yeniGorseller = [];

if (isset($_FILES["gorseller"])) {
  foreach ($_FILES["gorseller"]["tmp_name"] as $i => $tmpName) {
    if ($_FILES["gorseller"]["error"][$i] === 0) {
      $orijinalAd = basename($_FILES["gorseller"]["name"][$i]);
      $yeniAd = uniqid() . "_" . $orijinalAd;
      $hedefYol = $uploadDir . $yeniAd;

      if (move_uploaded_file($tmpName, $hedefYol)) {
        $yeniGorseller[] = "/uploads/" . $yeniAd;
      }
    }
  }
}

$gorselYollari = array_merge($mevcutGorseller, $yeniGorseller);

if (count($gorselYollari) === 0) {
  echo json_encode(["success" => false, "message" => "Hiç görsel kalmadı"]);
  exit;
}

// Kapak görselini belirle
$kapakGorsel = $gorselYollari[$kapakIndex] ?? $gorselYollari[0];

// Güncelle
$gorselJson = json_encode($gorselYollari);
$stmt = $conn->prepare("UPDATE urunler SET ad = ?, aciklama = ?, spot_aciklama = ?, yeni_fiyat = ?, gorsel_yolu = ?, kapak_gorsel = ? WHERE id = ?");
$stmt->bind_param("sssddsi", $ad, $aciklama, $spot, $yeni_fiyat, $gorselJson, $kapakGorsel, $id);

if ($stmt->execute()) {
  echo json_encode(["success" => true]);
} else {
  echo json_encode(["success" => false, "message" => $conn->error]);
}

$conn->close();
?>