<?php
session_start();
require 'require/conn.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not logged in']);
    exit();
}

$phone = $_SESSION['phone'];

// Validate PIN input
if (!isset($_POST['pin']) || !preg_match('/^\d{4}$/', $_POST['pin'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid PIN format']);
    exit();
}

$pin = $_POST['pin'];

// Hash the PIN securely (use PASSWORD_DEFAULT)
$hashed_pin = password_hash($pin, PASSWORD_DEFAULT);

$stmt = $conn->prepare("UPDATE jamaa SET transaction_pin = ? WHERE phone = ?");
$stmt->bind_param("ss", $hashed_pin, $phone);

if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save PIN']);
}
?>
