<?php
require_once '../includes/config.php';
require_once 'header.php';

$error = '';
$success = '';

// Handle manual renewal
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_renewal'])) {
    $member_id = $_POST['member_id'] ?? 0;
    $amount = floatval($_POST['amount'] ?? 0);
    
    if ($member_id && $amount > 0) {
        // Get member details
        $stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
        $stmt->execute([$member_id]);
        $member = $stmt->fetch();
        
        if ($member) {
            // Get membership type
            $stmt = $pdo->prepare("SELECT * FROM membership_types WHERE id = ?");
            $stmt->execute([$member['membership_type_id']]);
            $membershipType = $stmt->fetch();
            
            // Calculate new expiry date
            $currentExpiry = $member['expiry_date'] ?: date('Y-m-d');
            $newExpiry = $membershipType['duration_months'] > 0 
                ? date('Y-m-d', strtotime("$currentExpiry + {$membershipType['duration_months']} months"))
                : null;
            
            try {
                // Update member expiry
                $stmt = $pdo->prepare("UPDATE members SET expiry_date = ? WHERE id = ?");
                $stmt->execute([$newExpiry, $member_id]);
                
                // Add renewal record
                $stmt = $pdo->prepare("INSERT INTO renewals (member_id, amount, renewal_date, expiry_date, status) VALUES (?, ?, CURDATE(), ?, 'completed')");
                $stmt->execute([$member_id, $amount, $newExpiry]);
                
                $success = "Renewal added successfully for {$member['fullname']}";
            } catch (Exception $e) {
                $error = "Failed to add renewal: " . $e->getMessage();
            }
        } else {
            $error = 'Member not found';
        }
    } else {
        $error = 'Please select a member and enter valid amount';
    }
}

// Get filters
$search = $_GET['search'] ?? '';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

$sql = "SELECT r.*, m.fullname, m.membership_number, m.email, mt.type as membership_type 
        FROM renewals r 
        JOIN members m ON r.member_id = m.id 
        LEFT JOIN membership_types mt ON m.membership_type_id = mt.id 
        WHERE 1=1";
$params = [];

if ($search) {
    $sql .= " AND (m.fullname LIKE ? OR m.membership_number LIKE ? OR m.email LIKE ?)";
    $params = array_fill(0, 3, "%$search%");
}

if ($start_date) {
    $sql .= " AND r.renewal_date >= ?";
    $params[] = $start_date;
}

if ($end_date) {
    $sql .= " AND r.renewal_date <= ?";
    $params[] = $end_date;
}

$sql .= " ORDER BY r.renewal_date DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$renewals = $stmt->fetchAll();

// Get members for dropdown
$stmt = $pdo->query("SELECT id, fullname, membership_number FROM members ORDER BY fullname");
$members = $stmt->fetchAll();

// Get statistics
$stmt = $pdo->query("SELECT 
                    COUNT(*) as total_renewals,
                    SUM(amount) as total_revenue,
                    AVG(amount) as avg_renewal,
                    SUM(amount) as monthly_revenue
                    FROM renewals WHERE MONTH(renewal_date) = MONTH(CURDATE())");
$stats = $stmt->fetch();

// Get monthly revenue chart data
$stmt = $pdo->query("SELECT 
                    DATE_FORMAT(renewal_date, '%b') as month,
                    SUM(amount) as revenue,
                    COUNT(*) as count
                    FROM renewals 
                    WHERE YEAR(renewal_date) = YEAR(CURDATE())
                    GROUP BY MONTH(renewal_date)
                    ORDER BY MONTH(renewal_date)");
$monthlyData = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="fas fa-sync-alt me-2"></i>Manage Renewals</h1>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRenewalModal">
        <i class="fas fa-plus me-2"></i>Add Manual Renewal
    </button>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card bg-primary text-white">
            <div class="card-body">
                <h5 class="card-title">Total Renewals</h5>
                <h2 class="mb-0"><?php echo number_format($stats['total_renewals'] ?? 0); ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-success text-white">
            <div class="card-body">
                <h5 class="card-title">Total Revenue</h5>
                <h2 class="mb-0"><?php echo formatCurrency($stats['total_revenue'] ?? 0); ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-info text-white">
            <div class="card-body">
                <h5 class="card-title">Average Renewal</h5>
                <h2 class="mb-0"><?php echo formatCurrency($stats['avg_renewal'] ?? 0); ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-warning text-white">
            <div class="card-body">
                <h5 class="card-title">This Month</h5>
                <h2 class="mb-0"><?php echo formatCurrency($stats['monthly_revenue'] ?? 0); ?></h2>
            </div>
        </div>
    </div>
</div>

<!-- Filter Form -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <input type="text" class="form-control" name="search" placeholder="Search by name, membership number..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="col-md-3">
                <input type="date" class="form-control" name="start_date" placeholder="Start Date" value="<?php echo $start_date; ?>">
            </div>
            <div class="col-md-3">
                <input type="date" class="form-control" name="end_date" placeholder="End Date" value="<?php echo $end_date; ?>">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">Filter</button>
            </div>
        </form>
    </div>
</div>

<!-- Renewals Table -->
<div class="card">
    <div class="card-header">
        <h5 class="mb-0"><i class="fas fa-list me-2"></i>Renewal History</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover" id="renewalsTable">
                <thead class="table-dark">
                    <tr>
                        <th>Date</th>
                        <th>Member Name</th>
                        <th>Membership No</th>
                        <th>Type</th>
                        <th>Amount</th>
                        <th>Expiry Date</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($renewals as $renewal): ?>
                    <tr>
                        <td><?php echo formatDate($renewal['renewal_date']); ?></td>
                        <td><?php echo htmlspecialchars($renewal['fullname']); ?></td>
                        <td><?php echo $renewal['membership_number']; ?></td>
                        <td><?php echo $renewal['membership_type']; ?></td>
                        <td><?php echo formatCurrency($renewal['amount']); ?></td>
                        <td><?php echo formatDate($renewal['expiry_date']); ?></td>
                        <td><span class="badge bg-success">Completed</span></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Monthly Revenue Chart -->
<?php if (count($monthlyData) > 0): ?>
<div class="card mt-4">
    <div class="card-header">
        <h5 class="mb-0"><i class="fas fa-chart-line me-2"></i>Monthly Revenue <?php echo date('Y'); ?></h5>
    </div>
    <div class="card-body">
        <canvas id="revenueChart" height="100"></canvas>
    </div>
</div>
<?php endif; ?>

<!-- Add Renewal Modal -->
<div class="modal fade" id="addRenewalModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-plus me-2"></i>Add Manual Renewal</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Select Member *</label>
                        <select class="form-control" name="member_id" required>
                            <option value="">-- Select Member --</option>
                            <?php foreach ($members as $member): ?>
                                <option value="<?php echo $member['id']; ?>">
                                    <?php echo htmlspecialchars($member['fullname']); ?> (<?php echo $member['membership_number']; ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount (₹) *</label>
                        <input type="number" class="form-control" name="amount" step="0.01" required>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        This will extend the member's expiry date based on their membership type duration.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_renewal" class="btn btn-primary">Add Renewal</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function() {
    $('#renewalsTable').DataTable({
        pageLength: 25,
        order: [[0, 'desc']]
    });
});

<?php if (count($monthlyData) > 0): ?>
const ctx = document.getElementById('revenueChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?php echo json_encode(array_column($monthlyData, 'month')); ?>,
        datasets: [{
            label: 'Revenue (₹)',
            data: <?php echo json_encode(array_column($monthlyData, 'revenue')); ?>,
            borderColor: '#3498db',
            backgroundColor: 'rgba(52, 152, 219, 0.1)',
            fill: true,
            tension: 0.3
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { position: 'top' }
        }
    }
});
<?php endif; ?>
</script>

<?php require_once 'footer.php'; ?>