<?php
session_start();
require_once '../config/database.php';
require_once 'includes/auth_check.php';

$page = 'crypto_deposits';
$database = new Database();
$db = $database->getConnection();

// Get deposit ID from POST or GET
$deposit_id = $_POST['deposit_id'] ?? $_GET['id'] ?? null;

if (!$deposit_id) {
    $_SESSION['error'] = "Deposit ID is required.";
    header("Location: crypto_deposits.php");
    exit();
}

// Get deposit details
try {
    $stmt = $db->prepare("
        SELECT cd.*, u.first_name, u.last_name, u.email, u.account_number 
        FROM crypto_deposits cd
        LEFT JOIN users u ON cd.user_id = u.id
        WHERE cd.id = ?
    ");
    $stmt->execute([$deposit_id]);
    $deposit = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$deposit) {
        $_SESSION['error'] = "Deposit not found.";
        header("Location: crypto_deposits.php");
        exit();
    }
} catch (PDOException $e) {
    $_SESSION['error'] = "Error retrieving deposit details: " . $e->getMessage();
    header("Location: crypto_deposits.php");
    exit();
}

// Handle form submission for approving/rejecting deposits
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $admin_notes = $_POST['admin_notes'] ?? '';
    
    try {
        $db->beginTransaction();
        
        if ($action === 'approve') {
            // Update deposit status
            $stmt = $db->prepare("UPDATE crypto_deposits SET status = 'approved', admin_notes = ?, admin_id = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$admin_notes, $_SESSION['admin_id'], $deposit_id]);
            
            // Credit user's account
            $stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $stmt->execute([$deposit['amount'], $deposit['user_id']]);
            
            // Create transaction record
            $stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, status, description, transaction_type) 
                                 VALUES (?, 'credit', ?, 'completed', ?, 'deposit')");
            $stmt->execute([
                $deposit['user_id'], 
                $deposit['amount'], 
                'Crypto deposit (' . $deposit['currency'] . ') - Transaction: ' . substr($deposit['transaction_hash'], 0, 10) . '...'
            ]);
            
            // Create notification for user
            $stmt = $db->prepare("
                INSERT INTO notifications (user_id, type, title, message, link, is_read, created_at)
                VALUES (?, 'deposit_approved', 'Deposit Approved', ?, 'transactions.php', 0, NOW())
            ");
            $stmt->execute([
                $deposit['user_id'],
                'Your ' . $deposit['currency'] . ' deposit of ' . $deposit['amount'] . ' has been approved and credited to your account.'
            ]);
            
            $_SESSION['success'] = "Deposit approved and funds credited to user account.";
        } elseif ($action === 'reject') {
            // Update deposit status
            $stmt = $db->prepare("UPDATE crypto_deposits SET status = 'rejected', admin_notes = ?, admin_id = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$admin_notes, $_SESSION['admin_id'], $deposit_id]);
            
            // Create notification for user
            $stmt = $db->prepare("
                INSERT INTO notifications (user_id, type, title, message, link, is_read, created_at)
                VALUES (?, 'deposit_rejected', 'Deposit Rejected', ?, 'deposit_history.php', 0, NOW())
            ");
            $stmt->execute([
                $deposit['user_id'],
                'Your ' . $deposit['currency'] . ' deposit of ' . $deposit['amount'] . ' has been rejected. Reason: ' . $admin_notes
            ]);
            
            $_SESSION['success'] = "Deposit rejected successfully.";
        }
        
        $db->commit();
        header("Location: crypto_deposits.php");
        exit();
    } catch (Exception $e) {
        $db->rollBack();
        $_SESSION['error'] = "Error processing deposit: " . $e->getMessage();
    }
}

include 'includes/header.php';
?>

<div class="content-wrapper">
    <div class="container-fluid">
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col">
                    <h1 class="page-header-title text-primary">
                        <i class="fas fa-eye mr-2"></i> View Deposit
                    </h1>
                    <p class="text-muted">Viewing details for deposit #<?php echo $deposit['id']; ?></p>
                </div>
                <div class="col-auto">
                    <a href="crypto_deposits.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left mr-1"></i> Back to Deposits
                    </a>
                </div>
            </div>
        </div>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-lg-8">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Deposit Details</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="font-weight-bold">Deposit Information</h6>
                                <table class="table table-sm">
                                    <tr>
                                        <th>ID</th>
                                        <td><?php echo $deposit['id']; ?></td>
                                    </tr>
                                    <tr>
                                        <th>Currency</th>
                                        <td>
                                            <?php if ($deposit['currency'] === 'BTC'): ?>
                                                <i class="fab fa-bitcoin text-warning mr-1"></i>
                                            <?php elseif ($deposit['currency'] === 'USDT'): ?>
                                                <i class="fas fa-dollar-sign text-success mr-1"></i>
                                            <?php endif; ?>
                                            <?php echo htmlspecialchars($deposit['currency']); ?>
                                            <?php if ($deposit['network']): ?>
                                                <span class="badge badge-light"><?php echo htmlspecialchars($deposit['network']); ?></span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Amount</th>
                                        <td><?php echo number_format($deposit['amount'], 8); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Status</th>
                                        <td>
                                            <?php if ($deposit['status'] === 'pending'): ?>
                                                <span class="badge badge-warning">Pending</span>
                                            <?php elseif ($deposit['status'] === 'approved'): ?>
                                                <span class="badge badge-success">Approved</span>
                                            <?php elseif ($deposit['status'] === 'rejected'): ?>
                                                <span class="badge badge-danger">Rejected</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Date</th>
                                        <td><?php echo date('M d, Y H:i', strtotime($deposit['created_at'])); ?></td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <h6 class="font-weight-bold">Customer Information</h6>
                                <table class="table table-sm">
                                    <tr>
                                        <th>Name</th>
                                        <td>
                                            <a href="user_details.php?id=<?php echo $deposit['user_id']; ?>">
                                                <?php echo htmlspecialchars($deposit['first_name'] . ' ' . $deposit['last_name']); ?>
                                            </a>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Account #</th>
                                        <td><?php echo htmlspecialchars($deposit['account_number']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Email</th>
                                        <td><?php echo htmlspecialchars($deposit['email']); ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        
                        <h6 class="font-weight-bold mt-4">Transaction Details</h6>
                        <div class="form-group">
                            <label>Transaction Hash</label>
                            <div class="input-group">
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($deposit['transaction_hash']); ?>" readonly>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary copy-hash" type="button">
                                        <i class="fas fa-copy"></i> Copy
                                    </button>
                                    <?php
                                    $explorerUrl = '#';
                                    if ($deposit['currency'] === 'BTC') {
                                        $explorerUrl = 'https://www.blockchain.com/btc/tx/' . $deposit['transaction_hash'];
                                    } elseif ($deposit['currency'] === 'USDT') {
                                        if ($deposit['network'] === 'TRC20') {
                                            $explorerUrl = 'https://tronscan.org/#/transaction/' . $deposit['transaction_hash'];
                                        } elseif ($deposit['network'] === 'ERC20') {
                                            $explorerUrl = 'https://etherscan.io/tx/' . $deposit['transaction_hash'];
                                        } elseif ($deposit['network'] === 'BEP20') {
                                            $explorerUrl = 'https://bscscan.com/tx/' . $deposit['transaction_hash'];
                                        }
                                    }
                                    ?>
                                    <a href="<?php echo $explorerUrl; ?>" class="btn btn-outline-primary" target="_blank">
                                        <i class="fas fa-external-link-alt"></i> View
                                    </a>
                                </div>
                            </div>
                        </div>
                        
                        <h6 class="font-weight-bold mt-4">Wallet Address</h6>
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($deposit['wallet_address']); ?>" readonly>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary copy-address" type="button">
                                        <i class="fas fa-copy"></i> Copy
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <?php if ($deposit['screenshot']): ?>
                            <h6 class="font-weight-bold mt-4">Proof of Payment</h6>
                            <div class="text-center">
                                <a href="../uploads/deposit_proofs/<?php echo htmlspecialchars($deposit['screenshot']); ?>" target="_blank">
                                    <img src="../uploads/deposit_proofs/<?php echo htmlspecialchars($deposit['screenshot']); ?>" alt="Proof of Payment" class="img-fluid img-thumbnail" style="max-height: 300px;">
                                </a>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($deposit['admin_notes']): ?>
                            <h6 class="font-weight-bold mt-4">Admin Notes</h6>
                            <p class="p-2 bg-light rounded"><?php echo htmlspecialchars($deposit['admin_notes']); ?></p>
                        <?php endif; ?>
                        
                        <?php if ($deposit['status'] === 'pending'): ?>
                            <div class="mt-4">
                                <h6 class="font-weight-bold">Actions</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <form method="post">
                                            <input type="hidden" name="action" value="approve">
                                            <div class="form-group">
                                                <label for="admin_notes_approve">Admin Notes (Optional)</label>
                                                <textarea class="form-control" id="admin_notes_approve" name="admin_notes" rows="3" placeholder="Add any notes regarding this approval..."></textarea>
                                            </div>
                                            <button type="submit" class="btn btn-success">
                                                <i class="fas fa-check mr-1"></i> Approve Deposit
                                            </button>
                                        </form>
                                    </div>
                                    <div class="col-md-6">
                                        <form method="post">
                                            <input type="hidden" name="action" value="reject">
                                            <div class="form-group">
                                                <label for="admin_notes_reject">Reason for Rejection <span class="text-danger">*</span></label>
                                                <textarea class="form-control" id="admin_notes_reject" name="admin_notes" rows="3" required placeholder="Please provide a reason for rejecting this deposit..."></textarea>
                                            </div>
                                            <button type="submit" class="btn btn-danger">
                                                <i class="fas fa-times mr-1"></i> Reject Deposit
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-4">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Quick Actions</h6>
                    </div>
                    <div class="card-body">
                        <a href="crypto_deposits.php" class="btn btn-block btn-outline-secondary mb-3">
                            <i class="fas fa-arrow-left mr-1"></i> Back to Deposits
                        </a>
                        
                        <a href="user_details.php?id=<?php echo $deposit['user_id']; ?>" class="btn btn-block btn-outline-primary mb-3">
                            <i class="fas fa-user mr-1"></i> View Customer
                        </a>
                        
                        <?php if ($explorerUrl !== '#'): ?>
                            <a href="<?php echo $explorerUrl; ?>" target="_blank" class="btn btn-block btn-outline-info">
                                <i class="fas fa-external-link-alt mr-1"></i> View on Blockchain
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Copy transaction hash to clipboard
    document.querySelector('.copy-hash').addEventListener('click', function() {
        const hashInput = this.closest('.input-group').querySelector('input');
        hashInput.select();
        document.execCommand('copy');
        
        // Show feedback
        const originalText = this.innerHTML;
        this.innerHTML = '<i class="fas fa-check"></i> Copied!';
        
        setTimeout(() => {
            this.innerHTML = originalText;
        }, 2000);
    });
    
    // Copy wallet address to clipboard
    document.querySelector('.copy-address').addEventListener('click', function() {
        const addressInput = this.closest('.input-group').querySelector('input');
        addressInput.select();
        document.execCommand('copy');
        
        // Show feedback
        const originalText = this.innerHTML;
        this.innerHTML = '<i class="fas fa-check"></i> Copied!';
        
        setTimeout(() => {
            this.innerHTML = originalText;
        }, 2000);
    });
});
</script>

<?php include 'includes/footer.php'; ?>
