<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Include database configuration and functions
require_once 'includes/config.php';
require_once 'includes/functions.php';  // Functions are now included from here

// Get user data with error handling
$userData = [];
try {
    $stmt = $pdo->prepare("SELECT m.*, mt.type as membership_type_name, 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([$_SESSION['user_id']]);
    $userData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$userData) {
        // If user not found, logout and redirect
        session_destroy();
        header('Location: login.php');
        exit;
    }
} catch (PDOException $e) {
    $userData = [];
}

// Set user name in session if not set
if (!isset($_SESSION['user_name']) && isset($userData['fullname'])) {
    $_SESSION['user_name'] = $userData['fullname'];
}

// Get membership status
$status = ['status' => 'Active', 'class' => 'success'];
if (isset($userData['expiry_date']) && !empty($userData['expiry_date']) && $userData['expiry_date'] != '0000-00-00') {
    $today = new DateTime();
    $expiry = new DateTime($userData['expiry_date']);
    $diff = $today->diff($expiry)->days;
    
    if ($expiry < $today) {
        $status = ['status' => 'Expired', 'class' => 'danger'];
    } elseif ($diff <= 30) {
        $status = ['status' => 'Expiring Soon', 'class' => 'warning'];
    }
} elseif (empty($userData['expiry_date']) || $userData['expiry_date'] == '0000-00-00') {
    $status = ['status' => 'Lifetime', 'class' => 'success'];
}

// Get recent renewals with error handling
$recentRenewals = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM renewals WHERE member_id = ? ORDER BY renewal_date DESC LIMIT 5");
    $stmt->execute([$_SESSION['user_id']]);
    $recentRenewals = $stmt->fetchAll();
} catch (PDOException $e) {
    $recentRenewals = [];
}

// Get registered events with error handling
$registeredEvents = [];
try {
    $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 = ? AND e.event_date >= CURDATE() 
                          ORDER BY e.event_date LIMIT 5");
    $stmt->execute([$_SESSION['user_id']]);
    $registeredEvents = $stmt->fetchAll();
} catch (PDOException $e) {
    $registeredEvents = [];
}

// Get dashboard stats (revenue removed)
$stats = [
    'total_members' => 0,
    'new_members' => 0,
    'upcoming_events' => 0,
    'expiring_members' => 0
];

try {
    // Total members
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM members WHERE status = 'active'");
    $result = $stmt->fetch();
    $stats['total_members'] = $result ? $result['count'] : 0;
    
    // Upcoming events
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM events WHERE event_date >= CURDATE() AND status = 'upcoming'");
    $result = $stmt->fetch();
    $stats['upcoming_events'] = $result ? $result['count'] : 0;
    
    // Expiring members
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM members WHERE expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)");
    $stmt->execute();
    $result = $stmt->fetch();
    $stats['expiring_members'] = $result ? $result['count'] : 0;
    
    // New members this month
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM members WHERE MONTH(join_date) = MONTH(CURDATE()) AND YEAR(join_date) = YEAR(CURDATE())");
    $result = $stmt->fetch();
    $stats['new_members'] = $result ? $result['count'] : 0;
    
    // Total revenue query removed
} catch (PDOException $e) {
    // Keep default values
}

// Include header
include 'header.php';
?>

<div class="row">
    <!-- Left Column - Profile Card -->
    <div class="col-md-4 mb-4">
        <div class="card text-center h-100">
            <div class="card-body">
                <?php
                $profilePhoto = 'assets/images/default-avatar.png';
                if (isset($userData['profile_photo']) && !empty($userData['profile_photo']) && $userData['profile_photo'] != 'default.jpg') {
                    if (file_exists('uploads/' . $userData['profile_photo'])) {
                        $profilePhoto = 'uploads/' . $userData['profile_photo'];
                    }
                }
                ?>
                <img src="<?php echo $profilePhoto; ?>" class="profile-pic mb-3" alt="Profile Photo">
                
                <!-- Membership Details Card - Shifted here after profile picture -->
                <div class="membership-details-inline text-start mt-3 mb-3 p-3 bg-light rounded">
                    <h6 class="text-primary mb-3"><i class="fas fa-id-card me-2"></i>Membership Details</h6>
                    <p class="mb-2"><strong>Membership No:</strong><br><?php echo htmlspecialchars($userData['membership_number'] ?? 'N/A'); ?></p>
                    <p class="mb-2"><strong>Membership Type:</strong><br><?php echo htmlspecialchars($userData['membership_type_name'] ?? 'N/A'); ?></p>
                    <p class="mb-0"><strong>Expiry Date:</strong><br><?php echo formatDate($userData['expiry_date'] ?? ''); ?></p>
                    <a href="renew.php" class="btn btn-warning btn-sm w-100 mt-3">Renew Membership</a>
                </div>
                
                <h4><?php echo htmlspecialchars($userData['fullname'] ?? 'Member'); ?></h4>
                <p class="text-muted"><?php echo htmlspecialchars($userData['email'] ?? 'N/A'); ?></p>
                <p><strong>Member since:</strong> <?php echo formatDate($userData['join_date'] ?? ''); ?></p>
                <p>
                    <span class="badge bg-<?php echo $status['class']; ?>">
                        <?php echo $status['status']; ?>
                    </span>
                </p>
            </div>
        </div>
    </div>
    
    <!-- Right Column -->
    <div class="col-md-8">
        <!-- Statistics Row - Revenue card removed -->
        <div class="row">
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="dashboard-stat">
                    <i class="fas fa-users text-primary"></i>
                    <h3><?php echo number_format($stats['total_members']); ?></h3>
                    <p>Total Members</p>
                </div>
            </div>
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="dashboard-stat">
                    <i class="fas fa-calendar-alt text-success"></i>
                    <h3><?php echo number_format($stats['upcoming_events']); ?></h3>
                    <p>Upcoming Events</p>
                </div>
            </div>
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="dashboard-stat">
                    <i class="fas fa-clock text-warning"></i>
                    <h3><?php echo number_format($stats['expiring_members']); ?></h3>
                    <p>Expiring Soon</p>
                </div>
            </div>
        </div>
        
        <!-- Renewal History -->
        <div class="card mt-3">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="fas fa-history me-2"></i>Renewal History</h5>
            </div>
            <div class="card-body">
                <?php if (!empty($recentRenewals)): ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>Date</th>
                                    <th>Amount</th>
                                    <th>Expiry Date</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentRenewals as $renewal): ?>
                                <tr>
                                    <td><?php echo formatDate($renewal['renewal_date'] ?? ''); ?></td>
                                    <td class="text-success fw-bold"><?php echo formatCurrency($renewal['amount'] ?? 0); ?></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: ?>
                    <div class="text-center py-4">
                        <i class="fas fa-info-circle fa-3x text-muted mb-3"></i>
                        <p class="text-muted">No renewal history found.</p>
                        <a href="renew.php" class="btn btn-warning btn-sm">Renew Now</a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Registered Events -->
        <div class="card mt-4">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="fas fa-calendar-check me-2"></i>My Events</h5>
            </div>
            <div class="card-body">
                <?php if (!empty($registeredEvents)): ?>
                    <?php foreach ($registeredEvents as $event): ?>
                        <div class="alert alert-light border-start border-4 border-primary mb-3">
                            <div class="d-flex justify-content-between align-items-start flex-wrap">
                                <div class="flex-grow-1">
                                    <h6 class="mb-1"><?php echo htmlspecialchars($event['title'] ?? 'N/A'); ?></h6>
                                    <p class="mb-0 small">
                                        <i class="fas fa-calendar text-primary me-1"></i> <?php echo formatDate($event['event_date'] ?? ''); ?>
                                        <span class="mx-2">|</span>
                                        <i class="fas fa-map-marker-alt text-danger me-1"></i> <?php echo htmlspecialchars($event['venue'] ?? 'TBA'); ?>
                                    </p>
                                    <small class="text-muted">
                                        <i class="fas fa-clock me-1"></i> Registered on: <?php echo formatDate($event['registration_date'] ?? ''); ?>
                                    </small>
                                </div>
                                <a href="events.php" class="btn btn-sm btn-outline-primary mt-2 mt-sm-0">
                                    <i class="fas fa-eye"></i> Details
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="text-center py-4">
                        <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                        <p class="text-muted">You haven't registered for any events yet.</p>
                        <a href="events.php" class="btn btn-primary btn-sm">Browse Events</a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Quick Actions -->
        <div class="card mt-4">
            <div class="card-header bg-secondary 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-6 col-md-3">
                        <a href="profile.php" class="btn btn-outline-primary w-100 py-3">
                            <i class="fas fa-user-edit fa-2x d-block mb-2"></i>
                            <small>Edit Profile</small>
                        </a>
                    </div>
                    <div class="col-6 col-md-3">
                        <a href="id_card.php" class="btn btn-outline-success w-100 py-3">
                            <i class="fas fa-id-card fa-2x d-block mb-2"></i>
                            <small>ID Card</small>
                        </a>
                    </div>
                    <div class="col-6 col-md-3">
                        <a href="renew.php" class="btn btn-outline-warning w-100 py-3">
                            <i class="fas fa-sync-alt fa-2x d-block mb-2"></i>
                            <small>Renew</small>
                        </a>
                    </div>
                    <div class="col-6 col-md-3">
                        <a href="events.php" class="btn btn-outline-info w-100 py-3">
                            <i class="fas fa-calendar fa-2x d-block mb-2"></i>
                            <small>Events</small>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.dashboard-stat {
    text-align: center;
    padding: 20px 15px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}

.dashboard-stat:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.1);
}

.dashboard-stat i {
    font-size: 2rem;
    margin-bottom: 10px;
}

.dashboard-stat h3 {
    font-size: 1.5rem;
    margin-bottom: 5px;
    font-weight: 700;
}

.dashboard-stat p {
    color: #6c757d;
    margin-bottom: 0;
    font-size: 0.85rem;
    font-weight: 500;
}

.profile-pic {
    width: 120px;
    height: 120px;
    object-fit: cover;
    border-radius: 50%;
    border: 3px solid #3498db;
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.card {
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    overflow: hidden;
}

.card-header {
    border-radius: 12px 12px 0 0 !important;
    font-weight: 600;
}

.alert-light {
    background-color: #f8f9fa;
    border-left: 4px solid #3498db !important;
    transition: all 0.3s ease;
}

.alert-light:hover {
    background-color: #eef2f7;
    transform: translateX(5px);
}

.membership-details-inline {
    border-left: 4px solid #0d6efd;
}

@media (max-width: 768px) {
    .profile-pic {
        width: 90px;
        height: 90px;
    }
    
    .dashboard-stat h3 {
        font-size: 1.2rem;
    }
    
    .dashboard-stat i {
        font-size: 1.5rem;
    }
    
    .dashboard-stat {
        padding: 15px 10px;
    }
}

@media (max-width: 576px) {
    .col-6 {
        margin-bottom: 8px;
    }
}
</style>