<?php
session_start();
include '../config/koneksi.php';

if (!isset($_SESSION['admin'])) {
  header("Location: login.php");
  exit;
}

$id = $_SESSION['admin'];

if (isset($_FILES['foto']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
  $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];
  $file_name = $_FILES['foto']['name'];
  $file_tmp  = $_FILES['foto']['tmp_name'];
  $file_ext  = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

  if (!in_array($file_ext, $allowed_ext)) {
    $_SESSION['error'] = 'Format file tidak diizinkan.';
    header("Location: pengguna.php");
    exit;
  }

  $new_name = 'admin_' . $id . '_' . time() . '.' . $file_ext;
  $folder = 'assets/adminLTE/dist/img/foto-profil';
  if (!is_dir($folder)) mkdir($folder, 0777, true);
  $destination = $folder . '/' . $new_name;

  if (move_uploaded_file($file_tmp, $destination)) {
    $result = mysqli_query($conn, "SELECT foto FROM admin WHERE id='$id'");
    $admin  = mysqli_fetch_assoc($result);
    if ($admin['foto'] !== 'default.jpg' && file_exists($folder . '/' . $admin['foto'])) {
      unlink($folder . '/' . $admin['foto']);
    }

    mysqli_query($conn, "UPDATE admin SET foto = '$new_name' WHERE id = '$id'");
    $_SESSION['success'] = "Foto profil berhasil diperbarui.";
  } else {
    $_SESSION['error'] = "Gagal mengunggah foto.";
  }
} else {
  $_SESSION['error'] = "Tidak ada file yang diunggah.";
}

header("Location: pengguna.php");
exit;