<?php
session_start();
include('includes/head.php');

// Check admin session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';
$admin_role = $_SESSION['admin_role'] ?: 'admin';

// Get admin email for notification
$adminQuery = mysqli_query($conn, "SELECT email, first_name FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_email = $adminData['email'] ?? 'admin@system.com';
$admin_first_name = $adminData['first_name'] ?? 'Administrator';

// PIN for confirmation
$admin_pin = "1234"; // Change this to a secure PIN

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
    
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Changes not saved.";
    } else {
        switch ($action_type) {
            case 'update_system_settings':
                // Get old settings for comparison
                $old_settings = array();
                foreach ($settings as $key => $value) {
                    $old_settings[$key] = $value;
                }
                
                $withdrawal_fee = floatval($_POST['withdrawal_fee']);
                $min_withdrawal = floatval($_POST['min_withdrawal']);
                $max_withdrawal = floatval($_POST['max_withdrawal']);
                $min_deposit = floatval($_POST['min_deposit']);
                $max_deposit = floatval($_POST['max_deposit']);
                $deposit_fee = floatval($_POST['deposit_fee']);
                $trading_fee = floatval($_POST['trading_fee']);
                $subscription_fee_discount = floatval($_POST['subscription_fee_discount']);
                $referral_commission = floatval($_POST['referral_commission']);
                $affiliate_commission = floatval($_POST['affiliate_commission']);
                
                $settings = array(
                    'withdrawal_fee' => $withdrawal_fee,
                    'min_withdrawal' => $min_withdrawal,
                    'max_withdrawal' => $max_withdrawal,
                    'min_deposit' => $min_deposit,
                    'max_deposit' => $max_deposit,
                    'deposit_fee' => $deposit_fee,
                    'trading_fee' => $trading_fee,
                    'subscription_fee_discount' => $subscription_fee_discount,
                    'referral_commission' => $referral_commission,
                    'affiliate_commission' => $affiliate_commission
                );
                
                // Track changes for notification
                $changes = array();
                foreach ($settings as $key => $value) {
                    $sql = "INSERT INTO system_settings (setting_key, setting_value, description, updated_at) 
                            VALUES ('$key', '$value', '', NOW()) 
                            ON DUPLICATE KEY UPDATE setting_value = '$value', updated_at = NOW()";
                    mysqli_query($conn, $sql);
                    
                    if (isset($old_settings[$key]) && $old_settings[$key] != $value) {
                        $changes[] = array(
                            'key' => $key,
                            'old' => $old_settings[$key],
                            'new' => $value
                        );
                    }
                }
                
                logAdminActivity(
                    'Payment Settings Updated',
                    'Updated system payment settings',
                    'Settings',
                    null,
                    'system_settings'
                );
                
                // NOTIFICATION: Payment Settings Updated (ADMIN)
                $mail_subject = "Payment Settings Updated";
                $mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>System Payment Settings Updated</h2>
                                    
                                    <p class='message'>
                                        Payment settings have been updated by an administrator.
                                    </p>

                                    <!-- Settings Details -->
                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                            <strong>Update Date:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                        </div>
                                    </div>

                                    <!-- Settings Changes -->
                                    <div class='settings-comparison'>
                                        <h3 style='color: #2c3e50;'>📊 Settings Changes</h3>
                                        <table style='width: 100%; border-collapse: collapse; margin: 15px 0;'>
                                            <thead>
                                                <tr style='background: #f8f9fa;'>
                                                    <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>Setting</th>
                                                    <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>Old Value</th>
                                                    <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>New Value</th>
                                                    <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>Change</th>
                                                </tr>
                                            </thead>
                                            <tbody>";
                
                foreach ($changes as $change) {
                    $change_percent = $change['old'] > 0 ? round((($change['new'] - $change['old']) / $change['old']) * 100, 1) : 0;
                    $change_direction = $change['new'] > $change['old'] ? '▲' : '▼';
                    $change_color = $change['new'] > $change['old'] ? '#28a745' : '#dc3545';
                    
                    $mail_message .= "<tr>
                                        <td style='border: 1px solid #dee2e6; padding: 10px;'><strong>" . ucwords(str_replace('_', ' ', $change['key'])) . "</strong></td>
                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>" . $change['old'] . "</td>
                                        <td style='border: 1px solid #dee2e6; padding: 10px;'><span style='color: " . $change_color . "; font-weight: bold;'>" . $change['new'] . "</span></td>
                                        <td style='border: 1px solid #dee2e6; padding: 10px;'><span style='color: " . $change_color . ";'>" . $change_direction . " " . abs($change_percent) . "%</span></td>
                                    </tr>";
                }
                
                if (empty($changes)) {
                    $mail_message .= "<tr>
                                        <td style='border: 1px solid #dee2e6; padding: 10px;' colspan='4' align='center'>No settings were changed</td>
                                    </tr>";
                }
                
                $mail_message .= "          </tbody>
                                        </table>
                                    </div>

                                    <!-- Business Impact -->
                                    <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                        <h4 style='color: #0056b3;'>💼 Business Impact</h4>
                                        <p style='color: #0056b3;'>
                                            <strong>Withdrawal Fee:</strong> " . $withdrawal_fee . "% - Affects user withdrawals<br>
                                            <strong>Deposit Limits:</strong> $" . $min_deposit . " - $" . $max_deposit . " - Affects user deposits<br>
                                            <strong>Trading Fee:</strong> " . $trading_fee . "% - Affects trading profitability<br>
                                            <strong>Referral Commission:</strong> " . $referral_commission . "% - Affects affiliate earnings
                                        </p>
                                    </div>

                                    <!-- Admin Actions -->
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/system_settings.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                            View Settings
                                        </a>
                                        <a href='" . $myUrl . "/admin/audit-logs.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                            View Audit Logs
                                        </a>
                                    </div>

                                    <!-- Security Note -->
                                    <div class='support-section'>
                                        <p class='support-text'>This change has been logged in admin activities.</p>
                                        <p style='color: #6c757d; font-size: 12px;'>
                                            <strong>Module:</strong> System Settings<br>
                                            <strong>Action ID:</strong> SET-" . date('YmdHis') . "<br>
                                            <strong>Timestamp:</strong> " . date('Y-m-d H:i:s') . "
                                        </p>
                                    </div>
                                </div>";
                
                // Send admin notification
                require_once("../proccess/admin_mailer.php");
                
                $success = "Payment settings updated successfully!";
                break;
                
            case 'update_payment_method':
                $method_id = isset($_POST['method_id']) ? intval($_POST['method_id']) : 0;
                $method_name = mysqli_real_escape_string($conn, $_POST['method_name']);
                $network = mysqli_real_escape_string($conn, $_POST['network']);
                $wallet_address = mysqli_real_escape_string($conn, $_POST['wallet_address']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                $min_amount = floatval($_POST['min_amount']);
                $max_amount = floatval($_POST['max_amount']);
                
                // Get old method data if updating
                if ($method_id > 0) {
                    $old_method_sql = "SELECT * FROM payment_methods WHERE id = $method_id";
                    $old_method_result = mysqli_query($conn, $old_method_sql);
                    $old_method = mysqli_fetch_assoc($old_method_result);
                }
                
                if ($method_id > 0) {
                    // Update existing
                    $sql = "UPDATE payment_methods SET 
                            method_name = '$method_name',
                            network = '$network',
                            wallet_address = '$wallet_address',
                            is_active = $is_active,
                            min_amount = $min_amount,
                            max_amount = $max_amount,
                            updated_at = NOW()
                            WHERE id = $method_id";
                    
                    $action = 'updated';
                } else {
                    // Insert new
                    $sql = "INSERT INTO payment_methods (method_name, network, wallet_address, is_active, min_amount, max_amount, created_at, updated_at) 
                            VALUES ('$method_name', '$network', '$wallet_address', $is_active, $min_amount, $max_amount, NOW(), NOW())";
                    
                    $action = 'added';
                }
                
                if (mysqli_query($conn, $sql)) {
                    $affected_id = $method_id > 0 ? $method_id : mysqli_insert_id($conn);
                    
                    logAdminActivity(
                        $method_id > 0 ? 'Payment Method Updated' : 'Payment Method Added',
                        ($method_id > 0 ? 'Updated' : 'Added') . " payment method: $method_name",
                        'Settings',
                        $affected_id,
                        'payment_methods'
                    );
                    
                    // NOTIFICATION: Payment Method Updated (ADMIN)
                    $mail_subject = "Payment Method " . ($method_id > 0 ? "Updated" : "Added");
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Payment Method " . ($method_id > 0 ? "Updated" : "Added") . "</h2>
                                        
                                        <p class='message'>
                                            A payment method has been " . ($method_id > 0 ? "updated" : "added") . " in the system by an administrator.
                                        </p>

                                        <!-- Payment Method Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Action:</strong> " . ucfirst($action) . "<br>
                                                <strong>Method Name:</strong> " . $method_name . "<br>
                                                <strong>Network:</strong> " . $network . "<br>
                                                <strong>Wallet Address:</strong> " . substr($wallet_address, 0, 10) . "..." . substr($wallet_address, -6) . "<br>
                                                <strong>Status:</strong> " . ($is_active ? '<span style="color: #28a745;">Active</span>' : '<span style="color: #dc3545;">Inactive</span>') . "<br>
                                                <strong>Min Amount:</strong> $" . number_format($min_amount, 2) . "<br>
                                                <strong>Max Amount:</strong> $" . number_format($max_amount, 2) . "<br>
                                                <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                <strong>Update Date:</strong> " . date('F j, Y g:i A') . "
                                            </div>
                                        </div>";
                    
                    if ($method_id > 0 && $old_method) {
                        $mail_message .= "<!-- Changes Comparison -->
                                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #495057;'>📋 Changes Made</h4>
                                            <table style='width: 100%; border-collapse: collapse;'>
                                                <tr>
                                                    <td style='padding: 5px;'><strong>Old Status:</strong></td>
                                                    <td style='padding: 5px;'>" . ($old_method['is_active'] ? 'Active' : 'Inactive') . "</td>
                                                    <td style='padding: 5px;'><strong>New Status:</strong></td>
                                                    <td style='padding: 5px;'>" . ($is_active ? 'Active' : 'Inactive') . "</td>
                                                </tr>
                                                <tr>
                                                    <td style='padding: 5px;'><strong>Old Min:</strong></td>
                                                    <td style='padding: 5px;'>$" . number_format($old_method['min_amount'], 2) . "</td>
                                                    <td style='padding: 5px;'><strong>New Min:</strong></td>
                                                    <td style='padding: 5px;'>$" . number_format($min_amount, 2) . "</td>
                                                </tr>
                                                <tr>
                                                    <td style='padding: 5px;'><strong>Old Max:</strong></td>
                                                    <td style='padding: 5px;'>$" . number_format($old_method['max_amount'], 2) . "</td>
                                                    <td style='padding: 5px;'><strong>New Max:</strong></td>
                                                    <td style='padding: 5px;'>$" . number_format($max_amount, 2) . "</td>
                                                </tr>
                                            </table>
                                        </div>";
                    }
                    
                    $mail_message .= "<!-- Admin Actions -->
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/payment_methods.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                            View Payment Methods
                                        </a>
                                    </div>

                                    <!-- User Impact -->
                                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                        <h4 style='color: #856404;'>👥 User Impact</h4>
                                        <p style='color: #856404;'>
                                            This payment method is now " . ($is_active ? 'available' : 'unavailable') . " for users making deposits.<br>
                                            Users will see this change immediately on the deposit page.
                                        </p>
                                    </div>

                                    <!-- Support Section -->
                                    <div class='support-section'>
                                        <p class='support-text'>Action logged in admin activities.</p>
                                    </div>
                                </div>";
                    
                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Payment method " . ($method_id > 0 ? 'updated' : 'added') . " successfully!";
                } else {
                    $error = "Failed to save payment method.";
                }
                break;
                
            case 'delete_payment_method':
                $method_id = isset($_POST['method_id']) ? intval($_POST['method_id']) : 0;
                
                if ($method_id > 0) {
                    // Get method name before deletion
                    $method_sql = "SELECT method_name FROM payment_methods WHERE id = $method_id";
                    $method_result = mysqli_query($conn, $method_sql);
                    $method_data = mysqli_fetch_assoc($method_result);
                    $method_name = $method_data['method_name'] ?: 'Unknown';
                    
                    $sql = "DELETE FROM payment_methods WHERE id = $method_id";
                    
                    if (mysqli_query($conn, $sql)) {
                        logAdminActivity(
                            'Payment Method Deleted',
                            "Deleted payment method: $method_name",
                            'Settings',
                            $method_id,
                            'payment_methods'
                        );
                        
                        // NOTIFICATION: Payment Method Deleted (ADMIN)
                        $mail_subject = "Payment Method Deleted";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Payment Method Deleted</h2>
                                            
                                            <p class='message'>
                                                A payment method has been permanently deleted from the system by an administrator.
                                            </p>

                                            <!-- Deletion Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Deleted Method:</strong> " . $method_name . "<br>
                                                    <strong>Method ID:</strong> " . $method_id . "<br>
                                                    <strong>Deleted By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                    <strong>Deletion Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                                    <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>PERMANENTLY DELETED</span>
                                                </div>
                                            </div>

                                            <!-- Impact Warning -->
                                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #721c24;'>⚠️ Important</h4>
                                                <p style='color: #721c24;'>
                                                    This payment method is no longer available for users.<br>
                                                    Users will not be able to select this method for deposits.
                                                </p>
                                            </div>

                                            <!-- Admin Actions -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/admin/payment_methods.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                    View Remaining Methods
                                                </a>
                                            </div>

                                            <!-- Support Section -->
                                            <div class='support-section'>
                                                <p class='support-text'>Deletion logged in admin activities.</p>
                                            </div>
                                        </div>";
                        
                        // Send admin notification
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "Payment method deleted successfully!";
                    } else {
                        $error = "Failed to delete payment method.";
                    }
                }
                break;
                
            case 'update_commission_rates':
                // Get old commissions for comparison
                $old_commissions = array();
                $old_comm_sql = "SELECT id, plan_name, commission_rate FROM trading_bot_plans WHERE is_active = 1";
                $old_comm_result = mysqli_query($conn, $old_comm_sql);
                while ($row = mysqli_fetch_assoc($old_comm_result)) {
                    $old_commissions[$row['id']] = $row;
                }
                
                $updated_plans = array();
                
                // Update commission rates for bot plans
                if (isset($_POST['plan_commissions'])) {
                    foreach ($_POST['plan_commissions'] as $plan_id => $commission) {
                        $plan_id = intval($plan_id);
                        $commission = floatval($commission);
                        
                        $sql = "UPDATE trading_bot_plans SET commission_rate = $commission WHERE id = $plan_id";
                        mysqli_query($conn, $sql);
                        
                        if (isset($old_commissions[$plan_id]) && $old_commissions[$plan_id]['commission_rate'] != $commission) {
                            $updated_plans[] = array(
                                'id' => $plan_id,
                                'name' => $old_commissions[$plan_id]['plan_name'],
                                'old' => $old_commissions[$plan_id]['commission_rate'],
                                'new' => $commission
                            );
                        }
                    }
                    
                    logAdminActivity(
                        'Commission Rates Updated',
                        'Updated commission rates for trading bot plans',
                        'Settings',
                        null,
                        'trading_bot_plans'
                    );
                    
                    // NOTIFICATION: Commission Rates Updated (ADMIN)
                    $mail_subject = "Bot Commission Rates Updated";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Trading Bot Commission Rates Updated</h2>
                                        
                                        <p class='message'>
                                            Commission rates for trading bot plans have been updated by an administrator.
                                        </p>

                                        <!-- Update Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                <strong>Update Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                <strong>Plans Updated:</strong> " . count($updated_plans) . "<br>
                                            </div>
                                        </div>

                                        <!-- Commission Changes -->
                                        <div class='settings-comparison'>
                                            <h3 style='color: #2c3e50;'>📈 Commission Rate Changes</h3>
                                            <table style='width: 100%; border-collapse: collapse; margin: 15px 0;'>
                                                <thead>
                                                    <tr style='background: #f8f9fa;'>
                                                        <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>Bot Plan</th>
                                                        <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>Old Rate</th>
                                                        <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>New Rate</th>
                                                        <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>Change</th>
                                                    </tr>
                                                </thead>
                                                <tbody>";
                    
                    foreach ($updated_plans as $plan) {
                        $change_percent = $plan['old'] > 0 ? round((($plan['new'] - $plan['old']) / $plan['old']) * 100, 1) : 0;
                        $change_direction = $plan['new'] > $plan['old'] ? '▲' : '▼';
                        $change_color = $plan['new'] > $plan['old'] ? '#28a745' : '#dc3545';
                        
                        $mail_message .= "<tr>
                                            <td style='border: 1px solid #dee2e6; padding: 10px;'><strong>" . $plan['name'] . "</strong></td>
                                            <td style='border: 1px solid #dee2e6; padding: 10px;'>" . $plan['old'] . "%</td>
                                            <td style='border: 1px solid #dee2e6; padding: 10px;'><span style='color: " . $change_color . "; font-weight: bold;'>" . $plan['new'] . "%</span></td>
                                            <td style='border: 1px solid #dee2e6; padding: 10px;'><span style='color: " . $change_color . ";'>" . $change_direction . " " . abs($change_percent) . "%</span></td>
                                        </tr>";
                    }
                    
                    if (empty($updated_plans)) {
                        $mail_message .= "<tr>
                                            <td style='border: 1px solid #dee2e6; padding: 10px;' colspan='4' align='center'>No commission rates were changed</td>
                                        </tr>";
                    }
                    
                    $mail_message .= "          </tbody>
                                        </table>
                                    </div>

                                    <!-- Platform Impact -->
                                    <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                        <h4 style='color: #0056b3;'>💰 Platform Impact</h4>
                                        <p style='color: #0056b3;'>
                                            These commission rates affect:<br>
                                            • Admin revenue from bot subscriptions<br>
                                            • Bot profitability for users<br>
                                            • Platform competitiveness<br>
                                            • Marketing and promotions
                                        </p>
                                    </div>

                                    <!-- Admin Actions -->
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/bot_plans.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                            View Bot Plans
                                        </a>
                                    </div>

                                    <!-- Support Section -->
                                    <div class='support-section'>
                                        <p class='support-text'>Commission rate changes logged in admin activities.</p>
                                    </div>
                                </div>";
                    
                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Commission rates updated successfully!";
                }
                break;
        }
    }
}

// Get current settings
$settings = array();
$settings_sql = "SELECT setting_key, setting_value FROM system_settings";
$settings_result = mysqli_query($conn, $settings_sql);
while ($row = mysqli_fetch_assoc($settings_result)) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// Get payment methods
$methods_sql = "SELECT * FROM payment_methods ORDER BY is_active DESC, method_name ASC";
$methods_result = mysqli_query($conn, $methods_sql);

// Get bot plans for commission rates
$plans_sql = "SELECT * FROM trading_bot_plans WHERE is_active = 1 ORDER BY sort_order";
$plans_result = mysqli_query($conn, $plans_sql);

// Default values if not set
$default_settings = array(
    'withdrawal_fee' => '1.0',
    'min_withdrawal' => '10.0',
    'max_withdrawal' => '10000.0',
    'min_deposit' => '10.0',
    'max_deposit' => '100000.0',
    'deposit_fee' => '0.0',
    'trading_fee' => '0.1',
    'subscription_fee_discount' => '0.0',
    'referral_commission' => '10.0',
    'affiliate_commission' => '5.0'
);

// Merge with defaults
foreach ($default_settings as $key => $value) {
    if (!isset($settings[$key])) {
        $settings[$key] = $value;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
  	
	
	<body class="hold-transition dark-skin sidebar-mini theme-primary fixed">
		
		<div class="wrapper">
		  	<div id="loader"></div>
		  	
		  <?php include('includes/header.php') ?>

		  <?php include('includes/sidebar.php') ?>

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-credit-card me-2"></i>Payment Settings</h4>
										<p class="mb-0 text-mute">Configure payment methods, fees, and commission rates</p>
									</div>
									<div class="box-body">
										
										<?php if (isset($success)): ?>
											<div class="alert alert-success alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
											</div>
										<?php endif; ?>
										
										<?php if (isset($error)): ?>
											<div class="alert alert-danger alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
											</div>
										<?php endif; ?>
										
										<!-- Tabs -->
										<ul class="nav nav-tabs" role="tablist">
											<li class="nav-item">
												<a class="nav-link active" data-bs-toggle="tab" href="#system">System Settings</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#methods">Payment Methods</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#commissions">Commission Rates</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#history">Change History</a>
											</li>
										</ul>
										
										<div class="tab-content mt-3">
											<!-- System Settings Tab -->
											<div class="tab-pane fade show active" id="system">
												<form method="POST">
													<input type="hidden" name="action_type" value="update_system_settings">
													
													<div class="row">
														<div class="col-md-6">
															<h5 class="mb-3"><i class="fas fa-download me-2"></i>Deposit Settings</h5>
															<div class="mb-3">
																<label class="form-label">Minimum Deposit ($)</label>
																<div class="input-group">
																	<span class="input-group-text">$</span>
																	<input type="number" class="form-control" name="min_deposit" step="0.01" min="0" value="<?php echo htmlspecialchars($settings['min_deposit']); ?>" required>
																</div>
																<small class="text-mute">Minimum amount users can deposit</small>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Maximum Deposit ($)</label>
																<div class="input-group">
																	<span class="input-group-text">$</span>
																	<input type="number" class="form-control" name="max_deposit" step="0.01" min="0" value="<?php echo htmlspecialchars($settings['max_deposit']); ?>" required>
																</div>
																<small class="text-mute">Maximum amount users can deposit (0 for unlimited)</small>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Deposit Fee (%)</label>
																<div class="input-group">
																	<input type="number" class="form-control" name="deposit_fee" step="0.01" min="0" max="100" value="<?php echo htmlspecialchars($settings['deposit_fee']); ?>" required>
																	<span class="input-group-text">%</span>
																</div>
																<small class="text-mute">Fee charged on deposits (0 for no fee)</small>
															</div>
														</div>
														
														<div class="col-md-6">
															<h5 class="mb-3"><i class="fas fa-upload me-2"></i>Withdrawal Settings</h5>
															<div class="mb-3">
																<label class="form-label">Withdrawal Fee (%)</label>
																<div class="input-group">
																	<input type="number" class="form-control" name="withdrawal_fee" step="0.01" min="0" max="100" value="<?php echo htmlspecialchars($settings['withdrawal_fee']); ?>" required>
																	<span class="input-group-text">%</span>
																</div>
																<small class="text-mute">Fee charged on withdrawals</small>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Minimum Withdrawal ($)</label>
																<div class="input-group">
																	<span class="input-group-text">$</span>
																	<input type="number" class="form-control" name="min_withdrawal" step="0.01" min="0" value="<?php echo htmlspecialchars($settings['min_withdrawal']); ?>" required>
																</div>
																<small class="text-mute">Minimum amount users can withdraw</small>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Maximum Withdrawal ($)</label>
																<div class="input-group">
																	<span class="input-group-text">$</span>
																	<input type="number" class="form-control" name="max_withdrawal" step="0.01" min="0" value="<?php echo htmlspecialchars($settings['max_withdrawal']); ?>" required>
																</div>
																<small class="text-mute">Maximum amount users can withdraw per day (0 for unlimited)</small>
															</div>
														</div>
													</div>
													
													<div class="row mt-4">
														<div class="col-md-6">
															<h5 class="mb-3"><i class="fas fa-percentage me-2"></i>Fee Settings</h5>
															<div class="mb-3">
																<label class="form-label">Trading Fee (%)</label>
																<div class="input-group">
																	<input type="number" class="form-control" name="trading_fee" step="0.01" min="0" max="100" value="<?php echo htmlspecialchars($settings['trading_fee']); ?>" required>
																	<span class="input-group-text">%</span>
																</div>
																<small class="text-mute">Fee charged on each trade</small>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Subscription Fee Discount (%)</label>
																<div class="input-group">
																	<input type="number" class="form-control" name="subscription_fee_discount" step="0.01" min="0" max="100" value="<?php echo htmlspecialchars($settings['subscription_fee_discount']); ?>" required>
																	<span class="input-group-text">%</span>
																</div>
																<small class="text-mute">Discount applied to bot subscription fees</small>
															</div>
														</div>
														
														<div class="col-md-6">
															<h5 class="mb-3"><i class="fas fa-handshake me-2"></i>Commission Settings</h5>
															<div class="mb-3">
																<label class="form-label">Referral Commission (%)</label>
																<div class="input-group">
																	<input type="number" class="form-control" name="referral_commission" step="0.01" min="0" max="100" value="<?php echo htmlspecialchars($settings['referral_commission']); ?>" required>
																	<span class="input-group-text">%</span>
																</div>
																<small class="text-mute">Commission paid to referrers</small>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Affiliate Commission (%)</label>
																<div class="input-group">
																	<input type="number" class="form-control" name="affiliate_commission" step="0.01" min="0" max="100" value="<?php echo htmlspecialchars($settings['affiliate_commission']); ?>" required>
																	<span class="input-group-text">%</span>
																</div>
																<small class="text-mute">Commission paid to affiliates</small>
															</div>
														</div>
													</div>
													
													<div class="row mt-4">
														<div class="col-12">
															<h5 class="mb-3"><i class="fas fa-lock me-2"></i>Security Confirmation</h5>
															<div class="mb-3 col-md-4">
																<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
																<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
																<small class="text-mute">Required to save changes</small>
															</div>
														</div>
													</div>
													
													<div class="mt-4">
														<button type="submit" class="btn btn-primary">
															<i class="fas fa-save me-1"></i> Save All Settings
														</button>
														<button type="reset" class="btn btn-secondary">
															<i class="fas fa-undo me-1"></i> Reset to Defaults
														</button>
													</div>
												</form>
											</div>
											
											<!-- Payment Methods Tab -->
											<div class="tab-pane fade" id="methods">
												<div class="d-flex justify-content-between align-items-center mb-3">
													<h5>Payment Methods</h5>
													<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMethodModal">
														<i class="fas fa-plus me-1"></i> Add Payment Method
													</button>
												</div>
												
												<?php if (mysqli_num_rows($methods_result) > 0): ?>
													<div class="table-responsive">
														<table class="table table-hover">
															<thead>
																<tr>
																	<th>Method</th>
																	<th>Network</th>
																	<th>Wallet Address</th>
																	<th>Min Amount</th>
																	<th>Max Amount</th>
																	<th>Status</th>
																	<th>Actions</th>
																</tr>
															</thead>
															<tbody>
																<?php while ($method = mysqli_fetch_assoc($methods_result)): ?>
																	<tr>
																		<td>
																			<div class="d-flex align-items-center">
																				<div class="me-10">
																					<div class="bg-primary rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																						<i class="fas fa-wallet text-white"></i>
																					</div>
																				</div>
																				<div>
																					<p class="mb-0 fw-500"><?php echo htmlspecialchars($method['method_name']); ?></p>
																					<small class="text-mute">Added: <?php echo date('M d, Y', strtotime($method['created_at'])); ?></small>
																				</div>
																			</div>
																		</td>
																		<td>
																			<span class="badge bg-info"><?php echo htmlspecialchars($method['network']); ?></span>
																		</td>
																		<td>
																			<code class="text-truncate d-inline-block" style="max-width: 200px;" title="<?php echo htmlspecialchars($method['wallet_address']); ?>">
																				<?php echo htmlspecialchars($method['wallet_address']); ?>
																			</code>
																		</td>
																		<td>$<?php echo number_format($method['min_amount'], 2); ?></td>
																		<td>
																			<?php if ($method['max_amount'] > 0): ?>
																				$<?php echo number_format($method['max_amount'], 2); ?>
																			<?php else: ?>
																				<span class="text-mute">Unlimited</span>
																			<?php endif; ?>
																		</td>
																		<td>
																			<?php if ($method['is_active']): ?>
																				<span class="badge bg-success"><i class="fas fa-check me-1"></i> Active</span>
																			<?php else: ?>
																				<span class="badge bg-danger"><i class="fas fa-times me-1"></i> Inactive</span>
																			<?php endif; ?>
																		</td>
																		<td>
																			<div class="btn-group">
																				<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
																					<i class="fas fa-cog"></i>
																				</button>
																				<div class="dropdown-menu">
																					<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#editMethodModal" data-method-id="<?php echo $method['id']; ?>" data-method-name="<?php echo htmlspecialchars($method['method_name']); ?>" data-network="<?php echo htmlspecialchars($method['network']); ?>" data-wallet-address="<?php echo htmlspecialchars($method['wallet_address']); ?>" data-is-active="<?php echo $method['is_active']; ?>" data-min-amount="<?php echo $method['min_amount']; ?>" data-max-amount="<?php echo $method['max_amount']; ?>">
																						<i class="fas fa-edit me-2"></i> Edit
																					</a>
																					<a class="dropdown-item text-danger" href="#" onclick="confirmDeleteMethod(<?php echo $method['id']; ?>, '<?php echo htmlspecialchars($method['method_name']); ?>')">
																						<i class="fas fa-trash me-2"></i> Delete
																					</a>
																				</div>
																			</div>
																		</td>
																	</tr>
																<?php endwhile; ?>
															</tbody>
														</table>
													</div>
												<?php else: ?>
													<div class="alert alert-info">
														<i class="fas fa-info-circle me-2"></i> No payment methods configured yet.
													</div>
												<?php endif; ?>
											</div>
											
											<!-- Commission Rates Tab -->
											<div class="tab-pane fade" id="commissions">
												<form method="POST">
													<input type="hidden" name="action_type" value="update_commission_rates">
													
													<h5 class="mb-3">Bot Plan Commission Rates</h5>
													<p class="text-mute mb-4">Set commission percentages for each trading bot plan</p>
													
													<?php if (mysqli_num_rows($plans_result) > 0): ?>
														<div class="row">
															<?php while ($plan = mysqli_fetch_assoc($plans_result)): ?>
																<div class="col-md-6 mb-4">
																	<div class="box">
																		<div class="box-header">
																			<h6 class="box-title"><?php echo htmlspecialchars($plan['plan_name']); ?></h6>
																			<span class="badge bg-primary">$<?php echo number_format($plan['subscription_fee'], 2); ?>/month</span>
																		</div>
																		<div class="box-body">
																			<div class="mb-3">
																				<label class="form-label">Commission Rate (%)</label>
																				<div class="input-group">
																					<input type="number" class="form-control" name="plan_commissions[<?php echo $plan['id']; ?>]" step="0.01" min="0" max="100" value="<?php echo isset($plan['commission_rate']) ? $plan['commission_rate'] : '5.00'; ?>" required>
																					<span class="input-group-text">%</span>
																				</div>
																				<small class="text-mute">Commission earned from this plan's subscriptions</small>
																			</div>
																			
																			<div class="row">
																				<div class="col-6">
																					<p class="mb-1"><strong>Min Balance:</strong></p>
																					<p>$<?php echo number_format($plan['min_trading_balance'], 2); ?></p>
																				</div>
																				<div class="col-6">
																					<p class="mb-1"><strong>Daily ROI:</strong></p>
																					<p><?php echo $plan['daily_roi_percentage']; ?>%</p>
																				</div>
																			</div>
																		</div>
																	</div>
																</div>
															<?php endwhile; ?>
														</div>
														
														<div class="mt-4">
															<h5 class="mb-3">Security Confirmation</h5>
															<div class="mb-3 col-md-4">
																<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
																<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
																<small class="text-mute">Required to save changes</small>
															</div>
															
															<button type="submit" class="btn btn-primary">
																<i class="fas fa-save me-1"></i> Update Commission Rates
															</button>
														</div>
													<?php else: ?>
														<div class="alert alert-info">
															<i class="fas fa-info-circle me-2"></i> No active bot plans found.
														</div>
													<?php endif; ?>
												</form>
											</div>
											
											<!-- Change History Tab -->
											<div class="tab-pane fade" id="history">
												<h5 class="mb-3">Payment Settings Change History</h5>
												<p class="text-mute mb-4">Recent changes to payment settings</p>
												
												<?php
												// Get recent admin activities related to payment settings
												$history_sql = "SELECT * FROM admin_activities 
															   WHERE module = 'Settings' 
															   ORDER BY created_at DESC 
															   LIMIT 20";
												$history_result = mysqli_query($conn, $history_sql);
												?>
												
												<?php if (mysqli_num_rows($history_result) > 0): ?>
													<div class="timeline">
														<?php while ($activity = mysqli_fetch_assoc($history_result)): ?>
															<div class="timeline-item">
																<div class="timeline-point"></div>
																<div class="timeline-content">
																	<div class="d-flex justify-content-between">
																		<div>
																			<h6 class="mb-1"><?php echo htmlspecialchars($activity['action']); ?></h6>
																			<p class="mb-1"><?php echo htmlspecialchars($activity['description']); ?></p>
																		</div>
																		<small class="text-mute"><?php echo date('M d, Y H:i', strtotime($activity['created_at'])); ?></small>
																	</div>
																	<div class="mt-2">
																		<small>
																			<i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($activity['admin_name']); ?>
																			<span class="badge bg-secondary ms-2"><?php echo $activity['admin_role']; ?></span>
																		</small>
																	</div>
																</div>
															</div>
														<?php endwhile; ?>
													</div>
												<?php else: ?>
													<div class="alert alert-info">
														<i class="fas fa-info-circle me-2"></i> No change history found.
													</div>
												<?php endif; ?>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Adding/Editing Payment Method -->
		<div class="modal fade" id="addMethodModal" tabindex="-1" aria-labelledby="addMethodModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="addMethodModalLabel">Add Payment Method</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="update_payment_method">
							<input type="hidden" name="method_id" id="methodId" value="0">
							
							<div class="mb-3">
								<label class="form-label">Method Name <span class="text-danger">*</span></label>
								<input type="text" class="form-control" name="method_name" id="methodName" required placeholder="e.g., USDT (TRC20)">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Network <span class="text-danger">*</span></label>
								<input type="text" class="form-control" name="network" id="network" required placeholder="e.g., TRC20, ERC20, BEP20">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Wallet Address <span class="text-danger">*</span></label>
								<textarea class="form-control" name="wallet_address" id="walletAddress" rows="3" required placeholder="Enter wallet address..."></textarea>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Minimum Amount ($)</label>
										<input type="number" class="form-control" name="min_amount" id="minAmount" step="0.01" min="0" value="10.00">
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Maximum Amount ($)</label>
										<input type="number" class="form-control" name="max_amount" id="maxAmount" step="0.01" min="0" value="0">
										<small class="text-mute">0 for unlimited</small>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<div class="form-check form-switch">
									<input class="form-check-input" type="checkbox" name="is_active" id="isActive" value="1" checked>
									<label class="form-check-label" for="isActive">Active</label>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Save Method</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Hidden form for deleting payment methods -->
		<form method="POST" id="deleteMethodForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_payment_method">
			<input type="hidden" name="method_id" id="deleteMethodId">
			<input type="hidden" name="admin_pin" id="deleteMethodPin">
		</form>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<script>
		$(document).ready(function() {
			// Edit Payment Method Modal
			$('#editMethodModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var methodId = button.data('method-id');
				var methodName = button.data('method-name');
				var network = button.data('network');
				var walletAddress = button.data('wallet-address');
				var isActive = button.data('is-active');
				var minAmount = button.data('min-amount');
				var maxAmount = button.data('max-amount');
				
				var modal = $(this);
				modal.find('#methodId').val(methodId);
				modal.find('#methodName').val(methodName);
				modal.find('#network').val(network);
				modal.find('#walletAddress').val(walletAddress);
				modal.find('#minAmount').val(minAmount);
				modal.find('#maxAmount').val(maxAmount);
				modal.find('#isActive').prop('checked', isActive == 1);
				modal.find('.modal-title').text('Edit Payment Method');
			});
			
			// Reset add modal when shown
			$('#addMethodModal').on('show.bs.modal', function () {
				var modal = $(this);
				modal.find('#methodId').val(0);
				modal.find('#methodName').val('');
				modal.find('#network').val('');
				modal.find('#walletAddress').val('');
				modal.find('#minAmount').val('10.00');
				modal.find('#maxAmount').val('0');
				modal.find('#isActive').prop('checked', true);
				modal.find('.modal-title').text('Add Payment Method');
			});
			
			// Tab persistence
			$('a[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
				localStorage.setItem('activePaymentTab', $(e.target).attr('href'));
			});
			
			// Restore active tab
			var activeTab = localStorage.getItem('activePaymentTab');
			if (activeTab) {
				$('.nav-tabs a[href="' + activeTab + '"]').tab('show');
			}
		});
		
		// Confirm Delete Payment Method
		function confirmDeleteMethod(methodId, methodName) {
			Swal.fire({
				title: 'Delete Payment Method?',
				html: `
					<p>You are about to delete payment method: <strong>${methodName}</strong></p>
					<p class="text-danger">This action cannot be undone!</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete Method',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					document.getElementById('deleteMethodId').value = methodId;
					document.getElementById('deleteMethodPin').value = result.value.pin;
					document.getElementById('deleteMethodForm').submit();
				}
			});
		}
		
		// Validate form before submission
		function validateSettings(form) {
			var minDeposit = parseFloat(form.min_deposit.value);
			var maxDeposit = parseFloat(form.max_deposit.value);
			var minWithdrawal = parseFloat(form.min_withdrawal.value);
			var maxWithdrawal = parseFloat(form.max_withdrawal.value);
			
			if (maxDeposit > 0 && minDeposit > maxDeposit) {
				Swal.fire('Error', 'Minimum deposit cannot be greater than maximum deposit', 'error');
				return false;
			}
			
			if (maxWithdrawal > 0 && minWithdrawal > maxWithdrawal) {
				Swal.fire('Error', 'Minimum withdrawal cannot be greater than maximum withdrawal', 'error');
				return false;
			}
			
			return true;
		}
		</script>
		
		<style>
		.nav-tabs .nav-link.active {
			background-color: #f8f9fa;
			border-color: #dee2e6 #dee2e6 #f8f9fa;
		}
		
		.timeline {
			position: relative;
			padding-left: 30px;
		}
		
		.timeline-item {
			position: relative;
			padding-bottom: 20px;
			border-left: 2px solid #e9ecef;
			padding-left: 30px;
		}
		
		.timeline-point {
			position: absolute;
			left: -8px;
			top: 0;
			width: 14px;
			height: 14px;
			border-radius: 50%;
			background-color: #0d6efd;
			border: 2px solid white;
		}
		
		.timeline-content {
			padding: 10px;
			background-color: #f8f9fa;
			border-radius: 5px;
			margin-bottom: 10px;
		}
		
		.timeline-item:last-child {
			border-left: 2px solid transparent;
		}
		
		.form-check-input:checked {
			background-color: #0d6efd;
			border-color: #0d6efd;
		}
		
		code {
			background-color: #f8f9fa;
			padding: 2px 5px;
			border-radius: 3px;
			font-size: 12px;
		}
		
		.input-group-text {
			background-color: #f8f9fa;
		}
		</style>
		
	</body>
</html>