<?php
header("Content-Type: application/json");
require 'db.php';

$data = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;

$user_id = $data['user_id'] ?? '';
$pin = $data['pin'] ?? '';

if (!$user_id || !$pin) {
    echo json_encode(['success' => false, 'message' => 'User ID and PIN are required']);
    exit;
}

// Validate PIN format
if (strlen($pin) !== 4 || !is_numeric($pin)) {
    echo json_encode(['success' => false, 'message' => 'PIN must be exactly 4 digits']);
    exit;
}

// Get user and check if PIN is already set
$stmt = $conn->prepare("SELECT id, pin FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($user = $result->fetch_assoc()) {
    // Check if PIN is already set
    if (!empty($user['pin'])) {
        echo json_encode(['success' => false, 'message' => 'PIN already set. Use change PIN instead.']);
        exit;
    }

    // Set the PIN (storing as plain text like your change_pin.php)
    $update = $conn->prepare("UPDATE users SET pin = ? WHERE id = ?");
    $update->bind_param("si", $pin, $user_id);
    
    if ($update->execute()) {
        echo json_encode(['success' => true, 'message' => 'PIN setup successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update PIN']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'User not found']);
}
exit;
?>