<?php
session_start();
require_once __DIR__ . '/../includes/db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login");
    exit;
}

$user_id = $_SESSION['user_id'];

$current_pin = trim($_POST['current_pin'] ?? '');
$new_pin = trim($_POST['new_pin'] ?? '');
$confirm_pin = trim($_POST['confirm_pin'] ?? '');

if ($current_pin === '' || $new_pin === '' || $confirm_pin === '') {
    header("Location: ../users/change_pin?error=All fields are required");
    exit;
}

if (!ctype_digit($new_pin) || strlen($new_pin) !== 4) {
    header("Location: ../users/change_pin?error=PIN must be exactly 4 digits");
    exit;
}

if ($new_pin !== $confirm_pin) {
    header("Location: ../users/change_pin?error=New PIN and confirmation do not match");
    exit;
}

// Fetch stored PIN
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($current_pin != $user['transfer_pin']) {
    header("Location: ../users/change_pin?error=Incorrect current PIN");
    exit;
}

// Update new PIN
$update = $pdo->prepare("UPDATE users SET transfer_pin = ? WHERE id = ?");
$update->execute([$confirm_pin, $user_id]);

header("Location: ../users/change_pin?success=Transaction PIN updated successfully");
exit;
