<?php
session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

require_once '../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // 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 (for Vodafone Cash and InstaPay)
    $query = "SELECT pa.*, pm.name as method_name, pm.code as method_code
              FROM payment_accounts pa
              JOIN payment_methods pm ON pa.payment_method_id = pm.id
              ORDER BY pa.id";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $payment_accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = $e->getMessage();
    $payment_methods = [];
    $payment_accounts = [];
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['toggle_method'])) {
            $method_id = $_POST['method_id'];
            $query = "UPDATE payment_methods SET is_active = NOT is_active WHERE id = ?";
            $stmt = $db->prepare($query);
            $stmt->execute([$method_id]);
            header("Location: index.php?updated=1");
            exit;
        } elseif (isset($_POST['update_config'])) {
            $method_id = $_POST['method_id'];
            $config = json_encode([
                'api_key' => $_POST['api_key'] ?? '',
                'merchant_code' => $_POST['merchant_code'] ?? '',
                'hmac_secret' => $_POST['hmac_secret'] ?? '',
                'integration_id' => $_POST['integration_id'] ?? ''
            ]);
            $query = "UPDATE payment_methods SET integration_config = ? WHERE id = ?";
            $stmt = $db->prepare($query);
            $stmt->execute([$config, $method_id]);
            header("Location: index.php?updated=1");
            exit;
        } elseif (isset($_POST['add_account'])) {
            $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->execute([$method_id, $account_name, $account_number, $account_holder, $daily_limit]);
            header("Location: index.php?added=1");
            exit;
        } elseif (isset($_POST['delete_account'])) {
            $account_id = $_POST['account_id'];
            $query = "DELETE FROM payment_accounts WHERE id = ?";
            $stmt = $db->prepare($query);
            $stmt->execute([$account_id]);
            header("Location: index.php?deleted=1");
            exit;
        }
    } catch (Exception $e) {
        $message = "خطأ: " . $e->getMessage();
    }
}

if (isset($_GET['updated'])) {
    $message = 'تم التحديث بنجاح!';
} elseif (isset($_GET['added'])) {
    $message = 'تم إضافة الحساب بنجاح!';
} elseif (isset($_GET['deleted'])) {
    $message = 'تم حذف الحساب بنجاح!';
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة طرق الدفع - Roz Skin</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">
    <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; }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <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-4">
                <div class="flex items-center space-x-4 space-x-reverse">
                    <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-right text-xl"></i>
                    </a>
                    <h1 class="text-2xl font-bold text-gray-900">إدارة طرق الدفع</h1>
                </div>
            </div>
        </header>

        <div class="p-6">
            <?php if(isset($error)): ?>
                <div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6">
                    <p class="text-sm text-red-700">خطأ: <?php echo $error; ?></p>
                </div>
            <?php endif; ?>

            <?php if($message): ?>
                <div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6">
                    <p class="text-sm text-green-700"><?php echo $message; ?></p>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <?php
                $active_methods = count(array_filter($payment_methods, fn($m) => $m['is_active']));
                $total_accounts = count($payment_accounts);
            ?>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">طرق الدفع المتاحة</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo count($payment_methods); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-credit-card text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">الطرق النشطة</p>
                            <p class="text-2xl font-bold text-green-600"><?php echo $active_methods; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">الحسابات المضافة</p>
                            <p class="text-2xl font-bold text-purple-600"><?php echo $total_accounts; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-wallet text-purple-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Payment Methods -->
            <div class="space-y-6">
                <?php foreach ($payment_methods as $method): ?>
                    <?php 
                        $config = !empty($method['integration_config']) ? json_decode($method['integration_config'], true) : [];
                        $needs_config = in_array($method['code'], ['fawry', 'paymob']);
                        $needs_accounts = in_array($method['code'], ['vodafone_cash', 'instapay']);
                    ?>
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                        <div class="p-6">
                            <div class="flex items-center justify-between mb-4">
                                <div class="flex items-center gap-4">
                                    <div class="w-16 h-16 bg-gradient-to-br <?php 
                                        echo $method['code'] === 'cash_on_delivery' ? 'from-blue-400 to-blue-600' : 
                                            ($method['code'] === 'fawry' ? 'from-orange-400 to-orange-600' : 
                                            ($method['code'] === 'vodafone_cash' ? 'from-red-400 to-red-600' : 
                                            ($method['code'] === 'instapay' ? 'from-purple-400 to-purple-600' : 
                                            'from-indigo-400 to-indigo-600')));
                                    ?> rounded-lg flex items-center justify-center">
                                        <i class="<?php echo $method['icon_class']; ?> text-white text-2xl"></i>
                                    </div>
                                    <div>
                                        <h3 class="text-xl font-bold text-gray-900"><?php echo htmlspecialchars($method['name']); ?></h3>
                                        <p class="text-sm text-gray-600"><?php echo htmlspecialchars($method['description']); ?></p>
                                    </div>
                                </div>
                                <form method="POST">
                                    <input type="hidden" name="method_id" value="<?php echo $method['id']; ?>">
                                    <button type="submit" name="toggle_method" 
                                            class="px-4 py-2 rounded-lg font-semibold <?php echo $method['is_active'] ? 'bg-green-100 text-green-700 hover:bg-green-200' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'; ?>">
                                        <?php echo $method['is_active'] ? '✓ مفعل' : '✗ معطل'; ?>
                                    </button>
                                </form>
                            </div>

                            <?php if ($needs_config && $method['is_active']): ?>
                                <div class="mt-4 p-4 bg-gray-50 rounded-lg">
                                    <h4 class="font-semibold text-gray-900 mb-3">إعدادات API</h4>
                                    <form method="POST" class="space-y-3">
                                        <input type="hidden" name="method_id" value="<?php echo $method['id']; ?>">
                                        <?php if ($method['code'] === 'fawry'): ?>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700 mb-1">Merchant Code</label>
                                                <input type="text" name="merchant_code" value="<?php echo htmlspecialchars($config['merchant_code'] ?? ''); ?>" 
                                                       class="w-full border border-gray-300 rounded-lg px-3 py-2" placeholder="123456789">
                                            </div>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700 mb-1">API Key</label>
                                                <input type="text" name="api_key" value="<?php echo htmlspecialchars($config['api_key'] ?? ''); ?>" 
                                                       class="w-full border border-gray-300 rounded-lg px-3 py-2" placeholder="fawry_api_key_here">
                                            </div>
                                        <?php elseif ($method['code'] === 'paymob'): ?>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700 mb-1">API Key</label>
                                                <input type="text" name="api_key" value="<?php echo htmlspecialchars($config['api_key'] ?? ''); ?>" 
                                                       class="w-full border border-gray-300 rounded-lg px-3 py-2" placeholder="paymob_api_key">
                                            </div>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700 mb-1">HMAC Secret</label>
                                                <input type="text" name="hmac_secret" value="<?php echo htmlspecialchars($config['hmac_secret'] ?? ''); ?>" 
                                                       class="w-full border border-gray-300 rounded-lg px-3 py-2" placeholder="hmac_secret">
                                            </div>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700 mb-1">Integration ID</label>
                                                <input type="text" name="integration_id" value="<?php echo htmlspecialchars($config['integration_id'] ?? ''); ?>" 
                                                       class="w-full border border-gray-300 rounded-lg px-3 py-2" placeholder="integration_id">
                                            </div>
                                        <?php endif; ?>
                                        <button type="submit" name="update_config" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                                            <i class="fas fa-save ml-1"></i>حفظ الإعدادات
                                        </button>
                                    </form>
                                </div>
                            <?php endif; ?>

                            <?php if ($needs_accounts && $method['is_active']): ?>
                                <div class="mt-4 p-4 bg-gray-50 rounded-lg">
                                    <div class="flex items-center justify-between mb-3">
                                        <h4 class="font-semibold text-gray-900">الحسابات المضافة</h4>
                                        <button onclick="showAddAccountModal(<?php echo $method['id']; ?>, '<?php echo htmlspecialchars($method['name']); ?>')" 
                                                class="bg-green-600 text-white px-3 py-1 rounded-lg text-sm hover:bg-green-700">
                                            <i class="fas fa-plus ml-1"></i>إضافة حساب
                                        </button>
                                    </div>
                                    <?php 
                                        $method_accounts = array_filter($payment_accounts, fn($a) => $a['payment_method_id'] == $method['id']);
                                    ?>
                                    <?php if (!empty($method_accounts)): ?>
                                        <div class="space-y-2">
                                            <?php foreach ($method_accounts as $account): ?>
                                                <div class="flex items-center justify-between p-3 bg-white rounded-lg border border-gray-200">
                                                    <div>
                                                        <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($account['account_name']); ?></p>
                                                        <p class="text-sm text-gray-600"><?php echo htmlspecialchars($account['account_number']); ?></p>
                                                        <p class="text-xs text-gray-500">حد يومي: EGP <?php echo number_format($account['daily_limit'], 0); ?></p>
                                                    </div>
                                                    <form method="POST" onsubmit="return confirm('هل أنت متأكد من حذف هذا الحساب؟');">
                                                        <input type="hidden" name="account_id" value="<?php echo $account['id']; ?>">
                                                        <button type="submit" name="delete_account" class="text-red-600 hover:text-red-700">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </form>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <p class="text-sm text-gray-500 text-center py-4">لم يتم إضافة حسابات بعد</p>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Add Account Modal -->
    <div id="addAccountModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
            <div class="flex items-center justify-between p-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold 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="p-4 space-y-4">
                <input type="hidden" name="payment_method_id" id="modal_method_id">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">اسم الحساب</label>
                    <input type="text" name="account_name" required class="w-full border border-gray-300 rounded-lg px-3 py-2" 
                           placeholder="مثال: رقم فودافون كاش الأساسي">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">رقم الحساب</label>
                    <input type="text" name="account_number" required class="w-full border border-gray-300 rounded-lg px-3 py-2" 
                           placeholder="مثال: 01012345678">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">اسم صاحب الحساب</label>
                    <input type="text" name="account_holder" required class="w-full border border-gray-300 rounded-lg px-3 py-2" 
                           placeholder="مثال: متجر روز سكين">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">الحد اليومي (EGP)</label>
                    <input type="number" name="daily_limit" value="10000" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                </div>
                <div class="flex gap-2">
                    <button type="submit" name="add_account" class="flex-1 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
                        <i class="fas fa-plus ml-1"></i>إضافة
                    </button>
                    <button type="button" onclick="closeAddAccountModal()" class="flex-1 bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function showAddAccountModal(methodId, methodName) {
            document.getElementById('modal_method_id').value = methodId;
            document.getElementById('addAccountModal').classList.remove('hidden');
        }

        function closeAddAccountModal() {
            document.getElementById('addAccountModal').classList.add('hidden');
        }
    </script>
</body>
</html>
