<?php
include '../auth.php';
include '../../koneksi.php';

$user_id = $_SESSION['user_id'];

$currentPassword = $newPassword = $renewPassword = "";

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get and sanitize the input data
    $currentPassword = trim($_POST['password']);
    $newPassword = trim($_POST['newpassword']);
    $renewPassword = trim($_POST['renewpassword']);

    // Simpan input lama jika terjadi error
    $_SESSION['old_input'] = $_POST;

    // Validasi semua kolom harus diisi
    if (empty($currentPassword) || empty($newPassword) || empty($renewPassword)) {
        $_SESSION['error'] = "Semua kolom kata sandi harus diisi!";
        header("Location: ./");
        exit();
    }

    // Fetch the current password from the database
    $sql = "SELECT password FROM users WHERE id_user = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {
        $_SESSION['error'] = "Pengguna tidak ditemukan!";
        header("Location: ./");
        exit();
    }

    // Bind the result (current password)
    $stmt->bind_result($dbPassword);
    $stmt->fetch();
    $stmt->close();

    // Cek apakah password saat ini cocok dengan database
    if (!password_verify($currentPassword, $dbPassword)) {
        $_SESSION['error'] = "Kata sandi saat ini salah!";
        header("Location: ./");
        exit();
    }

        // Validasi panjang password minimal 8 karakter
        if (strlen($newPassword) < 8) {
            $_SESSION['error'] = "Kata sandi baru harus minimal 8 karakter!";
            header("Location: ./");
            exit();
        }
    
        // Validasi kecocokan password baru dan konfirmasi password
        if ($newPassword !== $renewPassword) {
            $_SESSION['error'] = "Kata sandi baru dan konfirmasi kata sandi tidak cocok!";
            header("Location: ./");
            exit();
        }    

    // Cek apakah sandi baru tidak sama dengan sandi lama
    if (password_verify($newPassword, $dbPassword)) {
        $_SESSION['error'] = "Kata sandi baru tidak boleh sama dengan kata sandi lama!";
        header("Location: ./");
        exit();
    }

    // Hash password baru sebelum disimpan
    $hashedNewPassword = password_hash($newPassword, PASSWORD_DEFAULT);

    // Update password dalam database
    $sql = "UPDATE users SET password = ? WHERE id_user = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $hashedNewPassword, $user_id);

    if ($stmt->execute()) {
        $_SESSION['success'] = "Kata sandi berhasil diperbarui!";
        unset($_SESSION['old_input']); // Hapus old input setelah sukses
        header("Location: ./");
        exit();
    } else {
        $_SESSION['error'] = "Terjadi kesalahan saat memperbarui kata sandi!";
        header("Location: ./");
        exit();
    }

    $stmt->close();
}

$conn->close();
?>
