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

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

$id = $_SESSION['admin']['id'];
$password_lama = $_POST['password_lama'];
$password_baru = $_POST['password_baru'];
$konfirmasi    = $_POST['konfirmasi_password'];

// Validasi konfirmasi password
if ($password_baru !== $konfirmasi) {
  $_SESSION['error'] = "Konfirmasi password tidak sesuai.";
  header("Location: pengguna.php");
  exit;
}

// Ambil password lama dari database
$query = mysqli_query($conn, "SELECT password FROM admin WHERE id = '$id'");
$data  = mysqli_fetch_assoc($query);

if (!$data) {
  $_SESSION['error'] = "Data pengguna tidak ditemukan.";
  header("Location: pengguna.php");
  exit;
}

// Validasi password lama
if (!password_verify($password_lama, $data['password'])) {
  $_SESSION['error'] = "Password lama salah.";
  header("Location: pengguna.php");
  exit;
}

// Hash password baru
$password_hash = password_hash($password_baru, PASSWORD_DEFAULT);

// Update password
if (mysqli_query($conn, "UPDATE admin SET password = '$password_hash' WHERE id = '$id'")) {
  $_SESSION['success'] = "Password berhasil diperbarui.";
} else {
  $_SESSION['error'] = "Terjadi kesalahan saat memperbarui password.";
}

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