<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');
$tabSessionID = $_GET['tab_id']; // Tab ID

if (isset($_POST['new_pin'])) {
    $student_id = $_SESSION['student_id'];
    $raw_pin = $_POST['new_pin'];

    // Validation: Must be 4 digits
    if (!preg_match('/^\d{4}$/', $raw_pin)) {
        header("Location: wallet_details.php?status=error&message=PIN must be 4 digits.&tab_id=$tabSessionID");
        exit();
    }

    // Secure Hashing (Innovation & Quality directive)
    $hashed_pin = password_hash($raw_pin, PASSWORD_BCRYPT);

    $stmt = $con->prepare("UPDATE wallets SET transaction_pin = ?, is_pin_set = 1 WHERE student_id = ?");
    $stmt->bind_param("si", $hashed_pin, $student_id);

    if ($stmt->execute()) {
        header("Location: wallet_details.php?status=success&message=Transaction PIN set successfully.&tab_id=$tabSessionID");
    } else {
        header("Location: wallet_details.php?status=error&message=Failed to save PIN.&tab_id=$tabSessionID");
    }
    $stmt->close();
}
?>