<?php
require_once('connection.php');

// Cek koneksi database
if ($con->connect_error) {
    die(json_encode(array('status' => 'error', 'message' => 'Database connection failed: ' . $con->connect_error)));
}

// Respon default
$response = array('status' => 'error', 'message' => 'Invalid request');

// Pastikan permintaan menggunakan metode POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil data dari body request
    $phoneNumber = isset($_POST['phoneNumber']) ? trim($_POST['phoneNumber']) : '';
    $newPassword = isset($_POST['pin']) ? trim($_POST['pin']) : '';

    // Validasi input
    if (!empty($phoneNumber) && !empty($newPassword)) {
        // Hash password dengan algoritma bcrypt
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

        // Prepared statement untuk update PIN
        $stmt = $con->prepare("UPDATE nasabah SET pin = ? WHERE phoneNumber = ?");
        $stmt->bind_param("ss", $hashedPassword, $phoneNumber);

        // Eksekusi query dan cek hasil
        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                $response['status'] = 'success';
                $response['message'] = 'Password updated successfully';
            } else {
                $response['status'] = 'error';
                $response['message'] = 'Phone number not found or no changes made.';
            }
        } else {
            $response['status'] = 'error';
            $response['message'] = 'Failed to update password. Error: ' . $stmt->error;
        }

        $stmt->close();
    } else {
        $response['status'] = 'error';
        $response['message'] = 'Invalid input. Phone number and PIN are required.';
    }
}

// Tutup koneksi
$con->close();

// Header HTTP
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

// Kirim respon dalam format JSON
echo json_encode($response);
?>
