<?php
require_once '../config/conn.php';
session_start();

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

// Check authentication
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$student_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? '';
$new_pin = $_POST['new_pin'] ?? '';
$confirm_pin = $_POST['confirm_pin'] ?? '';

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

if ($new_pin !== $confirm_pin) {
    echo json_encode(['success' => false, 'message' => 'PINs do not match']);
    exit();
}

// Check for weak PINs (all same digits, sequential, etc.)
if (preg_match('/^(\d)\1{3}$/', $new_pin)) {
    echo json_encode(['success' => false, 'message' => 'PIN too simple - avoid repeating digits']);
    exit();
}

try {
    $conn->begin_transaction();
    
    if ($action === 'update') {
        $current_pin = $_POST['current_pin'] ?? '';
        
        // Verify current PIN
        $stmt = $conn->prepare("SELECT pin_hash FROM wallet_pins WHERE student_id = ?");
        $stmt->bind_param("i", $student_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            throw new Exception('No PIN found to update');
        }
        
        $row = $result->fetch_assoc();
        if (!password_verify($current_pin, $row['pin_hash'])) {
            throw new Exception('Current PIN is incorrect');
        }
        
        // Update PIN
        $pin_hash = password_hash($new_pin, PASSWORD_DEFAULT);
        $update_stmt = $conn->prepare("UPDATE wallet_pins SET pin_hash = ?, updated_at = NOW() WHERE student_id = ?");
        $update_stmt->bind_param("si", $pin_hash, $student_id);
        $update_stmt->execute();
        
        $message = 'PIN updated successfully';
    } else {
        // Create new PIN
        $pin_hash = password_hash($new_pin, PASSWORD_DEFAULT);
        $insert_stmt = $conn->prepare("INSERT INTO wallet_pins (student_id, pin_hash, created_at, updated_at) VALUES (?, ?, NOW(), NOW())");
        $insert_stmt->bind_param("is", $student_id, $pin_hash);
        $insert_stmt->execute();
        
        $message = 'PIN created successfully';
    }
    
    $conn->commit();
    echo json_encode(['success' => true, 'message' => $message]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}