<?php
require '../config.php';
session_start();

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

$id = $_SESSION['user_id'];
$peran = $_SESSION['peran']; // 'admin' atau 'pelanggan'

// Tentukan halaman redirect berdasarkan peran
$redirect_page = ($peran === 'admin') ? '../admin/profile.php' : '../pelanggan/profile.php';

$password_lama = $_POST['password_lama'];
$password_baru = $_POST['password_baru'];
$konfirmasi_password = $_POST['konfirmasi_password'];

// Ambil password saat ini dari DB
$query = mysqli_query($conn, "SELECT password FROM pengguna WHERE id = $id");
$data = mysqli_fetch_assoc($query);
$password_db = $data['password'];

// Validasi password lama
if (!password_verify($password_lama, $password_db)) {
  echo "<script>alert('Password lama salah!'); window.location='$redirect_page';</script>";
  exit;
}

// Validasi konfirmasi password
if ($password_baru !== $konfirmasi_password) {
  echo "<script>alert('Konfirmasi password tidak cocok!'); window.location='$redirect_page';</script>";
  exit;
}

// Enkripsi dan update password baru
$password_hash = password_hash($password_baru, PASSWORD_DEFAULT);
mysqli_query($conn, "UPDATE pengguna SET password = '$password_hash' WHERE id = $id");

echo "<script>alert('Password berhasil diubah!'); window.location='$redirect_page';</script>";
