<?php
require_once(__DIR__ . '/../../config/config.php');
require_once(__DIR__ . '/../../classes/Database.php');
require_once(__DIR__ . '/../../classes/Payment.php');

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

$db = Database::getInstance();
$payment = new Payment();
$paymentDetails = $payment->getPaymentDetails();

$uploadDir = __DIR__ . '/../../uploads/qrcodes/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$message = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_details') {
        $upiId = trim($_POST['upi_id'] ?? '');
        $telegramToken = trim($_POST['telegram_token'] ?? '');
        $telegramChatId = trim($_POST['telegram_chat_id'] ?? '');
        
        $qrCodePath = $paymentDetails['qr_code_path'] ?? '';
        
        // Handle QR code upload
        if (!empty($_FILES['qr_code']['name'])) {
            $file = $_FILES['qr_code'];
            $allowed = ['image/jpeg', 'image/png', 'image/gif'];
            
            if (in_array($file['type'], $allowed)) {
                $filename = 'qr_' . time() . '.png';
                $filepath = $uploadDir . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $filepath)) {
                    $qrCodePath = 'uploads/qrcodes/' . $filename;
                } else {
                    $error = 'Failed to upload QR code';
                }
            } else {
                $error = 'Invalid file type. Only JPG, PNG, GIF allowed.';
            }
        }
        
        if (empty($error)) {
            if ($payment->updatePaymentDetails($qrCodePath, $upiId, $telegramToken, $telegramChatId)) {
                $message = 'Payment settings updated successfully!';
                $paymentDetails = $payment->getPaymentDetails();
            } else {
                $error = 'Failed to update settings';
            }
        }
    }
}

$pendingApprovals = $payment->getPendingApprovals();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Settings - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background: #f8f9fa;
            padding: 20px;
        }

        .header {
            margin-bottom: 30px;
        }

        .card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            margin-bottom: 25px;
        }

        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
            padding: 20px;
            border: none;
        }

        .card-body {
            padding: 25px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            display: block;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            border-color: #667eea;
            outline: none;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .btn-submit {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
        }

        .btn-submit:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }

        .alert {
            border-radius: 8px;
            border: none;
            margin-bottom: 20px;
        }

        .qr-preview {
            max-width: 300px;
            margin-top: 15px;
            border-radius: 8px;
            border: 2px solid #e0e0e0;
            padding: 10px;
        }

        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
            width: 100%;
        }

        .file-input-wrapper input[type=file] {
            position: absolute;
            left: -9999px;
        }

        .file-input-label {
            display: block;
            padding: 12px;
            background: #f8f9fa;
            border: 2px dashed #667eea;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            color: #667eea;
            font-weight: 600;
        }

        .file-input-label:hover {
            background: #f0f1ff;
            border-color: #764ba2;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 25px;
        }

        .stat-box {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .stat-box h6 {
            color: #666;
            margin: 0 0 8px 0;
            font-weight: 600;
        }

        .stat-box .value {
            font-size: 24px;
            font-weight: 700;
            color: #333;
        }

        .pending-list {
            max-height: 300px;
            overflow-y: auto;
        }

        .pending-item {
            padding: 12px;
            border-bottom: 1px solid #e0e0e0;
            background: #fff;
            border-radius: 6px;
            margin-bottom: 8px;
        }

        .pending-item:hover {
            background: #f8f9fa;
        }

        .pending-amount {
            color: #10b981;
            font-weight: 700;
            font-size: 16px;
        }

        .pending-user {
            color: #666;
            font-size: 12px;
        }

        /* MOBILE RESPONSIVE */
        @media (max-width: 768px) {
            body {
                padding: 12px;
            }

            .container-fluid {
                padding: 0;
            }

            .header {
                margin-bottom: 20px;
            }

            .header h1 {
                font-size: 24px;
                margin-bottom: 8px;
            }

            .header p {
                font-size: 12px;
            }

            .card {
                margin-bottom: 15px;
            }

            .card-header {
                padding: 15px;
            }

            .card-header h5 {
                font-size: 18px;
                margin: 0;
            }

            .card-body {
                padding: 15px;
            }

            .form-group {
                margin-bottom: 15px;
            }

            .form-group label {
                font-size: 13px;
            }

            .form-group input,
            .form-group textarea {
                padding: 10px;
                font-size: 16px;
            }

            .btn-submit {
                padding: 12px;
                font-size: 14px;
            }

            .stats-grid {
                grid-template-columns: 1fr;
                gap: 12px;
            }

            .stat-box {
                padding: 12px;
            }

            .stat-box h6 {
                font-size: 12px;
            }

            .stat-box .value {
                font-size: 18px;
            }

            .qr-preview {
                max-width: 100%;
                max-height: 250px;
            }

            .pending-item {
                padding: 10px;
            }

            .d-flex {
                flex-direction: column;
            }

            .pending-amount {
                font-size: 14px;
            }
        }

        @media (max-width: 480px) {
            body {
                padding: 8px;
            }

            .header h1 {
                font-size: 20px;
            }

            .card-header h5 {
                font-size: 16px;
            }

            .form-group label {
                font-size: 12px;
            }

            .form-group input {
                font-size: 14px;
                padding: 8px;
            }

            .btn-submit {
                padding: 10px;
                font-size: 13px;
            }

            .stat-box .value {
                font-size: 16px;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="header">
            <h1><i class="fas fa-cog"></i> Payment Settings</h1>
            <p class="text-muted">Manage payment methods, QR codes, and notifications</p>
        </div>

        <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-times-circle"></i> <?php echo htmlspecialchars($error); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-box">
                <h6>Pending Approvals</h6>
                <div class="value"><?php echo count($pendingApprovals); ?></div>
            </div>
            <div class="stat-box">
                <h6>Current UPI ID</h6>
                <div class="value" style="font-size: 14px;"><?php echo htmlspecialchars($paymentDetails['upi_id'] ?? 'Not Set'); ?></div>
            </div>
        </div>

        <!-- Payment Settings Form -->
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-credit-card"></i> Update Payment Details</h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="update_details">

                    <!-- UPI ID -->
                    <div class="form-group">
                        <label for="upi_id"><i class="fas fa-mobile-alt"></i> UPI ID</label>
                        <input 
                            type="text" 
                            id="upi_id" 
                            name="upi_id" 
                            placeholder="example@bank"
                            value="<?php echo htmlspecialchars($paymentDetails['upi_id'] ?? ''); ?>"
                            required
                        >
                        <small class="text-muted d-block mt-2">Users will send payments to this UPI ID</small>
                    </div>

                    <!-- QR Code Upload -->
                    <div class="form-group">
                        <label for="qr_code"><i class="fas fa-qrcode"></i> Payment QR Code</label>
                        <div class="file-input-wrapper">
                            <input type="file" id="qr_code" name="qr_code" accept="image/*">
                            <label for="qr_code" class="file-input-label">
                                <i class="fas fa-cloud-upload-alt"></i> Click to upload QR code (JPG, PNG, GIF)
                            </label>
                        </div>
                        
                        <?php if (!empty($paymentDetails['qr_code_path'])): ?>
                        <div style="margin-top: 15px;">
                            <p class="text-muted small">Current QR Code:</p>
                            <img src="/extract/<?php echo htmlspecialchars($paymentDetails['qr_code_path']); ?>" alt="QR Code" class="qr-preview" onerror="this.style.border='3px solid red'; this.title='Image failed to load';">
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Telegram Settings -->
                    <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 20px 0;">
                        <h6><i class="fab fa-telegram"></i> Telegram Bot Settings (Optional)</h6>
                        <p class="text-muted small">Admin will get notifications and can approve payments via Telegram</p>
                    </div>

                    <div class="form-group">
                        <label for="telegram_token"><i class="fab fa-telegram"></i> Telegram Bot Token</label>
                        <input 
                            type="text" 
                            id="telegram_token" 
                            name="telegram_token" 
                            placeholder="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
                            value="<?php echo htmlspecialchars($paymentDetails['telegram_bot_token'] ?? ''); ?>"
                        >
                        <small class="text-muted d-block mt-2">Get from <strong>@BotFather</strong> on Telegram</small>
                    </div>

                    <div class="form-group">
                        <label for="telegram_chat_id">Admin Telegram Chat ID</label>
                        <input 
                            type="text" 
                            id="telegram_chat_id" 
                            name="telegram_chat_id" 
                            placeholder="123456789"
                            value="<?php echo htmlspecialchars($paymentDetails['telegram_admin_chat_id'] ?? ''); ?>"
                        >
                        <small class="text-muted d-block mt-2">Get by sending /start to <strong>@userinfobot</strong> on Telegram</small>
                    </div>

                    <button type="submit" class="btn-submit">
                        <i class="fas fa-save"></i> Save Payment Settings
                    </button>
                </form>
            </div>
        </div>

        <!-- Pending Approvals -->
        <?php if (count($pendingApprovals) > 0): ?>
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-hourglass-half"></i> Pending Approvals (<?php echo count($pendingApprovals); ?>)</h5>
            </div>
            <div class="card-body">
                <div class="pending-list">
                    <?php foreach ($pendingApprovals as $approval): ?>
                    <div class="pending-item">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong><?php echo htmlspecialchars($approval['name']); ?></strong>
                                <div class="pending-user">
                                    <?php echo htmlspecialchars($approval['email']); ?> • 
                                    <?php echo htmlspecialchars($approval['package_name']); ?>
                                </div>
                            </div>
                            <div class="pending-amount">
                                ₹<?php echo number_format($approval['amount'], 2); ?>
                            </div>
                        </div>
                        <div class="text-muted small" style="margin-top: 8px;">
                            Txn ID: <?php echo htmlspecialchars($approval['transaction_id'] ?? 'N/A'); ?>
                            <br>
                            Submitted: <?php echo date('d M Y H:i', strtotime($approval['created_at'])); ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div style="text-align: center; margin-top: 15px;">
                    <a href="payments.php" class="btn btn-primary btn-sm">
                        <i class="fas fa-arrow-right"></i> Go to Payment Dashboard
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Show file name when selected
        document.getElementById('qr_code').addEventListener('change', function(e) {
            const label = document.querySelector('.file-input-label');
            if (this.files.length > 0) {
                label.innerHTML = '<i class="fas fa-check-circle"></i> ' + this.files[0].name;
            }
        });
    </script>
</body>
</html>
