<?php
/**
 * set_user_pin_settings.php
 * 
 * Admin endpoint to enable/disable withdrawal PIN requirements for a specific user
 * Also allows setting maximum number of PINs and PIN expiry period
 */

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require admin authentication
requireAdmin(true);

require_once 'config.php';
require_once 'db.php';

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

// Get and validate POST data
$json_data = file_get_contents('php://input');
$data = json_decode($json_data, true);

if (!$data || !isset($data['user_id']) || !isset($data['pin_enabled'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$user_id = intval($data['user_id']);
$pin_enabled = (bool)$data['pin_enabled'] ? 1 : 0;
$max_pins = isset($data['max_pins']) ? intval($data['max_pins']) : 5;
$pin_expiry_days = isset($data['pin_expiry_days']) ? intval($data['pin_expiry_days']) : 30;
$notes = isset($data['notes']) ? trim($data['notes']) : null;

// Validate max pins
if ($max_pins < 1 || $max_pins > 10) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Max pins must be between 1 and 10']);
    exit;
}

// Validate pin expiry days
if ($pin_expiry_days !== null && ($pin_expiry_days < 1 || $pin_expiry_days > 365)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Pin expiry days must be between 1 and 365']);
    exit;
}

try {
    // Begin transaction
    $pdo->beginTransaction();
    
    // Check if user exists
    $userStmt = $pdo->prepare("SELECT id, username, email FROM users WHERE id = ?");
    $userStmt->execute([$user_id]);
    $user = $userStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        throw new Exception('User not found');
    }
    
    // Check if user already has pin settings
    $settingsStmt = $pdo->prepare("
        SELECT * FROM user_pin_settings 
        WHERE user_id = ? 
        LIMIT 1
    ");
    
    $settingsStmt->execute([$user_id]);
    $settings = $settingsStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($settings) {
        // Update existing settings
        $updateStmt = $pdo->prepare("
            UPDATE user_pin_settings 
            SET 
                pin_enabled = ?,
                max_pins = ?,
                pin_expiry_days = ?,
                updated_at = NOW() 
            WHERE user_id = ?
        ");
        
        $updateStmt->execute([$pin_enabled, $max_pins, $pin_expiry_days, $user_id]);
        $settings_id = $settings['id'];
        $message = 'Withdrawal PIN settings updated successfully';
    } else {
        // Create new settings
        $insertStmt = $pdo->prepare("
            INSERT INTO user_pin_settings 
            (user_id, pin_enabled, max_pins, pin_expiry_days, created_at) 
            VALUES (?, ?, ?, ?, NOW())
        ");
        
        $insertStmt->execute([$user_id, $pin_enabled, $max_pins, $pin_expiry_days]);
        $settings_id = $pdo->lastInsertId();
        $message = 'Withdrawal PIN settings created successfully';
    }
    
    // Update user table pin setting for compatibility with existing code
    $updateUserStmt = $pdo->prepare("
        UPDATE users 
        SET 
            withdrawal_pin_required = ?,
            updated_at = NOW() 
        WHERE id = ?
    ");
    
    $updateUserStmt->execute([$pin_enabled, $user_id]);
    
    // Handle PIN status based on new settings
    if ($pin_enabled == 0) {
        // If pins are disabled, update all active pins to cancelled
        $updatePinsStmt = $pdo->prepare("
            UPDATE withdrawal_pins 
            SET 
                status = 'cancelled',
                updated_at = NOW() 
            WHERE user_id = ? AND status = 'active'
        ");
        
        $updatePinsStmt->execute([$user_id]);
        $pins_affected = $updatePinsStmt->rowCount();
    }
    
    // Create admin log
    $logStmt = $pdo->prepare("
        INSERT INTO admin_logs 
        (admin_id, action, target_type, target_id, details, created_at) 
        VALUES (?, 'set_pin_settings', 'user', ?, ?, NOW())
    ");
    
    $log_details = json_encode([
        'user_id' => $user_id,
        'pin_enabled' => $pin_enabled,
        'max_pins' => $max_pins,
        'pin_expiry_days' => $pin_expiry_days,
        'notes' => $notes
    ]);
    
    $logStmt->execute([isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1, $user_id, $log_details]);
    
    // Commit the transaction
    $pdo->commit();
    
    // Return success response
    $response = [
        'success' => true,
        'message' => $message,
        'settings' => [
            'id' => $settings_id,
            'user_id' => $user_id,
            'username' => $user['username'],
            'email' => $user['email'],
            'pin_enabled' => (bool)$pin_enabled,
            'max_pins' => $max_pins,
            'pin_expiry_days' => $pin_expiry_days
        ]
    ];
    
    if (isset($pins_affected)) {
        $response['pins_cancelled'] = $pins_affected;
    }
    
    echo json_encode($response);
    
} catch (PDOException $e) {
    // Rollback transaction if in progress
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log('Database error setting user PIN settings: ' . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Database error setting user PIN settings.'
    ]);
    
} catch (Exception $e) {
    // Rollback transaction if in progress
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    http_response_code(400);
    echo json_encode([
        'success' => false, 
        'message' => $e->getMessage()
    ]);
}
