<?php
/**
 * set_deposit_address.php
 * 
 * Admin endpoint to set the deposit address for each payment method
 * These addresses will be displayed to users as if they were generated uniquely
 */

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();

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['payment_method_id']) || !isset($data['deposit_address'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$payment_method_id = intval($data['payment_method_id']);
$deposit_address = trim($data['deposit_address']);
$qr_code = isset($data['qr_code']) ? trim($data['qr_code']) : null; // Optional QR code data

// Validate deposit address
if (empty($deposit_address)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Deposit address cannot be empty']);
    exit;
}

try {
    // Begin transaction
    $pdo->beginTransaction();
    
    // Check if payment method exists
    $methodStmt = $pdo->prepare("SELECT * FROM payment_methods WHERE id = ?");
    $methodStmt->execute([$payment_method_id]);
    $payment_method = $methodStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$payment_method) {
        throw new Exception('Payment method not found');
    }
    
    // Check if an address already exists for this payment method
    $checkStmt = $pdo->prepare("
        SELECT * FROM admin_deposit_addresses 
        WHERE payment_method_id = ?
    ");
    
    $checkStmt->execute([$payment_method_id]);
    $existing = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existing) {
        // Update existing address
        $updateStmt = $pdo->prepare("
            UPDATE admin_deposit_addresses 
            SET 
                address = ?,
                qr_code = ?,
                updated_at = NOW() 
            WHERE id = ?
        ");
        
        $updateStmt->execute([$deposit_address, $qr_code, $existing['id']]);
        $address_id = $existing['id'];
        $message = 'Deposit address updated successfully';
    } else {
        // Create new address
        $insertStmt = $pdo->prepare("
            INSERT INTO admin_deposit_addresses 
            (payment_method_id, address, qr_code, created_at) 
            VALUES (?, ?, ?, NOW())
        ");
        
        $insertStmt->execute([$payment_method_id, $deposit_address, $qr_code]);
        $address_id = $pdo->lastInsertId();
        $message = 'Deposit address created successfully';
    }
    
    // Create admin log
    $logStmt = $pdo->prepare("
        INSERT INTO admin_logs 
        (admin_id, action, target_type, target_id, details, created_at) 
        VALUES (?, 'set_deposit_address', 'payment_method', ?, ?, NOW())
    ");
    
    $log_details = json_encode([
        'payment_method_id' => $payment_method_id,
        'payment_method_name' => $payment_method['name'],
        'address' => $deposit_address
    ]);
    
    $logStmt->execute([isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1, $payment_method_id, $log_details]);
    
    // Commit the transaction
    $pdo->commit();
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => $message,
        'deposit_address' => [
            'id' => $address_id,
            'payment_method_id' => $payment_method_id,
            'payment_method_name' => $payment_method['name'],
            'address' => $deposit_address
        ]
    ]);
    
} catch (Exception $e) {
    // Rollback transaction if in progress
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Failed to set deposit address: ' . $e->getMessage()
    ]);
}
