<?php
// File: proses_rubah_sandi.php
// Lokasi: Server Lokal

header('Content-Type: application/json');

// --- Konfigurasi Database Lokal ---
// Ambil data JSON dari request
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? null;

include_once 'data.php';
$conn = new mysqli($servername, $username, $password, $dbname);



if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Koneksi database gagal.']);
    exit;
}

if ($action === 'verify') {
    $userid = $input['userid'];
    $old_password = $input['old_password'];

    $stmt = $conn->prepare("SELECT password FROM users WHERE username = ?");
    $stmt->bind_param("s", $userid);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
        // PERINGATAN: Ini hanya perbandingan teks biasa.
        // Di sistem produksi, gunakan password_verify()
        if ($old_password === $user['password']) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Password saat ini salah.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'User ID tidak ditemukan.']);
    }
    $stmt->close();

} elseif ($action === 'update') {
    $userid = $input['userid'];
    $new_password = $input['new_password'];

    // PERINGATAN: Simpan password sebagai hash di sistem produksi
    // $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("UPDATE users SET password = ? WHERE username = ?");
    $stmt->bind_param("ss", $new_password, $userid);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Password berhasil diubah!']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal memperbarui password.']);
    }
    $stmt->close();
}

$conn->close();
?>