<?php
require_once 'includes/config.php';
redirectIfNotLoggedIn();

$userData = getMemberData($pdo, $_SESSION['user_id']);
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $duration = $_POST['duration'] ?? 12;
    
    // Get membership type details
    $stmt = $pdo->prepare("SELECT * FROM membership_types WHERE id = ?");
    $stmt->execute([$userData['membership_type_id']]);
    $membershipType = $stmt->fetch();
    
    $amount = $membershipType['amount'] * ($duration / 12);
    $newExpiryDate = $userData['expiry_date'] 
        ? date('Y-m-d', strtotime($userData['expiry_date'] . " + $duration months"))
        : date('Y-m-d', strtotime("+ $duration months"));
    
    try {
        // Update member expiry date
        $stmt = $pdo->prepare("UPDATE members SET expiry_date = ? WHERE id = ?");
        $stmt->execute([$newExpiryDate, $_SESSION['user_id']]);
        
        // Record renewal
        $stmt = $pdo->prepare("INSERT INTO renewals (member_id, amount, renewal_date, expiry_date, status) VALUES (?, ?, CURDATE(), ?, 'completed')");
        $stmt->execute([$_SESSION['user_id'], $amount, $newExpiryDate]);
        
        $success = "Membership renewed successfully for $duration months! New expiry date: " . formatDate($newExpiryDate);
        $userData = getMemberData($pdo, $_SESSION['user_id']);
        
    } catch (Exception $e) {
        $error = 'Renewal failed: ' . $e->getMessage();
    }
}

$status = getMembershipStatus($userData['expiry_date']);
?>

<?php include 'header.php'; ?>

<div class="row justify-content-center">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header bg-warning text-dark">
                <h4 class="mb-0"><i class="fas fa-sync-alt me-2"></i>Renew Membership</h4>
            </div>
            <div class="card-body">
                <?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; ?>
                
                <div class="alert alert-info">
                    <p><strong>Current Membership:</strong> <?php echo $userData['membership_type_name']; ?></p>
                    <p><strong>Current Expiry:</strong> <?php echo formatDate($userData['expiry_date']); ?></p>
                    <p><strong>Status:</strong> <span class="badge bg-<?php echo $status['class']; ?>"><?php echo $status['status']; ?></span></p>
                </div>
                
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Select Renewal Duration</label>
                        <select class="form-control" name="duration" required>
                            <option value="12">1 Year - <?php echo formatCurrency($userData['membership_amount']); ?></option>
                            <option value="24">2 Years - <?php echo formatCurrency($userData['membership_amount'] * 2); ?></option>
                            <option value="36">3 Years - <?php echo formatCurrency($userData['membership_amount'] * 3); ?></option>
                            <?php if ($userData['membership_type_name'] != 'Life Member'): ?>
                                <option value="0">Lifetime - <?php echo formatCurrency($userData['membership_amount'] * 5); ?></option>
                            <?php endif; ?>
                        </select>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle"></i> After renewal, your membership will be extended from the current expiry date.
                    </div>
                    
                    <button type="submit" class="btn btn-warning w-100">Proceed to Renewal</button>
                </form>
            </div>
        </div>
    </div>
</div>

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