<?php
// File: /admin/proses_setting.php
session_start();
if (!isset($_SESSION['admin'])) {
  header("Location: login.php");
  exit;
}

include '../config/koneksi.php';

// Ambil data input
$nama_madrasah = $_POST['nama_madrasah'];
$tagline        = $_POST['tagline'];
$alamat         = $_POST['alamat'];
$telepon        = $_POST['telepon'];
$email          = $_POST['email'];
$facebook       = $_POST['facebook'];
$instagram      = $_POST['instagram'];
$whatsapp       = $_POST['whatsapp'];
$x              = $_POST['x'];

// Cek apakah ada logo baru diupload
$logo_name = null;
if (isset($_FILES['logo']) && $_FILES['logo']['error'] == UPLOAD_ERR_OK) {
  $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
  $file_size = $_FILES['logo']['size'];
  $allowed = ['jpg', 'jpeg', 'png'];

  // Validasi format
  if (!in_array($ext, $allowed)) {
    echo "<script>alert('Format file tidak valid. Hanya JPG/PNG yang diperbolehkan.'); window.history.back();</script>";
    exit;
  }

  // Validasi ukuran (max 1MB)
  if ($file_size > 1048576) {
    echo "<script>alert('Ukuran file terlalu besar. Maksimal 1MB.'); window.history.back();</script>";
    exit;
  }

  // Nama file baru
  $logo_name = 'logo_' . time() . '.' . $ext;
  $upload_path = '../uploads/logo/' . $logo_name;

  // Pastikan folder ada
  if (!is_dir('../uploads/logo/')) {
    mkdir('../uploads/logo/', 0777, true);
  }

  // Hapus logo lama jika ada
  $old_logo = mysqli_fetch_assoc(mysqli_query($conn, "SELECT logo FROM setting LIMIT 1"));
  if (!empty($old_logo['logo']) && file_exists("../uploads/logo/" . $old_logo['logo'])) {
    unlink("../uploads/logo/" . $old_logo['logo']);
  }

  // Upload file baru
  if (!move_uploaded_file($_FILES['logo']['tmp_name'], $upload_path)) {
    echo "<script>alert('Gagal mengupload logo baru.'); window.history.back();</script>";
    exit;
  }
}

// Update ke database
$sql = "UPDATE setting SET
  nama_madrasah = '$nama_madrasah',
  tagline = '$tagline',
  alamat = '$alamat',
  telepon = '$telepon',
  email = '$email',
  facebook = '$facebook',
  instagram = '$instagram',
  whatsapp = '$whatsapp',
  x = '$x'";

if ($logo_name) {
  $sql .= ", logo = '$logo_name'";
}

$sql .= " LIMIT 1";

if (mysqli_query($conn, $sql)) {
  echo "<script>alert('Pengaturan berhasil disimpan.'); window.location='setting.php';</script>";
} else {
  echo "<script>alert('Gagal menyimpan pengaturan!'); window.history.back();</script>";
}