<?php
// Include required files
require_once '../../config/database.php';
require_once '../../models/user.php';
require_once '../../models/product.php';
require_once '../../models/order.php';

// Initialize database
$database = new Database();
$db = $database->getConnection();

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in and is admin - DISABLED
// if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
//     header('Location: login.php');
//     exit;
// }

// Get user data
$user_model = new User($db);
$user_data = $user_model->getUserById($_SESSION['user_id']);

// Get models
$order_model = new Order($db);

// Get payment methods
$query = "SELECT * FROM payment_methods ORDER BY id";
$stmt = $db->prepare($query);
$stmt->execute();
$payment_methods = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get payment accounts
$query = "SELECT pa.*, pm.name as payment_method_name, pm.code as payment_method_code
          FROM payment_accounts pa
          JOIN payment_methods pm ON pa.payment_method_id = pm.id
          ORDER BY pm.id, pa.account_name";
$stmt = $db->prepare($query);
$stmt->execute();
$payment_accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Check for payment account limit alerts
$limit_alerts = $order_model->checkPaymentAccountLimits();

// Handle admin actions
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['toggle_payment_method'])) {
        $method_id = $_POST['method_id'];
        $is_active = $_POST['is_active'] ? 1 : 0;

        $query = "UPDATE payment_methods SET is_active = ? WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->bindParam(1, $is_active);
        $stmt->bindParam(2, $method_id);

        if ($stmt->execute()) {
            $message = $is_active ? 'تم تفعيل طريقة الدفع بنجاح!' : 'تم تعطيل طريقة الدفع بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء تحديث حالة طريقة الدفع';
        }
    } elseif (isset($_POST['update_payment_settings'])) {
        // Update payment methods active status
        $methods = [
            'cash_on_delivery' => $_POST['cash_on_delivery_enabled'] ?? 0,
            'fawry' => $_POST['fawry_enabled'] ?? 0,
            'vodafone_cash' => $_POST['vodafone_cash_enabled'] ?? 0,
            'instapay' => $_POST['instapay_enabled'] ?? 0,
            'paymob' => $_POST['paymob_enabled'] ?? 0
        ];
        foreach ($methods as $code => $active) {
            $active = $active ? 1 : 0;
            $query = "UPDATE payment_methods SET is_active = ? WHERE code = ?";
            $stmt = $db->prepare($query);
            $stmt->bindParam(1, $active);
            $stmt->bindParam(2, $code);
            $stmt->execute();
        }

        $message = 'تم حفظ إعدادات الدفع بنجاح!';
    } elseif (isset($_POST['update_fawry_config'])) {
        $merchant_code = $_POST['merchant_code'] ?? '';
        $api_key = $_POST['api_key'] ?? '';
        $config = json_encode(['merchant_code' => $merchant_code, 'api_key' => $api_key]);

        $query = "UPDATE payment_methods SET integration_config = ? WHERE code = 'fawry'";
        $stmt = $db->prepare($query);
        $stmt->bindParam(1, $config);

        if ($stmt->execute()) {
            $message = 'تم حفظ إعدادات فوري بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء حفظ إعدادات فوري';
        }
    } elseif (isset($_POST['update_paymob_config'])) {
        $api_key = $_POST['api_key'] ?? '';
        $hmac_secret = $_POST['hmac_secret'] ?? '';
        $config = json_encode(['api_key' => $api_key, 'hmac_secret' => $hmac_secret]);

        $query = "UPDATE payment_methods SET integration_config = ? WHERE code = 'paymob'";
        $stmt = $db->prepare($query);
        $stmt->bindParam(1, $config);

        if ($stmt->execute()) {
            $message = 'تم حفظ إعدادات باي موب بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء حفظ إعدادات باي موب';
        }
    } elseif (isset($_POST['add_payment_account'])) {
        $payment_method_id = $_POST['payment_method_id'];
        $account_name = $_POST['account_name'];
        $account_number = $_POST['account_number'];
        $account_holder = $_POST['account_holder'];
        $daily_limit = $_POST['daily_limit'] ?? 0;

        $query = "INSERT INTO payment_accounts (payment_method_id, account_name, account_number, account_holder, daily_limit) VALUES (?, ?, ?, ?, ?)";
        $stmt = $db->prepare($query);
        $stmt->bindParam(1, $payment_method_id);
        $stmt->bindParam(2, $account_name);
        $stmt->bindParam(3, $account_number);
        $stmt->bindParam(4, $account_holder);
        $stmt->bindParam(5, $daily_limit);

        if ($stmt->execute()) {
            $message = 'تم إضافة حساب الدفع بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء إضافة حساب الدفع';
        }
    } elseif (isset($_POST['edit_payment_account'])) {
        $account_id = $_POST['account_id'];
        $account_name = $_POST['account_name'];
        $account_number = $_POST['account_number'];
        $account_holder = $_POST['account_holder'];
        $daily_limit = $_POST['daily_limit'] ?? 0;
        $is_active = $_POST['is_active'] ? 1 : 0;

        $query = "UPDATE payment_accounts SET account_name = ?, account_number = ?, account_holder = ?, daily_limit = ?, is_active = ? WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->bindParam(1, $account_name);
        $stmt->bindParam(2, $account_number);
        $stmt->bindParam(3, $account_holder);
        $stmt->bindParam(4, $daily_limit);
        $stmt->bindParam(5, $is_active);
        $stmt->bindParam(6, $account_id);

        if ($stmt->execute()) {
            $message = 'تم تحديث حساب الدفع بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء تحديث حساب الدفع';
        }
    } elseif (isset($_POST['delete_payment_account'])) {
        $account_id = $_POST['account_id'];

        $query = "DELETE FROM payment_accounts WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->bindParam(1, $account_id);

        if ($stmt->execute()) {
            $message = 'تم حذف حساب الدفع بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء حذف حساب الدفع';
        }
    }
}

// Get payment methods enabled status
$cod_method = array_filter($payment_methods, fn($m) => $m['code'] === 'cash_on_delivery');
$cod_enabled = !empty($cod_method) ? reset($cod_method)['is_active'] : 0;

$fawry_method = array_filter($payment_methods, fn($m) => $m['code'] === 'fawry');
$fawry_enabled = !empty($fawry_method) ? reset($fawry_method)['is_active'] : 0;
$fawry_config = !empty($fawry_method) ? json_decode(reset($fawry_method)['integration_config'], true) : [];

$vodafone_method = array_filter($payment_methods, fn($m) => $m['code'] === 'vodafone_cash');
$vodafone_enabled = !empty($vodafone_method) ? reset($vodafone_method)['is_active'] : 0;

$instapay_method = array_filter($payment_methods, fn($m) => $m['code'] === 'instapay');
$instapay_enabled = !empty($instapay_method) ? reset($instapay_method)['is_active'] : 0;

$paymob_method = array_filter($payment_methods, fn($m) => $m['code'] === 'paymob');
$paymob_enabled = !empty($paymob_method) ? reset($paymob_method)['is_active'] : 0;
$paymob_config = !empty($paymob_method) ? json_decode(reset($paymob_method)['integration_config'], true) : [];

// Get payment statistics
$all_orders = $order_model->getAllOrders();
$total_orders = count($all_orders);

// Payment methods statistics
$cod_orders = array_filter($all_orders, function($order) {
    return $order['payment_method'] === 'cash_on_delivery';
});
$fawry_orders = array_filter($all_orders, function($order) {
    return $order['payment_method'] === 'fawry';
});
$vodafone_orders = array_filter($all_orders, function($order) {
    return $order['payment_method'] === 'vodafone_cash';
});
$paymob_orders = array_filter($all_orders, function($order) {
    return $order['payment_method'] === 'paymob';
});
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة الدفع - لوحة تحكم المدير</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            font-family: 'Tajawal', sans-serif;
            direction: rtl;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen" style="background-attachment: fixed;">

    <!-- Header -->
    <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
        <div class="flex items-center justify-between px-6 py-3">
            <div class="flex items-center">
                <button onclick="window.location.href='admin.php'" class="p-2 rounded-lg text-gray-600 hover:bg-gray-100 transition-all duration-200 mr-3">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                </button>
                <div class="flex items-center ml-4">
                    <?php if ($user_data['profile_picture']): ?>
                        <img src="<?php echo htmlspecialchars($user_data['profile_picture']); ?>" alt="صورة الملف الشخصي" class="w-8 h-8 rounded-lg mr-3 object-cover">
                    <?php else: ?>
                        <div class="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white font-bold text-sm mr-3">
                            R
                        </div>
                    <?php endif; ?>
                    <h1 class="text-xl font-semibold text-gray-900">إدارة الدفع</h1>
                </div>
            </div>
            <div class="flex items-center space-x-4 space-x-reverse">
                <a href="index.php" class="p-2 rounded-md text-gray-600 hover:bg-gray-100" title="المتجر">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                    </svg>
                </a>
                <a href="#" class="p-2 rounded-md text-gray-600 hover:bg-gray-100" title="الحساب">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                    </svg>
                </a>
                <a href="logout.php" class="p-2 rounded-md text-gray-600 hover:bg-gray-100" title="تسجيل الخروج">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                    </svg>
                </a>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="flex-1 flex flex-col min-w-0">
        <div class="p-4 lg:p-6 xl:p-8 flex-1 overflow-auto">

            <!-- Success/Error Message Display -->
            <!-- Payment Account Limit Alerts -->
            <?php if (!empty($limit_alerts)): ?>
                <div class="bg-yellow-50 border-r-4 border-yellow-400 p-4 mb-6">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <svg class="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <div class="mr-3 flex-1">
                            <h3 class="text-sm font-medium text-yellow-800">تنبيهات حدود الحسابات المالية</h3>
                            <div class="mt-2 space-y-2">
                                <?php foreach ($limit_alerts as $alert): ?>
                                    <div class="text-sm text-yellow-700">
                                        <?php if ($alert['is_exceeded']): ?>
                                            <strong>تم تجاوز الحد اليومي!</strong>
                                        <?php else: ?>
                                            <strong>اقتراب من الحد اليومي</strong>
                                        <?php endif; ?>
                                        حساب <?php echo htmlspecialchars($alert['payment_method']); ?> -
                                        <?php echo htmlspecialchars($alert['account_name']); ?>
                                        (<?php echo htmlspecialchars($alert['account_number']); ?>):
                                        <?php echo number_format($alert['current_amount'], 0, ',', ','); ?> EGP من
                                        <?php echo number_format($alert['daily_limit'], 0, ',', ','); ?> EGP
                                        (<?php echo $alert['percentage']; ?>%)
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($message): ?>
                <div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <svg class="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <div class="mr-3">
                            <p class="text-sm text-green-700"><?php echo $message; ?></p>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Breadcrumb -->
            <div class="mb-6">
                <nav class="flex text-sm text-gray-500">
                    <a href="admin.php" class="hover:text-purple-600">لوحة التحكم</a>
                    <span class="mx-2">/</span>
                    <span class="text-gray-900">إدارة الدفع</span>
                </nav>
            </div>

            <!-- Payment Statistics -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <!-- Total Payments -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all duration-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">إجمالي المدفوعات</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo $total_orders; ?></p>
                        </div>
                        <div class="bg-emerald-50 p-3 rounded-lg">
                            <svg class="w-6 h-6 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2-2z"></path>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a2 2 0 012-2h0a2 2 0 012 2v1a2 2 0 01-2 2H9a2 2 0 01-2-2v-1z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-emerald-600 text-sm font-medium">جميع طرق الدفع</span>
                    </div>
                </div>

                <!-- Cash on Delivery -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all duration-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">الدفع عند الاستلام</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo count($cod_orders); ?></p>
                        </div>
                        <div class="bg-blue-50 p-3 rounded-lg">
                            <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2-2z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-blue-600 text-sm font-medium"><?php echo $total_orders > 0 ? round((count($cod_orders) / $total_orders) * 100, 1) : 0; ?>% من الإجمالي</span>
                    </div>
                </div>

                <!-- Fawry -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all duration-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">فوري</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo count($fawry_orders); ?></p>
                        </div>
                        <div class="bg-orange-50 p-3 rounded-lg">
                            <svg class="w-6 h-6 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-orange-600 text-sm font-medium"><?php echo $total_orders > 0 ? round((count($fawry_orders) / $total_orders) * 100, 1) : 0; ?>% من الإجمالي</span>
                    </div>
                </div>

                <!-- Vodafone Cash -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all duration-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">فودافون كاش</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo count($vodafone_orders); ?></p>
                        </div>
                        <div class="bg-red-50 p-3 rounded-lg">
                            <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-red-600 text-sm font-medium"><?php echo $total_orders > 0 ? round((count($vodafone_orders) / $total_orders) * 100, 1) : 0; ?>% من الإجمالي</span>
                    </div>
                </div>

                <!-- Paymob -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all duration-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">باي موب</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo count($paymob_orders); ?></p>
                        </div>
                        <div class="bg-purple-50 p-3 rounded-lg">
                            <svg class="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-purple-600 text-sm font-medium"><?php echo $total_orders > 0 ? round((count($paymob_orders) / $total_orders) * 100, 1) : 0; ?>% من الإجمالي</span>
                    </div>
                </div>
            </div>

            <!-- Payment Methods Management -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                <?php foreach ($payment_methods as $method): ?>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                    <div class="px-6 py-4 border-b border-gray-200">
                        <div class="flex items-center justify-between">
                            <h3 class="text-lg font-medium text-gray-900 flex items-center">
                                <i class="fas <?php echo $method['icon_class'] ?? 'fa-credit-card'; ?> <?php echo $method['color_class'] ?? 'text-gray-600'; ?> ml-3"></i>
                                <?php echo htmlspecialchars($method['name']); ?>
                            </h3>
                            <div class="flex items-center space-x-2 space-x-reverse">
                                <span class="text-sm text-gray-500"><?php echo $method['is_active'] ? 'مفعل' : 'معطل'; ?></span>
                                <label class="inline-flex items-center cursor-pointer">
                                    <input type="checkbox"
                                           onchange="togglePaymentMethod(<?php echo $method['id']; ?>, this.checked)"
                                           <?php echo $method['is_active'] ? 'checked' : ''; ?>
                                           class="sr-only peer">
                                    <div class="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="p-6">
                        <div class="space-y-4">
                            <div class="bg-blue-50 border-r-4 border-blue-400 p-4 rounded-lg">
                                <h4 class="font-semibold text-blue-900 mb-2">وصف الطريقة</h4>
                                <p class="text-blue-800 text-sm"><?php echo htmlspecialchars($method['description']); ?></p>
                            </div>
                            <?php
                            $method_orders = array_filter($all_orders, function($order) use ($method) {
                                return $order['payment_method'] === $method['code'];
                            });
                            ?>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <p class="text-sm text-gray-600">عدد الطلبات</p>
                                    <p class="text-2xl font-bold text-gray-900"><?php echo count($method_orders); ?></p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-600">نسبة الاستخدام</p>
                                    <p class="text-2xl font-bold text-gray-900"><?php echo $total_orders > 0 ? round((count($method_orders) / $total_orders) * 100, 1) : 0; ?>%</p>
                                </div>
                            </div>
                            <?php if ($method['code'] === 'fawry'): ?>
                            <div class="border-t pt-4">
                                <button onclick="window.location.href='fawry_api.php'" class="w-full bg-orange-600 hover:bg-orange-700 text-white px-4 py-2 rounded-md font-medium transition-colors duration-150 inline-flex items-center justify-center">
                                    <i class="fas fa-cog ml-2"></i>
                                    إعدادات فوري
                                </button>
                            <?php endif; ?>
                            <?php if ($method['code'] === 'paymob'): ?>
                            <div class="border-t pt-4">
                                <button onclick="showPaymobModal()" class="w-full bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md font-medium transition-colors duration-150 inline-flex items-center justify-center">
                                    <i class="fas fa-cog ml-2"></i>
                                    إعدادات باي موب
                                </button>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>

                <!-- Payment Accounts Management -->
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 lg:col-span-2">
                    <div class="px-6 py-4 border-b border-gray-200">
                        <h3 class="text-lg font-medium text-gray-900 flex items-center justify-between">
                            <span class="flex items-center">
                                <i class="fas fa-university text-blue-600 ml-3"></i>
                                إدارة حسابات الدفع
                            </span>
                            <button onclick="showAddAccountModal()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md font-medium transition-colors duration-150 inline-flex items-center">
                                <i class="fas fa-plus ml-2"></i>
                                إضافة حساب
                            </button>
                        </h3>
                    </div>
                    <div class="p-6">
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">طريقة الدفع</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">اسم الحساب</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">رقم الحساب</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الحد اليومي</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">المبلغ الحالي</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الحالة</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الإجراءات</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    <?php foreach ($payment_accounts as $account): ?>
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                            <?php echo htmlspecialchars($account['payment_method_name']); ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <?php echo htmlspecialchars($account['account_name']); ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <?php echo htmlspecialchars($account['account_number']); ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            EGP <?php echo number_format($account['daily_limit'], 0, ',', ','); ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            EGP <?php echo number_format($account['current_daily_amount'], 0, ',', ','); ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $account['is_active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                                <?php echo $account['is_active'] ? 'فعال' : 'معطل'; ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <button onclick="editAccount(<?php echo $account['id']; ?>, '<?php echo addslashes($account['account_name']); ?>', '<?php echo addslashes($account['account_number']); ?>', '<?php echo addslashes($account['account_holder']); ?>', <?php echo $account['daily_limit']; ?>, <?php echo $account['is_active']; ?>)" class="text-blue-600 hover:text-blue-900 ml-2">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button onclick="deleteAccount(<?php echo $account['id']; ?>)" class="text-red-600 hover:text-red-900 ml-2">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($payment_accounts)): ?>
                                    <tr>
                                        <td colspan="7" class="px-6 py-12 text-center">
                                            <div class="text-gray-400">
                                                <i class="fas fa-university text-4xl mb-4"></i>
                                                <p>لا توجد حسابات دفع مضافة</p>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Payment Transactions -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-900">أحدث المعاملات المالية</h3>
                </div>
                <div class="overflow-x-auto">
                    <?php if (!empty($all_orders)): ?>
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">رقم الطلب</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">العميل</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">طريقة الدفع</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">المبلغ</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الحالة</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">التاريخ</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php
                                $recent_orders = array_slice($all_orders, 0, 10);
                                foreach ($recent_orders as $order):
                                ?>
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">#<?php echo $order['id']; ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo htmlspecialchars($order['customer_name']); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="flex items-center">
                                                <?php
                                                $payment_icons = [
                                                    'cash_on_delivery' => ['fas fa-hand-holding-usd', 'text-blue-600'],
                                                    'fawry' => ['fas fa-mobile-alt', 'text-orange-600'],
                                                                                                    'vodafone_cash' => ['fas fa-wallet', 'text-red-600'],
                                                                                                    'instapay' => ['fas fa-university', 'text-purple-600'],
                                                                                                    'paymob' => ['fas fa-credit-card', 'text-indigo-600']                                                ];
                                                $method = $order['payment_method'] ?? 'cash_on_delivery';
                                                $method_name = $order['payment_method_name'] ?? 'الدفع عند الاستلام';
                                                $icon_class = $payment_icons[$method] ?? $payment_icons['cash_on_delivery'];
                                                ?>
                                                <i class="fas <?php echo $icon_class[0]; ?> <?php echo $icon_class[1]; ?> ml-2"></i>
                                                <span class="text-sm text-gray-900"><?php echo $method_name; ?></span>
                                                <?php if (!empty($order['account_name'])): ?>
                                                    <br><small class="text-gray-500"><?php echo htmlspecialchars($order['account_name']); ?> (<?php echo htmlspecialchars($order['account_number']); ?>)</small>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">EGP <?php echo number_format($order['total_amount'], 0, ',', ','); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <?php
                                            $status_classes = [
                                                'pending' => 'bg-yellow-100 text-yellow-800',
                                                'processing' => 'bg-blue-100 text-blue-800',
                                                'shipped' => 'bg-indigo-100 text-indigo-800',
                                                'delivered' => 'bg-green-100 text-green-800',
                                                'cancelled' => 'bg-red-100 text-red-800'
                                            ];
                                            $status_class = $status_classes[$order['status']] ?? 'bg-gray-100 text-gray-800';
                                            $status_ar = [
                                                'pending' => 'في الانتظار',
                                                'processing' => 'قيد المعالجة',
                                                'shipped' => 'تم الشحن',
                                                'delivered' => 'تم التسليم',
                                                'cancelled' => 'ملغي'
                                            ];
                                            ?>
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $status_class; ?>">
                                                <?php echo $status_ar[$order['status']] ?? $order['status']; ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo date('Y-m-d H:i', strtotime($order['created_at'])); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <div class="text-center py-12">
                            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2-2z"></path>
                            </svg>
                            <h3 class="mt-2 text-sm font-medium text-gray-900">لا توجد معاملات مالية</h3>
                            <p class="mt-1 text-sm text-gray-500">لم يتم العثور على أي معاملات في النظام.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Modals -->
    <!-- Fawry Configuration Modal -->
    <div id="fawryModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white" dir="rtl">
            <div class="mt-3">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900">إعدادات فوري</h3>
                    <button onclick="closeFawryModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <form method="POST" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Merchant Code</label>
                        <input type="text" name="merchant_code" value="<?php echo htmlspecialchars($fawry_config['merchant_code'] ?? ''); ?>"
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-orange-500 focus:border-orange-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">API Key</label>
                        <input type="password" name="api_key" value="<?php echo htmlspecialchars($fawry_config['api_key'] ?? ''); ?>"
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-orange-500 focus:border-orange-500">
                    </div>
                    <div class="flex justify-end space-x-3 space-x-reverse">
                        <button type="button" onclick="closeFawryModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">إلغاء</button>
                        <button type="submit" name="update_fawry_config" class="px-4 py-2 bg-orange-600 text-white rounded-md hover:bg-orange-700">حفظ</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Paymob Configuration Modal -->
    <div id="paymobModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white" dir="rtl">
            <div class="mt-3">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900">إعدادات باي موب</h3>
                    <button onclick="closePaymobModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <form method="POST" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">API Key</label>
                        <input type="text" name="api_key" value="<?php echo htmlspecialchars($paymob_config['api_key'] ?? ''); ?>"
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-purple-500 focus:border-purple-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">HMAC Secret</label>
                        <input type="password" name="hmac_secret" value="<?php echo htmlspecialchars($paymob_config['hmac_secret'] ?? ''); ?>"
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-purple-500 focus:border-purple-500">
                    </div>
                    <div class="flex justify-end space-x-3 space-x-reverse">
                        <button type="button" onclick="closePaymobModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">إلغاء</button>
                        <button type="submit" name="update_paymob_config" class="px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700">حفظ</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Account Modal -->
    <div id="addAccountModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white" dir="rtl">
            <div class="mt-3">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900">إضافة حساب دفع</h3>
                    <button onclick="closeAddAccountModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <form method="POST" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">طريقة الدفع</label>
                        <select name="payment_method_id" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                            <?php foreach ($payment_methods as $method): ?>
                                <?php if (in_array($method['code'], ['vodafone_cash', 'instapay'])): ?>
                                    <option value="<?php echo $method['id']; ?>"><?php echo htmlspecialchars($method['name']); ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">اسم الحساب</label>
                        <input type="text" name="account_name" required
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">رقم الحساب</label>
                        <input type="text" name="account_number" required
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">اسم صاحب الحساب</label>
                        <input type="text" name="account_holder"
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">الحد اليومي (EGP)</label>
                        <input type="number" name="daily_limit" step="0.01" min="0"
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div class="flex justify-end space-x-3 space-x-reverse">
                        <button type="button" onclick="closeAddAccountModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">إلغاء</button>
                        <button type="submit" name="add_payment_account" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">إضافة</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Account Modal -->
    <div id="editAccountModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white" dir="rtl">
            <div class="mt-3">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900">تعديل حساب الدفع</h3>
                    <button onclick="closeEditAccountModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <form method="POST" id="editAccountForm" class="space-y-4">
                    <input type="hidden" name="account_id" id="edit_account_id">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">اسم الحساب</label>
                        <input type="text" name="account_name" id="edit_account_name" required
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">رقم الحساب</label>
                        <input type="text" name="account_number" id="edit_account_number" required
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">اسم صاحب الحساب</label>
                        <input type="text" name="account_holder" id="edit_account_holder"
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">الحد اليومي (EGP)</label>
                        <input type="number" name="daily_limit" id="edit_daily_limit" step="0.01" min="0"
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div class="flex items-center">
                        <input type="checkbox" name="is_active" id="edit_is_active"
                               class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                        <label class="mr-2 block text-sm text-gray-900">مفعل</label>
                    </div>
                    <div class="flex justify-end space-x-3 space-x-reverse">
                        <button type="button" onclick="closeEditAccountModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">إلغاء</button>
                        <button type="submit" name="edit_payment_account" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">حفظ</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function togglePaymentMethod(methodId, isActive) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="method_id" value="${methodId}">
                <input type="hidden" name="is_active" value="${isActive ? 1 : 0}">
                <input type="hidden" name="toggle_payment_method" value="1">
            `;
            document.body.appendChild(form);
            form.submit();
        }

        function showFawryConfig() {
            window.location.href = 'fawry_api.php';
        }

        function showPaymobModal() {
            document.getElementById('paymobModal').classList.remove('hidden');
        }

        function closePaymobModal() {
            document.getElementById('paymobModal').classList.add('hidden');
        }

        function showAddAccountModal() {
            document.getElementById('addAccountModal').classList.remove('hidden');
        }

        function closeAddAccountModal() {
            document.getElementById('addAccountModal').classList.add('hidden');
        }

        function editAccount(id, name, number, holder, limit, active) {
            document.getElementById('edit_account_id').value = id;
            document.getElementById('edit_account_name').value = name;
            document.getElementById('edit_account_number').value = number;
            document.getElementById('edit_account_holder').value = holder;
            document.getElementById('edit_daily_limit').value = limit;
            document.getElementById('edit_is_active').checked = active;
            document.getElementById('editAccountModal').classList.remove('hidden');
        }

        function closeEditAccountModal() {
            document.getElementById('editAccountModal').classList.add('hidden');
        }

        function deleteAccount(accountId) {
            Swal.fire({
                title: 'هل أنت متأكد؟',
                text: 'سيتم حذف هذا الحساب نهائياً!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'نعم، احذف',
                cancelButtonText: 'إلغاء'
            }).then((result) => {
                if (result.isConfirmed) {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.innerHTML = `
                        <input type="hidden" name="account_id" value="${accountId}">
                        <input type="hidden" name="delete_payment_account" value="1">
                    `;
                    document.body.appendChild(form);
                    form.submit();
                }
            });
        }

        // Success message with SweetAlert2
        <?php if ($message): ?>
        Swal.fire({
            icon: 'success',
            title: 'تم بنجاح!',
            text: '<?php echo $message; ?>',
            timer: 3000,
            showConfirmButton: false
        });
        <?php endif; ?>
    </script>
</body>
</html>