<?php
/**
 * verify_deposit.php
 * 
 * Admin endpoint to verify and approve pending deposits
 * Updates user balance and transaction status
 * Part of the Ton Sui Mining payment processing system
 */

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');
// Reflect exact Origin for credentialed requests
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
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['transaction_id']) || !isset($data['action'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$transaction_id = intval($data['transaction_id']);
$action = $data['action']; // 'approve', 'reject'
$admin_notes = isset($data['admin_notes']) ? $data['admin_notes'] : null;
$tx_hash = isset($data['tx_hash']) ? $data['tx_hash'] : null;

// Validate action
if (!in_array($action, ['approve', 'reject'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

try {
    // Begin transaction
    $pdo->beginTransaction();
    
    // Introspect columns used in updates
    $tx_has_updated = false;
    try {
        $c1 = $pdo->query("SHOW COLUMNS FROM transactions");
        while ($c = $c1->fetch(PDO::FETCH_ASSOC)) {
            if (strtolower($c['Field'] ?? '') === 'updated_at') $tx_has_updated = true;
        }
    } catch (Exception $ie) { /* ignore */ }
    
    // Get the transaction details
    $transStmt = $pdo->prepare("
        SELECT * FROM transactions 
        WHERE id = ? AND type = 'deposit' AND status = 'pending'
    ");
    
    $transStmt->execute([$transaction_id]);
    $transaction = $transStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$transaction) {
        throw new Exception('Transaction not found or not a pending deposit');
    }
    
    // Get user details
    $userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $userStmt->execute([$transaction['user_id']]);
    $user = $userStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        throw new Exception('User not found');
    }
    
    // Parse additional details
    $details = json_decode($transaction['details'], true) ?? [];
    
    // Add admin action information to details
    $details['admin_action'] = $action;
    $details['admin_id'] = isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1;
    $details['admin_notes'] = $admin_notes;
    $details['verification_date'] = date('Y-m-d H:i:s');
    
    if ($tx_hash) {
        $details['tx_hash'] = $tx_hash;
    }
    
    $updated_details = json_encode($details);
    
    if ($action === 'approve') {
        // Approve the deposit
        
        // Update transaction status (schema-aware)
        $txSql = "UPDATE transactions SET status='completed', details=?" . ($tx_has_updated ? ", updated_at=NOW()" : "") . " WHERE id = ?";
        $updateTransStmt = $pdo->prepare($txSql);
        $updateTransStmt->execute([$updated_details, $transaction_id]);
        
        // Update user balance (schema-tolerant for legacy DBs without total_deposited)
        $amount = floatval($transaction['amount']);
        $hasTotalDeposited = false;
        try {
            $c = $pdo->query("SHOW COLUMNS FROM users LIKE 'total_deposited'");
            $hasTotalDeposited = $c && $c->rowCount() > 0;
        } catch (Exception $ie) { /* ignore */ }

        if ($hasTotalDeposited) {
            $updateBalanceStmt = $pdo->prepare("\n                UPDATE users \n                SET \n                    balance = balance + ?,\n                    total_deposited = COALESCE(total_deposited, 0) + ?,\n                    updated_at = NOW() \n                WHERE id = ?\n            ");
            $updateBalanceStmt->execute([$amount, $amount, $transaction['user_id']]);
        } else {
            $updateBalanceStmt = $pdo->prepare("\n                UPDATE users \n                SET \n                    balance = balance + ?,\n                    updated_at = NOW() \n                WHERE id = ?\n            ");
            $updateBalanceStmt->execute([$amount, $transaction['user_id']]);
        }
        
        // Create log entry (non-fatal if logging table missing)
        $log_details = json_encode([
            'transaction_id' => $transaction_id,
            'user_id' => $transaction['user_id'],
            'amount' => $amount,
            'reference' => $transaction['reference'],
            'notes' => $admin_notes
        ]);
        try {
            $logStmt = $pdo->prepare("INSERT INTO admin_logs (admin_id, action, target_type, target_id, details, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
            $logStmt->execute([
                isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1, 
                'approve_deposit', 
                'transaction', 
                $transaction_id,
                $log_details
            ]);
        } catch (Exception $ie) { /* ignore logging errors */ }
        
        $message = 'Deposit approved successfully. User balance updated.';
        
    } else {
        // Reject the deposit
        
        // Update transaction status (schema-aware)
        $txSql = "UPDATE transactions SET status='rejected', details=?" . ($tx_has_updated ? ", updated_at=NOW()" : "") . " WHERE id = ?";
        $updateTransStmt = $pdo->prepare($txSql);
        $updateTransStmt->execute([$updated_details, $transaction_id]);
        
        // Create log entry (non-fatal)
        $log_details = json_encode([
            'transaction_id' => $transaction_id,
            'user_id' => $transaction['user_id'],
            'amount' => $transaction['amount'],
            'reference' => $transaction['reference'],
            'notes' => $admin_notes
        ]);
        try {
            $logStmt = $pdo->prepare("INSERT INTO admin_logs (admin_id, action, target_type, target_id, details, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
            $logStmt->execute([
                isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1, 
                'reject_deposit', 
                'transaction', 
                $transaction_id,
                $log_details
            ]);
        } catch (Exception $ie) { /* ignore logging errors */ }
        
        $message = 'Deposit rejected successfully.';
    }
    
    // Commit the transaction
    $pdo->commit();
    
    // Send notification to user (in a production environment)
    // This would typically involve sending an email or push notification
    
    echo json_encode([
        'success' => true, 
        'message' => $message,
        'transaction' => [
            'id' => $transaction_id,
            'status' => $action === 'approve' ? 'completed' : 'rejected',
            'user_id' => $transaction['user_id'],
            'amount' => $transaction['amount'],
            'reference' => $transaction['reference']
        ]
    ]);
    
} 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 process deposit: ' . $e->getMessage()
    ]);
}
