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

$memberId = $_GET['id'] ?? 0;

if (!$memberId) {
    header('Location: members.php');
    exit;
}

// Get member data
$stmt = $pdo->prepare("SELECT m.*, mt.type as membership_type, mt.amount as membership_amount 
                      FROM members m 
                      LEFT JOIN membership_types mt ON m.membership_type_id = mt.id 
                      WHERE m.id = ?");
$stmt->execute([$memberId]);
$member = $stmt->fetch();

if (!$member) {
    header('Location: members.php');
    exit;
}

// Get renewal history
$stmt = $pdo->prepare("SELECT * FROM renewals WHERE member_id = ? ORDER BY renewal_date DESC");
$stmt->execute([$memberId]);
$renewals = $stmt->fetchAll();

// Get registered events
$stmt = $pdo->prepare("SELECT e.*, er.registration_date 
                      FROM events e 
                      JOIN event_registrations er ON e.id = er.event_id 
                      WHERE er.member_id = ? 
                      ORDER BY e.event_date DESC");
$stmt->execute([$memberId]);
$events = $stmt->fetchAll();

$status = getMembershipStatus($member['expiry_date']);
$totalRenewals = count($renewals);
$totalRevenue = array_sum(array_column($renewals, 'amount'));
?>

<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-user-circle me-2"></i>Member Details: <?php echo htmlspecialchars($member['fullname']); ?></h1>
    <div>
        <a href="member_edit.php?id=<?php echo $memberId; ?>" class="btn btn-warning">
            <i class="fas fa-edit me-2"></i>Edit
        </a>
        <a href="member_idcard.php?id=<?php echo $memberId; ?>" class="btn btn-success">
            <i class="fas fa-id-card me-2"></i>ID Card
        </a>
        <a href="members.php" class="btn btn-secondary">
            <i class="fas fa-arrow-left me-2"></i>Back
        </a>
    </div>
</div>

<div class="row">
    <div class="col-md-4">
        <div class="card">
            <div class="card-body text-center">
                <img src="<?php echo UPLOAD_URL . $member['profile_photo']; ?>" 
                     style="width: 150px; height: 150px; object-fit: cover; border-radius: 50%; margin-bottom: 15px;"
                     onerror="this.src='assets/images/default-avatar.png'">
                <h4><?php echo htmlspecialchars($member['fullname']); ?></h4>
                <p class="text-muted"><?php echo htmlspecialchars($member['email']); ?></p>
                <p><strong>Member since:</strong> <?php echo formatDate($member['created_at']); ?></p>
                <p>
                    <span class="badge bg-<?php echo $status['class']; ?> fs-6">
                        <?php echo $status['status']; ?>
                    </span>
                </p>
            </div>
        </div>
        
        <div class="card mt-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Membership Info</h5>
            </div>
            <div class="card-body">
                <table class="table table-sm">
                    <tr>
                        <th>Membership No:</th>
                        <td><?php echo $member['membership_number']; ?></td>
                    </tr>
                    <tr>
                        <th>Membership Type:</th>
                        <td><?php echo $member['membership_type']; ?></td>
                    </tr>
                    <tr>
                        <th>Join Date:</th>
                        <td><?php echo formatDate($member['join_date']); ?></td>
                    </tr>
                    <tr>
                        <th>Expiry Date:</th>
                        <td><?php echo formatDate($member['expiry_date']); ?></td>
                    </tr>
                    <tr>
                        <th>Phone:</th>
                        <td><?php echo $member['phone'] ?: 'N/A'; ?></td>
                    </tr>
                    <tr>
                        <th>Occupation:</th>
                        <td><?php echo $member['occupation'] ?: 'N/A'; ?></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="fas fa-chart-line me-2"></i>Statistics</h5>
                    </div>
                    <div class="card-body">
                        <div class="text-center">
                            <h3><?php echo $totalRenewals; ?></h3>
                            <p>Total Renewals</p>
                            <hr>
                            <h3><?php echo formatCurrency($totalRevenue); ?></h3>
                            <p>Total Amount Paid</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h5 class="mb-0"><i class="fas fa-map-marker-alt me-2"></i>Address</h5>
                    </div>
                    <div class="card-body">
                        <p><strong>Address:</strong> <?php echo nl2br(htmlspecialchars($member['address'] ?: 'N/A')); ?></p>
                        <p><strong>City:</strong> <?php echo $member['city'] ?: 'N/A'; ?></p>
                        <p><strong>State:</strong> <?php echo $member['state'] ?: 'N/A'; ?></p>
                        <p><strong>Pincode:</strong> <?php echo $member['pincode'] ?: 'N/A'; ?></p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Renewal History -->
        <div class="card mt-4">
            <div class="card-header bg-warning text-dark">
                <h5 class="mb-0"><i class="fas fa-history me-2"></i>Renewal History</h5>
            </div>
            <div class="card-body">
                <?php if (count($renewals) > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Date</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 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>
                <?php else: ?>
                    <p class="text-muted">No renewal records found.</p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Registered Events -->
        <div class="card mt-4">
            <div class="card-header bg-secondary text-white">
                <h5 class="mb-0"><i class="fas fa-calendar-check me-2"></i>Registered Events</h5>
            </div>
            <div class="card-body">
                <?php if (count($events) > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Event Title</th>
                                    <th>Date</th>
                                    <th>Registration Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($events as $event): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($event['title']); ?></td>
                                    <td><?php echo formatDate($event['event_date']); ?></td>
                                    <td><?php echo formatDate($event['registration_date']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <p class="text-muted">No event registrations found.</p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Quick Actions -->
        <div class="card mt-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-bolt me-2"></i>Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="row g-2">
                    <div class="col-md-4">
                        <a href="member_edit.php?id=<?php echo $memberId; ?>" class="btn btn-warning w-100">
                            <i class="fas fa-edit"></i> Edit
                        </a>
                    </div>
                    <div class="col-md-4">
                        <a href="member_idcard.php?id=<?php echo $memberId; ?>" class="btn btn-success w-100">
                            <i class="fas fa-id-card"></i> ID Card
                        </a>
                    </div>
                    <div class="col-md-4">
                        <button class="btn btn-info w-100" onclick="sendEmail()">
                            <i class="fas fa-envelope"></i> Send Email
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Delete Member Section -->
        <div class="card mt-4 border-danger">
            <div class="card-header bg-danger text-white">
                <h5 class="mb-0"><i class="fas fa-trash-alt me-2"></i>Danger Zone</h5>
            </div>
            <div class="card-body">
                <p class="text-muted">Once you delete a member, all their data including renewal history and event registrations will be permanently removed.</p>
                <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteMemberModal">
                    <i class="fas fa-trash-alt me-2"></i>Delete Member
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Member Modal -->
<div class="modal fade" id="deleteMemberModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>Confirm Delete</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete <strong><?php echo htmlspecialchars($member['fullname']); ?></strong>?</p>
                <p class="text-danger">This action cannot be undone. All data associated with this member will be permanently deleted.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <a href="?action=delete&id=<?php echo $memberId; ?>" class="btn btn-danger">Yes, Delete Member</a>
            </div>
        </div>
    </div>
</div>

<script>
function sendEmail() {
    window.location.href = "mailto:<?php echo $member['email']; ?>?subject=Regarding your membership with BMYA";
}
</script>

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