<?php
include_once '../db/koneksi.php';
header('Content-Type: application/json');

$action = $_POST['action'] ?? '';

function success($msg)
{
  echo json_encode(['success' => true, 'message' => $msg]);
  exit;
}
function fail($msg)
{
  echo json_encode(['success' => false, 'message' => $msg]);
  exit;
}

// function upload_file($field, $folder = "../asset/img/") {
//     if (!empty($_FILES[$field]['name'])) {
//         $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
//         $allowed = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'ico'];
//         if (in_array($ext, $allowed)) {
//             $new_name = uniqid() . '_' . basename($_FILES[$field]['name']);
//             $target = $folder . $new_name;
//             if (move_uploaded_file($_FILES[$field]['tmp_name'], $target)) {
//                 return $new_name;
//             }
//         }
//     }
//     return null;
// }

if ($action == 'update_info') {
  $judul = $_POST['judul_web'];
  $desc = $_POST['deskripsi_web'];
  $kata = $_POST['kata_kunci_web'];
  mysqli_query($koneksi, "UPDATE tb_web SET judul_web='$judul', deskripsi_web='$desc', kata_kunci_web='$kata'");
  success("Berhasil menyimpan informasi dasar.");
}

if ($action == 'update_logo') {
  foreach (['logo_web', 'favicon_web', 'logo_aplikasi_web'] as $fileKey) {
    if (!empty($_FILES[$fileKey]['name'])) {
      $rand = rand(100000, 999999);
      $ext = pathinfo($_FILES[$fileKey]['name'], PATHINFO_EXTENSION);
      $name = "{$rand}_{$fileKey}.{$ext}";
      $path = "../asset/img/{$name}";
      move_uploaded_file($_FILES[$fileKey]['tmp_name'], $path);
      mysqli_query($koneksi, "UPDATE tb_web SET $fileKey='$name'");
    }
  }
  success("Logo & favicon berhasil diperbarui.");
}

if ($action == 'update_popup') {
  $updateData = [];

  if (isset($_POST['teks_popup'])) {
    $teks_popup = mysqli_real_escape_string($koneksi, $_POST['teks_popup']);
    $updateData[] = "popup_pengumuman_link_alt='$teks_popup'";
  }

  if (isset($_POST['judul_popup'])) {
    $judul_popup = mysqli_real_escape_string($koneksi, $_POST['judul_popup']);
    $updateData[] = "judul_popup='$judul_popup'";
  }

  if (!empty($_FILES['popup_pengumuman_gambar']['name'])) {
    $rand = rand(100000, 999999);
    $ext = strtolower(pathinfo($_FILES['popup_pengumuman_gambar']['name'], PATHINFO_EXTENSION));
    $name = "{$rand}_popup_pengumuman_gambar.{$ext}";
    $path = "../asset/popup/{$name}";

    if (move_uploaded_file($_FILES['popup_pengumuman_gambar']['tmp_name'], $path)) {
      $updateData[] = "popup_pengumuman_gambar='$name'";
    } else {
      echo json_encode(['success' => false, 'message' => 'Gagal mengunggah gambar popup!']);
      exit;
    }
  }

  if (!empty($updateData)) {
    $query = "UPDATE tb_web SET " . implode(', ', $updateData);
    $update = mysqli_query($koneksi, $query);

    echo json_encode([
      'success' => $update,
      'message' => $update ? 'Popup berhasil diperbarui!' : 'Gagal memperbarui popup!'
    ]);
    exit;
  } else {
    echo json_encode(['success' => false, 'message' => 'Tidak ada data yang diubah!']);
    exit;
  }
}

if ($_POST['action'] == 'update_warna') {
    $primary = $_POST['primary_color'];
    $secondary = $_POST['secondary_color'];
    $tertiary = $_POST['tertiary_color'];

    mysqli_query($koneksi, "UPDATE tb_web SET 
        primary_color='$primary',
        secondary_color='$secondary',
        tertiary_color='$tertiary'
    ");

    echo json_encode(["success" => true, "message" => "Warna tema disimpan!"]);
    exit;
}

if ($action == 'update_sosmed') {
  $wa = $_POST['whatsapp'];
  $fb = $_POST['facebook'];
  $tg = $_POST['telegram'];
  $live = $_POST['link_livechat_web'];
  $script = $_POST['script_livechat_web'];
  mysqli_query($koneksi, "UPDATE tb_web SET whatsapp='$wa', facebook='$fb', telegram='$tg', link_livechat_web='$live', script_livechat_web='$script'");
  success("Sosial media & livechat diperbarui.");
}

if ($action == 'update_teks') {
  $t1 = $_POST['teks_berjalan_1'];
  $t2 = $_POST['teks_berjalan_2'];
  $t3 = $_POST['teks_berjalan_3'];
  mysqli_query($koneksi, "UPDATE tb_web SET teks_berjalan_1='$t1', teks_berjalan_2='$t2', teks_berjalan_3='$t3'");
  success("Teks berjalan berhasil disimpan.");
}

if ($action == 'update_rtp') {
  $awal = intval($_POST['rtp_awal']);
  $akhir = intval($_POST['rtp_akhir']);
  mysqli_query($koneksi, "UPDATE tb_web SET rtp_awal='$awal', rtp_akhir='$akhir'");
  success("RTP berhasil diperbarui.");
}

fail("Aksi tidak dikenali.");
