<?php
// File: API_KONEKSI/customer/update_password.php
header('Content-Type: application/json');
include '../config/koneksi.php';
include '../config/middleware.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $payload = authenticateJWT();
    $user_id = $payload['user_id'] ?? '';
    $pass_lama = $_POST['pass_lama'] ?? '';
    $pass_baru = $_POST['pass_baru'] ?? '';

    if (empty($user_id) || empty($pass_lama) || empty($pass_baru)) {
        echo json_encode(["status" => "gagal", "pesan" => "Form kata sandi harus diisi lengkap!", "data" => []]);
        exit;
    }

    // 1. Cek password lama di database
    $query = "SELECT password_tx FROM mst_user WHERE user_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        $db_password = $row['password_tx'];
        
        // Cek kecocokan password (jika kamu pakai MD5 di login, ganti jadi md5($pass_lama) == $db_password)
        // Di sini saya asumsikan menggunakan standar hash bawaan PHP / md5 (sesuaikan dengan login.php mu)
        if (md5($pass_lama) === $db_password || password_verify($pass_lama, $db_password) || $pass_lama === $db_password) {
            
            // 2. Jika cocok, update dengan sandi baru
            $pass_baru_hashed = md5($pass_baru); // Sesuaikan enkripsi dengan login.php mu
            
            $query_update = "UPDATE mst_user SET password_tx = ? WHERE user_id = ?";
            $stmt_update = $conn->prepare($query_update);
            $stmt_update->bind_param("ss", $pass_baru_hashed, $user_id);
            
            if ($stmt_update->execute()) {
                echo json_encode(["status" => "sukses", "pesan" => "Kata sandi berhasil diperbarui!", "data" => []]);
            } else {
                echo json_encode(["status" => "gagal", "pesan" => "Gagal menyimpan kata sandi", "data" => []]);
            }
            $stmt_update->close();
        } else {
            echo json_encode(["status" => "gagal", "pesan" => "Kata sandi lama Anda salah!", "data" => []]);
        }
    }
    $stmt->close();
}
?>
