<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);
include('config.php');
include "auth_guard.php";
// Initialize variables
$error = '';
$success = '';

// code for action taken on leave
if(isset($_POST['update'])) {
    $did = intval($_GET['id']);
    $email = $_GET['email'] ?? '';
    $deposit_amount = $_GET['deposit'] ?? 0;
    $description = $_POST['description'] ?? '';
    $status = $_POST['status'] ?? 0;
    $trade_id = $_POST['tradeid'] ?? '';

    try {
        // Update wallet deposit record
        $sql = "UPDATE wallet_deposit SET AdminRemark=:description, Status=:status WHERE id=:did";
        $query = $conn->prepare($sql);
        $query->bindParam(':description', $description, PDO::PARAM_STR);
        $query->bindParam(':status', $status, PDO::PARAM_INT);
        $query->bindParam(':did', $did, PDO::PARAM_INT);
        $query->execute();

        // If approved, add to total balance
        if($status == 1) {
            $sql = "INSERT INTO total_balance(email, deposit_amount, trade_id) VALUES(:email, :deposit_amount, :tradeid)";
            $query = $conn->prepare($sql);
            $query->bindParam(':email', $email, PDO::PARAM_STR);
            $query->bindParam(':deposit_amount', $deposit_amount, PDO::PARAM_STR);
            $query->bindParam(':tradeid', $trade_id, PDO::PARAM_STR);
            $query->execute();
            $lastInsertId = $conn->lastInsertId();

            // MT5 API integration
                    // MT5 API integration
            define("PATH_TO_SCRIPTS", "mt5_api/");
            include PATH_TO_SCRIPTS . "mt5_api.php";

            
define("MT5_SERVER_IP", "access.tgshost.org");
define("MT5_SERVER_PORT", "26043");
define("MT5_SERVER_WEB_LOGIN", "7020");
define("MT5_SERVER_WEB_PASSWORD", "Aa@123456");

            define("MT5_CRYPT_PROTOCOL", true);
            define("IS_WRITE_DEBUG_LOG", true);
            define("MT5_CONNECTION_TIMEOUT", 3);
            define("PATH_TO_LOGS", "./logs");
            define("AGENT", "WebAPITesterArt");

            $api = new MTWebAPI(AGENT, PATH_TO_LOGS, MT5_CRYPT_PROTOCOL);
            $api->SetLoggerWriteDebug(IS_WRITE_DEBUG_LOG);

            // MT5 manager connection - updated error handling
            if (($error_code = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, MT5_CONNECTION_TIMEOUT, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD)) != MTRetCode::MT_RET_OK) {
                // Check if error code is available
                if (defined('MTRetCode::MT_RET_'.$error_code)) {
                    $error_name = constant('MTRetCode::MT_RET_'.$error_code);
                    throw new Exception("Failed to connect to MT5 server (Error $error_code: $error_name)");
                } else {
                    throw new Exception("Failed to connect to MT5 server (Error $error_code)");
                }
            }

            // Get user account details - updated error handling
            if (($error_code = $api->UserAccountGet($trade_id, $account)) != MTRetCode::MT_RET_OK) {
                if (defined('MTRetCode::MT_RET_'.$error_code)) {
                    $error_name = constant('MTRetCode::MT_RET_'.$error_code);
                    throw new Exception("Failed to get account details (Error $error_code: $error_name)");
                } else {
                    throw new Exception("Failed to get account details (Error $error_code)");
                }
            }

            // Process deposit - updated error handling
            $comment = "Deposit request";
            $type = MTEnDealAction::DEAL_BALANCE;
            if (($error_code = $api->UserDepositChange($trade_id, $deposit_amount, $comment, $type)) != MTRetCode::MT_RET_OK) {
                if (defined('MTRetCode::MT_RET_'.$error_code)) {
                    $error_name = constant('MTRetCode::MT_RET_'.$error_code);
                    throw new Exception("Failed to process deposit (Error $error_code: $error_name)");
                } else {
                    throw new Exception("Failed to process deposit (Error $error_code)");
                }
            }

        }

        $success = "Client Wallet Deposit Updated Successfully";
    } catch (Exception $e) {
        $error = "Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wallet Deposit Details</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <style>
        .badge {
            display: inline-block;
            padding: 0.35em 0.65em;
            font-size: 0.75em;
            font-weight: 700;
            line-height: 1;
            text-align: center;
            white-space: nowrap;
            vertical-align: baseline;
            border-radius: 0.25rem;
        }
        .badge-success {
            color: #fff;
            background-color: #28a745;
        }
        .badge-danger {
            color: #fff;
            background-color: #dc3545;
        }
        .badge-primary {
            color: #fff;
            background-color: orange;
        }
        .badge-warning {
            color: #212529;
            background-color: #ffc107;
        }
        @media (max-width: 768px) {
            .flex-col-reverse {
                flex-direction: column-reverse;
            }
            .w-full-mobile {
                width: 100% !important;
            }
        }
    </style>
</head>
<body class="bg-gray-100">
<?php include('header.php');?>
<div class="flex flex-col md:flex-row h-screen">
    <?php include "side_bar.php";?>
    
    <main class="flex-1 p-4 md:p-6 md:ml-64">
        <!-- Header Section -->
        <div class="flex flex-col md:flex-row justify-between items-center mb-6">
            <h1 class="text-2xl font-bold text-gray-800">Wallet Deposit Details</h1>
            <a href="wallet_deposit.php" class="bg-orange-500 hover:bg-orange-600 text-white font-medium py-2 px-4 rounded-full transition duration-300 mt-2 md:mt-0">
                <i class="fas fa-arrow-left mr-2"></i>Back to List
            </a>
        </div>

        <!-- Display Messages -->
        <?php if($error): ?>
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-4" role="alert">
                <p><?php echo htmlspecialchars($error); ?></p>
            </div>
        <?php endif; ?>
        
        <?php if($success): ?>
            <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-4" role="alert">
                <p><?php echo htmlspecialchars($success); ?></p>
            </div>
        <?php endif; ?>

        <!-- Main Content -->
        <div class="flex flex-col lg:flex-row gap-6">
            <?php
            $id = intval($_GET['id']);
            $sql = "SELECT * FROM wallet_deposit WHERE id=:id";
            $query = $conn->prepare($sql);
            $query->bindParam(':id', $id, PDO::PARAM_INT);
            $query->execute();
            $results = $query->fetchAll(PDO::FETCH_OBJ);
            
            if($query->rowCount() > 0) {
                foreach($results as $result) {
            ?>
            <!-- Deposit Details Card -->
            <div class="w-full lg:w-7/12">
                <div class="bg-white rounded-lg shadow-md overflow-hidden">
                    <div class="bg-orange-600 px-4 py-3">
                        <h5 class="text-white font-semibold"><i class="fas fa-info-circle mr-2"></i>Deposit Details</h5>
                    </div>
                    <div class="p-4">
                        <div class="space-y-4">
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">Client Email:</span>
                                <span class="md:w-2/3"><?php echo htmlspecialchars($result->email ?? 'N/A'); ?></span>
                            </div>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">Deposit Amount:</span>
                                <span class="md:w-2/3 font-semibold text-green-600">$<?php echo htmlspecialchars($result->deposit_amount ?? '0'); ?></span>
                            </div>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">Trading Account:</span>
                                <span class="md:w-2/3"><?php echo htmlspecialchars($result->trade_id ?? 'N/A'); ?></span>
                            </div>
                            <?php if($result->deposit_type == 'Bitcoin' && !empty($result->btc_amount)): ?>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">BTC Amount:</span>
                                <span class="md:w-2/3"><?php echo htmlspecialchars($result->btc_amount); ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">Deposit Method:</span>
                                <span class="md:w-2/3"><?php echo htmlspecialchars($result->deposit_type ?? 'N/A'); ?></span>
                            </div>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">From:</span>
                                <span class="md:w-2/3"><?php echo htmlspecialchars($result->client_bank ?? 'N/A'); ?></span>
                            </div>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">To:</span>
                                <span class="md:w-2/3"><?php echo htmlspecialchars($result->company_bank ?? 'N/A'); ?></span>
                            </div>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">Reference ID:</span>
                                <span class="md:w-2/3"><?php echo htmlspecialchars($result->utr_number ?? 'N/A'); ?></span>
                            </div>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">Payment Proof:</span>
                                <span class="md:w-2/3">
                                    <?php if(!empty($result->image)): ?>
                                        <a href="https://test.traderssolution.com/crmvideonew/docs/<?php echo htmlspecialchars($result->image); ?>" 
                                           target="_blank" 
                                           class="text-orange-600 hover:text-orange-800">
                                            View Image
                                        </a>
                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Deposit Status Card -->
            <div class="w-full lg:w-5/12">
                <div class="bg-white rounded-lg shadow-md overflow-hidden">
                    <div class="bg-orange-600 px-4 py-3">
                        <h5 class="text-white font-semibold"><i class="fas fa-tasks mr-2"></i>Deposit Status</h5>
                    </div>
                    <div class="p-4">
                        <div class="space-y-4">
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">Deposit Date:</span>
                                <span class="md:w-2/3"><?php echo htmlspecialchars($result->deposted_date ?? 'N/A'); ?></span>
                            </div>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">Deposit Status:</span>
                                <span class="md:w-2/3">
                                    <?php
                                    $stats = $result->Status ?? 0;
                                    if($stats == 1) {
                                        echo '<span class="badge badge-success">Approved</span>';
                                    } elseif($stats == 2) {
                                        echo '<span class="badge badge-primary">Not Approved</span>';
                                    } else {
                                        echo '<span class="badge badge-warning">Pending Approval</span>';
                                    }
                                    ?>
                                </span>
                            </div>
                            <div class="flex flex-col md:flex-row">
                                <span class="text-gray-600 font-medium md:w-1/3">Admin Remark:</span>
                                <span class="md:w-2/3">
                                    <?php 
                                    echo !empty($result->AdminRemark) ? 
                                        htmlspecialchars($result->AdminRemark) : 
                                        'Waiting for Approval';
                                    ?>
                                </span>
                            </div>
                        </div>

                        <!-- Action Button (only show if status is pending) -->
                        <?php if(($result->Status ?? 0) == 0): ?>
                        <div class="mt-6">
                            <button type="button" 
                                    class="w-full bg-orange-600 hover:bg-orange-700 text-white font-medium py-2 px-4 rounded transition duration-300"
                                    data-toggle="modal" 
                                    data-target="#actionModal">
                                Take Action
                            </button>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php }} ?>
        </div>
    </main>
</div>

<!-- Action Modal -->
<div id="actionModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-1/2 shadow-lg rounded-md bg-white">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="text-lg font-semibold text-gray-900">Wallet Deposit Action</h3>
            </div>
            <form name="adminaction" method="post">
                <div class="modal-body space-y-4">
                    <div>
                        <label for="status" class="block text-sm font-medium text-gray-700">Action:</label>
                        <select name="status" id="status" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-orange-500 focus:border-orange-500" required>
                            <option value="">Choose your option</option>
                            <option value="1">Approved</option>
                            <option value="2">Not Approved</option>
                        </select>
                    </div>
                    <div>
                        <label for="description" class="block text-sm font-medium text-gray-700">Description:</label>
                        <textarea name="description" id="description" rows="3" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-orange-500 focus:border-orange-500" required></textarea>
                    </div>
                    <input type="hidden" name="tradeid" value="<?php echo htmlspecialchars($result->trade_id ?? ''); ?>">
                </div>
                <div class="modal-footer flex justify-end space-x-3 mt-4">
                    <button type="submit" class="bg-orange-600 hover:bg-orange-700 text-white font-medium py-2 px-4 rounded transition duration-300" name="update">
                        Update
                    </button>
                    <button type="button" onclick="document.getElementById('actionModal').classList.add('hidden')" class="bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded transition duration-300">
                        Close
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Simple Modal Toggle Script -->
<script>
    document.querySelector('[data-target="#actionModal"]').addEventListener('click', function() {
        document.getElementById('actionModal').classList.remove('hidden');
    });
</script>

<?php include('footer.php');?>
</body>
</html>