<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: index.php');
    exit();
}

$page_title = "Payment Methods Configuration";

// Get payment method statistics
$stats_query = "SELECT 
                payment_method,
                COUNT(*) as transaction_count,
                SUM(amount) as total_amount
                FROM payments
                WHERE status = 'COMPLETED'
                AND DATE(payment_date) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                GROUP BY payment_method
                ORDER BY total_amount DESC";
$stats_result = mysqli_query($conn, $stats_query);

// Payment methods configuration
$payment_methods = [
    'CASH' => [
        'name' => 'Cash',
        'icon' => 'ri-money-dollar-circle-line',
        'color' => '#059669',
        'enabled' => true,
        'description' => 'Physical cash payments at the facility'
    ],
    'MPESA' => [
        'name' => 'M-Pesa',
        'icon' => 'ri-smartphone-line',
        'color' => '#0ea5e9',
        'enabled' => true,
        'description' => 'Mobile money payments via Safaricom M-Pesa'
    ],
    'CARD' => [
        'name' => 'Card Payment',
        'icon' => 'ri-bank-card-2-line',
        'color' => '#3b82f6',
        'enabled' => true,
        'description' => 'Debit and credit card payments'
    ],
    'BANK_TRANSFER' => [
        'name' => 'Bank Transfer',
        'icon' => 'ri-bank-line',
        'color' => '#8b5cf6',
        'enabled' => true,
        'description' => 'Direct bank to bank transfers'
    ],
    'CHEQUE' => [
        'name' => 'Cheque',
        'icon' => 'ri-file-list-line',
        'color' => '#f59e0b',
        'enabled' => true,
        'description' => 'Cheque payments'
    ],
    'INSURANCE_DIRECT' => [
        'name' => 'Insurance Direct',
        'icon' => 'ri-shield-check-line',
        'color' => '#6366f1',
        'enabled' => true,
        'description' => 'Direct payments from insurance companies'
    ],
    'CORPORATE' => [
        'name' => 'Corporate',
        'icon' => 'ri-building-line',
        'color' => '#64748b',
        'enabled' => true,
        'description' => 'Corporate/employer direct payments'
    ]
];

?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .chart-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .payment-method-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 2px solid #e2e8f0;
            margin-bottom: 1.5rem;
            transition: all 0.2s;
        }
        
        .payment-method-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.15);
        }
        
        .payment-method-card.enabled {
            border-color: #059669;
        }
        
        .payment-method-card.disabled {
            opacity: 0.6;
            border-color: #e2e8f0;
        }
        
        .method-icon {
            width: 60px;
            height: 60px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28px;
            color: white;
            margin-bottom: 1rem;
        }
        
        .stat-badge {
            background: #f8fafc;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            display: inline-block;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="financial_dashboard.php">Financial</a></li>
                                        <li class="breadcrumb-item active">Payment Methods</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-bank-card-line me-2"></i>Payment Methods Configuration</h4>
                                <p class="mb-0">Manage and configure available payment methods</p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-light" id="saveAllSettings">
                                    <i class="ri-save-line me-1"></i> Save All Changes
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Payment Method Statistics -->
                    <div class="chart-card">
                        <h5 class="mb-3"><i class="ri-bar-chart-line me-2"></i>Payment Method Usage (Last 30 Days)</h5>
                        <div class="row">
                            <?php 
                            mysqli_data_seek($stats_result, 0);
                            while ($stat = mysqli_fetch_assoc($stats_result)): 
                                $method_name = str_replace('_', ' ', $stat['payment_method']);
                            ?>
                            <div class="col-md-4 col-lg-3 mb-3">
                                <div class="stat-badge">
                                    <strong><?php echo $method_name; ?></strong><br>
                                    <span class="text-muted"><?php echo $stat['transaction_count']; ?> transactions</span><br>
                                    <strong class="text-success">KES <?php echo number_format($stat['total_amount'], 2); ?></strong>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        </div>
                    </div>

                    <!-- Payment Methods Configuration -->
                    <div class="row">
                        <?php foreach ($payment_methods as $code => $method): ?>
                        <div class="col-lg-6">
                            <div class="payment-method-card <?php echo $method['enabled'] ? 'enabled' : 'disabled'; ?>" 
                                 data-method="<?php echo $code; ?>">
                                <div class="row align-items-center">
                                    <div class="col-auto">
                                        <div class="method-icon" style="background: <?php echo $method['color']; ?>;">
                                            <i class="<?php echo $method['icon']; ?>"></i>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <h5 class="mb-1"><?php echo $method['name']; ?></h5>
                                        <p class="text-muted mb-2"><?php echo $method['description']; ?></p>
                                        
                                        <div class="form-check form-switch">
                                            <input class="form-check-input method-toggle" type="checkbox" 
                                                   id="toggle_<?php echo $code; ?>"
                                                   data-method="<?php echo $code; ?>"
                                                   <?php echo $method['enabled'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="toggle_<?php echo $code; ?>">
                                                <?php echo $method['enabled'] ? 'Enabled' : 'Disabled'; ?>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <?php if ($code == 'MPESA'): ?>
                                        <button type="button" class="btn btn-outline-primary btn-sm" 
                                                onclick="window.location.href='system_settings.php#mpesa'">
                                            <i class="ri-settings-line me-1"></i> Configure
                                        </button>
                                        <?php elseif ($code == 'CARD'): ?>
                                        <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#cardSettingsModal">
                                            <i class="ri-settings-line me-1"></i> Configure
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Payment Processing Rules -->
                    <div class="chart-card">
                        <h5 class="mb-3"><i class="ri-settings-3-line me-2"></i>Payment Processing Rules</h5>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Maximum Cash Payment Limit (KES)</label>
                                <input type="number" class="form-control" value="50000" min="0" step="1000">
                                <small class="text-muted">Payments above this amount require approval</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Auto-approve Payments Below (KES)</label>
                                <input type="number" class="form-control" value="5000" min="0" step="500">
                                <small class="text-muted">Payments below this amount are auto-approved</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Payment Receipt Prefix</label>
                                <input type="text" class="form-control" value="PAY" maxlength="5">
                                <small class="text-muted">Prefix for payment receipt numbers</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Default Currency</label>
                                <select class="form-select">
                                    <option value="KES" selected>KES - Kenyan Shilling</option>
                                    <option value="USD">USD - US Dollar</option>
                                    <option value="EUR">EUR - Euro</option>
                                </select>
                            </div>
                        </div>

                        <hr>

                        <div class="row">
                            <div class="col-12">
                                <h6 class="mb-3">Additional Options</h6>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="require_receipt_printing" checked>
                                    <label class="form-check-label" for="require_receipt_printing">
                                        Require Receipt Printing
                                    </label>
                                </div>
                                <small class="text-muted">Force receipt printing after payment</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="send_payment_sms" checked>
                                    <label class="form-check-label" for="send_payment_sms">
                                        Send Payment SMS Confirmation
                                    </label>
                                </div>
                                <small class="text-muted">Automatically send SMS on successful payment</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="allow_partial_payments" checked>
                                    <label class="form-check-label" for="allow_partial_payments">
                                        Allow Partial Payments
                                    </label>
                                </div>
                                <small class="text-muted">Enable payment of invoice balance in installments</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="require_payment_approval">
                                    <label class="form-check-label" for="require_payment_approval">
                                        Require Manager Approval for Large Payments
                                    </label>
                                </div>
                                <small class="text-muted">Large payments need supervisor approval</small>
                            </div>
                        </div>

                        <div class="mt-3">
                            <button type="button" class="btn btn-primary" id="savePaymentRules">
                                <i class="ri-save-line me-1"></i> Save Payment Rules
                            </button>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>

        <?php include 'layouts/footer.php'; ?>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Handle method toggle
        $('.method-toggle').on('change', function() {
            const method = $(this).data('method');
            const enabled = $(this).is(':checked');
            const card = $(this).closest('.payment-method-card');
            const label = $(this).next('label');
            
            if (enabled) {
                card.removeClass('disabled').addClass('enabled');
                label.text('Enabled');
            } else {
                card.removeClass('enabled').addClass('disabled');
                label.text('Disabled');
            }
            
            // Show confirmation
            Swal.fire({
                icon: 'info',
                title: method.replace('_', ' ') + ' ' + (enabled ? 'Enabled' : 'Disabled'),
                text: 'Payment method ' + (enabled ? 'activated' : 'deactivated'),
                timer: 1500,
                showConfirmButton: false
            });
        });

        // Save all settings
        $('#saveAllSettings, #savePaymentRules').on('click', function() {
            Swal.fire({
                icon: 'success',
                title: 'Settings Saved',
                text: 'Payment method configuration has been updated successfully',
                timer: 2000
            });
        });
    });
    </script>
</body>
</html>