<?php
session_start();
require_once 'config/config.php';
require_once 'auth/check_auth.php';

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

$pageTitle = 'Membership Renewal Management';
$currentPage = 'membership-renewal';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $pageTitle; ?> | KSO Chandigarh</title>
    
    <!-- AdminLTE CSS -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <style>
        .renewal-stats {
            background: linear-gradient(135deg, #00b894 0%, #00cec9 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .renewal-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border-left: 4px solid #007bff;
        }
        
        .renewal-card.warning {
            border-left-color: #ffc107;
        }
        
        .renewal-card.danger {
            border-left-color: #dc3545;
        }
        
        .renewal-timeline {
            position: relative;
            padding-left: 30px;
        }
        
        .timeline-item {
            position: relative;
            padding-bottom: 20px;
        }
        
        .timeline-item:before {
            content: '';
            position: absolute;
            left: -35px;
            top: 5px;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #007bff;
        }
        
        .timeline-item:after {
            content: '';
            position: absolute;
            left: -31px;
            top: 15px;
            width: 2px;
            height: 100%;
            background: #dee2e6;
        }
        
        .timeline-item:last-child:after {
            display: none;
        }
        
        .automated-renewal {
            background: #e8f5e8;
            border: 1px solid #c3e6cb;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .reminder-settings {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .payment-integration {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 8px;
            padding: 20px;
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Include header -->
    <?php include 'templates/header.php'; ?>
    
    <!-- Include sidebar -->
    <?php include 'templates/sidebar.php'; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-redo-alt text-primary"></i> Membership Renewal Management
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item active">Membership Renewal</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                
                <!-- Renewal Statistics -->
                <div class="renewal-stats">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-primary">
                                    <i class="fas fa-users"></i>
                                </div>
                                <h3 class="mb-1" id="totalMembers">0</h3>
                                <p class="mb-0">Total Members</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-warning">
                                    <i class="fas fa-exclamation-triangle"></i>
                                </div>
                                <h3 class="mb-1" id="expiringMembers">0</h3>
                                <p class="mb-0">Expiring Soon</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-danger">
                                    <i class="fas fa-times-circle"></i>
                                </div>
                                <h3 class="mb-1" id="expiredMembers">0</h3>
                                <p class="mb-0">Expired</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-success">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <h3 class="mb-1" id="renewedMembers">0</h3>
                                <p class="mb-0">Renewed This Month</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Automated Renewal Settings -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-robot"></i> Automated Renewal System
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="automated-renewal">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="enableAutoRenewal">
                                            <label class="custom-control-label" for="enableAutoRenewal">Enable Automatic Renewal</label>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label>Grace Period (Days)</label>
                                        <input type="number" class="form-control" id="gracePeriod" value="30">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Renewal Fee (₹)</label>
                                        <input type="number" class="form-control" id="renewalFee" value="1000">
                                    </div>
                                    <div class="form-group">
                                        <label>Late Fee (₹)</label>
                                        <input type="number" class="form-control" id="lateFee" value="200">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Reminder Settings -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-bell"></i> Reminder Settings
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="reminder-settings">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>First Reminder (Days Before)</label>
                                        <input type="number" class="form-control" id="firstReminder" value="60">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Second Reminder (Days Before)</label>
                                        <input type="number" class="form-control" id="secondReminder" value="30">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Final Reminder (Days Before)</label>
                                        <input type="number" class="form-control" id="finalReminder" value="7">
                                    </div>
                                </div>
                            </div>
                            <button class="btn btn-primary" onclick="saveReminderSettings()">
                                <i class="fas fa-save"></i> Save Settings
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Renewal Dashboard -->
                <div class="row">
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-list"></i> Renewal Queue
                                </h3>
                            </div>
                            <div class="card-body">
                                <div id="renewalQueue">
                                    <!-- Renewal items will be loaded here -->
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-chart-line"></i> Renewal Analytics
                                </h3>
                            </div>
                            <div class="card-body">
                                <canvas id="renewalChart" width="400" height="200"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Payment Integration -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-credit-card"></i> Payment Integration
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="payment-integration">
                            <h6>Payment Gateway Settings</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Payment Gateway</label>
                                        <select class="form-control" id="paymentGateway">
                                            <option value="razorpay">Razorpay</option>
                                            <option value="paytm">Paytm</option>
                                            <option value="paypal">PayPal</option>
                                            <option value="stripe">Stripe</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Merchant ID</label>
                                        <input type="text" class="form-control" id="merchantId" placeholder="Enter Merchant ID">
                                    </div>
                                </div>
                            </div>
                            <button class="btn btn-success" onclick="testPaymentGateway()">
                                <i class="fas fa-check"></i> Test Connection
                            </button>
                        </div>
                    </div>
                </div>

            </div>
        </section>
    </div>
</div>

<!-- Include footer -->
<?php include 'templates/footer.php'; ?>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
// Membership Renewal Management System
$(document).ready(function() {
    loadRenewalStatistics();
    loadRenewalQueue();
    loadRenewalChart();
    loadSettings();
});

function loadRenewalStatistics() {
    $.ajax({
        url: 'api/renewal/stats.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalMembers').text(response.stats.total);
                $('#expiringMembers').text(response.stats.expiring);
                $('#expiredMembers').text(response.stats.expired);
                $('#renewedMembers').text(response.stats.renewed);
            }
        }
    });
}

function loadRenewalQueue() {
    $.ajax({
        url: 'api/renewal/queue.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const queue = $('#renewalQueue');
                queue.empty();
                
                response.members.forEach(function(member) {
                    queue.append(createRenewalCard(member));
                });
            }
        }
    });
}

function createRenewalCard(member) {
    const daysUntilExpiry = Math.ceil((new Date(member.expiry_date) - new Date()) / (1000 * 60 * 60 * 24));
    let cardClass = '';
    let statusText = '';
    
    if (daysUntilExpiry < 0) {
        cardClass = 'danger';
        statusText = `Expired ${Math.abs(daysUntilExpiry)} days ago`;
    } else if (daysUntilExpiry <= 30) {
        cardClass = 'warning';
        statusText = `Expires in ${daysUntilExpiry} days`;
    } else {
        statusText = `Expires in ${daysUntilExpiry} days`;
    }
    
    return `
        <div class="renewal-card ${cardClass}">
            <div class="row">
                <div class="col-md-6">
                    <h6>${member.name}</h6>
                    <p class="text-muted mb-1">ID: ${member.kso_id}</p>
                    <p class="text-muted mb-0">Type: ${member.membership_type}</p>
                </div>
                <div class="col-md-4">
                    <p class="mb-1"><strong>${statusText}</strong></p>
                    <p class="text-muted mb-0">Expiry: ${formatDate(member.expiry_date)}</p>
                </div>
                <div class="col-md-2">
                    <button class="btn btn-primary btn-sm btn-block" onclick="processRenewal(${member.id})">
                        <i class="fas fa-redo"></i> Renew
                    </button>
                    <button class="btn btn-secondary btn-sm btn-block mt-1" onclick="sendReminder(${member.id})">
                        <i class="fas fa-envelope"></i> Remind
                    </button>
                </div>
            </div>
        </div>
    `;
}

function processRenewal(memberId) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Process Renewal',
            text: 'This will renew the membership for 1 year.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, renew!'
        }).then((result) => {
            if (result.isConfirmed) {
                performRenewal(memberId);
            }
        });
    } else {
        if (confirm('Are you sure you want to renew this membership?')) {
            performRenewal(memberId);
        }
    }
}

function performRenewal(memberId) {
    $.ajax({
        url: 'api/renewal/process.php',
        method: 'POST',
        data: { member_id: memberId },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Membership renewed successfully!');
                }
                loadRenewalStatistics();
                loadRenewalQueue();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Renewal failed: ' + response.message);
                }
            }
        }
    });
}

function sendReminder(memberId) {
    $.ajax({
        url: 'api/renewal/send-reminder.php',
        method: 'POST',
        data: { member_id: memberId },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Reminder sent successfully!');
                }
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Failed to send reminder: ' + response.message);
                }
            }
        }
    });
}

function saveReminderSettings() {
    const settings = {
        first_reminder: $('#firstReminder').val(),
        second_reminder: $('#secondReminder').val(),
        final_reminder: $('#finalReminder').val(),
        grace_period: $('#gracePeriod').val(),
        renewal_fee: $('#renewalFee').val(),
        late_fee: $('#lateFee').val(),
        auto_renewal: $('#enableAutoRenewal').is(':checked')
    };
    
    $.ajax({
        url: 'api/renewal/save-settings.php',
        method: 'POST',
        data: settings,
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Settings saved successfully!');
                }
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Failed to save settings: ' + response.message);
                }
            }
        }
    });
}

function loadSettings() {
    $.ajax({
        url: 'api/renewal/get-settings.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const settings = response.settings;
                $('#firstReminder').val(settings.first_reminder || 60);
                $('#secondReminder').val(settings.second_reminder || 30);
                $('#finalReminder').val(settings.final_reminder || 7);
                $('#gracePeriod').val(settings.grace_period || 30);
                $('#renewalFee').val(settings.renewal_fee || 1000);
                $('#lateFee').val(settings.late_fee || 200);
                $('#enableAutoRenewal').prop('checked', settings.auto_renewal || false);
            }
        }
    });
}

function testPaymentGateway() {
    const gateway = $('#paymentGateway').val();
    const merchantId = $('#merchantId').val();
    
    if (!merchantId) {
        if (window.ksoToast) {
            window.ksoToast.error('Please enter Merchant ID');
        }
        return;
    }
    
    $.ajax({
        url: 'api/renewal/test-payment.php',
        method: 'POST',
        data: { gateway: gateway, merchant_id: merchantId },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Payment gateway connection successful!');
                }
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Connection failed: ' + response.message);
                }
            }
        }
    });
}

function loadRenewalChart() {
    $.ajax({
        url: 'api/renewal/chart-data.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const ctx = document.getElementById('renewalChart').getContext('2d');
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: response.labels,
                        datasets: [{
                            label: 'Renewals',
                            data: response.data,
                            borderColor: 'rgb(75, 192, 192)',
                            backgroundColor: 'rgba(75, 192, 192, 0.2)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            }
        }
    });
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}
</script>

</body>
</html>
