<?php
session_start();
include "connect.php";

// Validasi input
$passwordlama = (isset($_POST['passwordlama']) && !empty($_POST['passwordlama'])) ? $_POST['passwordlama'] : "";
$passwordbaru = (isset($_POST['passwordbaru']) && !empty($_POST['passwordbaru'])) ? $_POST['passwordbaru'] : "";
$repasswordbaru = (isset($_POST['repasswordbaru']) && !empty($_POST['repasswordbaru'])) ? $_POST['repasswordbaru'] : "";
$username = $_SESSION['username_bangblake'];

// Debug: Uncomment untuk testing
// echo "Password lama: " . $passwordlama . "<br>";
// echo "Username: " . $username . "<br>";
// exit;

if (!empty($_POST['ubah_password_validate'])) {
    // Validasi input kosong
    if (empty($passwordlama) || empty($passwordbaru) || empty($repasswordbaru)) {
        $message = '<script>alert("Semua field harus diisi"); window.history.back()</script>';
    } else {
        // Hash password lama untuk pengecekan
        $passwordlama_hash = md5($passwordlama);
        
        // Gunakan prepared statement untuk keamanan
        $stmt = $conn->prepare("SELECT * FROM tb_user WHERE username = ? AND password = ?");
        $stmt->bind_param("ss", $username, $passwordlama_hash);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            // Password lama benar, cek apakah password baru sama
            if ($passwordbaru == $repasswordbaru) {
                // Hash password baru
                $passwordbaru_hash = md5($passwordbaru);
                
                // Update password
                $update_stmt = $conn->prepare("UPDATE tb_user SET password = ? WHERE username = ?");
                $update_stmt->bind_param("ss", $passwordbaru_hash, $username);
                
                if ($update_stmt->execute()) {
                    $message = '<script>alert("Password berhasil diubah"); window.history.back()</script>';
                } else {
                    $message = '<script>alert("Password gagal diubah"); window.history.back()</script>';
                }
                $update_stmt->close();
            } else {
                $message = '<script>alert("Password baru tidak sama"); window.history.back()</script>';
            }
        } else {
            $message = '<script>alert("Password lama tidak sesuai"); window.history.back()</script>';
        }
        $stmt->close();
    }
} else {
    header('location:../home');
}

echo $message;
?>