<?php
$pageTitle = 'My Profile';
include 'includes/header.php';

// --- Authentication Check ---
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
$user_id = $_SESSION['user_id'];

// --- Instantiate Models ---
$userModel = new User();
$db = new Database();

// --- Fetch Active Memberships ---
$db->query("SELECT m.*, c.name as club_name, c.logo as club_logo 
            FROM memberships m 
            JOIN clubs c ON m.club_id = c.id 
            WHERE m.user_id = :user_id AND m.expiry_date >= CURDATE() 
            ORDER BY m.expiry_date ASC");
$db->bind(':user_id', $user_id);
$active_memberships = $db->resultSet();

// --- Fetch User Data ---
$user = $userModel->getFullUserDetailsById($user_id);

if (!$user) {
    echo "<p class='error-msg'>Could not load user profile.</p>";
    include 'includes/footer.php';
    exit();
}
?>

<div class="page-content">
    <div class="matches-header">
        <h1>My Profile</h1>
    </div>

    <!-- Display any success or error messages -->
    <?php if (isset($_GET['status'])): ?>
        <div class="status-message <?php echo $_GET['status'] === 'success' ? 'success' : 'error'; ?>">
            <?php
            if ($_GET['status'] === 'success') {
                echo 'Profile updated successfully!';
            } elseif (isset($_GET['error'])) {
                echo 'Error: ' . htmlspecialchars($_GET['error']);
            }
            ?>
        </div>
    <?php endif; ?>

    <div class="form-container" style="max-width: 700px; margin: auto;">
        <form action="profile_process.php" method="POST" enctype="multipart/form-data" class="auth-form">
            <input type="hidden" name="action" value="update_details">

            <h3>Personal Details</h3>
            <div class="form-group">
                <label for="first_name">First Name</label>
                <input type="text" id="first_name" name="first_name" value="<?php echo htmlspecialchars($user->first_name); ?>" required>
            </div>
            <div class="form-group">
                <label for="last_name">Last Name</label>
                <input type="text" id="last_name" name="last_name" value="<?php echo htmlspecialchars($user->last_name); ?>" required>
            </div>
            <div class="form-group">
                <label for="email">Email Address</label>
                <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($user->email); ?>" required>
            </div>
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($user->username); ?>" required>
            </div>

            <h3>Profile Images</h3>
            <div class="form-group">
                <label for="profile_picture">Profile Picture</label>
                <input type="file" id="profile_picture" name="profile_picture">
                <?php if ($user->profile_picture): ?>
                    <img src="<?php echo htmlspecialchars($user->profile_picture); ?>" alt="Current Profile Picture" style="width: 80px; height: 80px; border-radius: 50%; margin-top: 10px;">
                <?php endif; ?>
            </div>

            <button type="submit">Update Profile</button>
        </form>

        <hr style="margin: 2rem 0;">

        <h3>Notifications</h3>
        <div class="form-group">
            <button type="button" class="btn btn-secondary" onclick="subscribeToPush()">Enable Push Notifications</button>
            <button type="button" class="btn btn-danger" onclick="unsubscribeFromPush()" style="margin-left: 10px;">Unsubscribe</button>
            <small style="display:block; margin-top:5px; color:#666;">Receive updates about matches, transfers, and team news.</small>
        </div>

        <hr style="margin: 2rem 0;">

        <form action="profile_process.php" method="POST" class="auth-form">
            <input type="hidden" name="action" value="change_password">
            <h3>Change Password</h3>
            <div class="form-group">
                <label for="current_password">Current Password</label>
                <input type="password" id="current_password" name="current_password" required>
            </div>
            <div class="form-group">
                <label for="new_password">New Password</label>
                <input type="password" id="new_password" name="new_password" required>
            </div>
            <div class="form-group">
                <label for="confirm_password">Confirm New Password</label>
                <input type="password" id="confirm_password" name="confirm_password" required>
            </div>
            <button type="submit">Change Password</button>
        </form>

        <hr style="margin: 2rem 0;">

        <h3>My Memberships</h3>
        <?php if (!empty($active_memberships)): ?>
            <div class="table-wrapper">
                <table class="styled-table">
                    <thead><tr><th>Club</th><th>Type</th><th>Expiry</th><th>Status</th><th>Action</th></tr></thead>
                    <tbody>
                        <?php foreach($active_memberships as $membership): 
                            $days_left = ceil((strtotime($membership->expiry_date) - time()) / (60 * 60 * 24));
                            $is_expiring = $days_left <= 7;
                        ?>
                            <tr>
                                <td>
                                    <div style="display: flex; align-items: center; gap: 10px;">
                                        <img src="<?php echo htmlspecialchars($membership->club_logo); ?>" alt="" style="width: 30px; height: 30px; object-fit: contain; border-radius: 50%;">
                                        <?php echo htmlspecialchars($membership->club_name); ?>
                                    </div>
                                </td>
                                <td><?php echo htmlspecialchars($membership->membership_type); ?></td>
                                <td><?php echo date('d M Y', strtotime($membership->expiry_date)); ?></td>
                                <td>
                                    <span style="background: #d4edda; color: #155724; padding: 4px 8px; border-radius: 12px; font-size: 0.8rem; font-weight: 600;">Active</span>
                                    <?php if ($is_expiring): ?><div style="font-size: 0.75rem; color: #e74c3c; margin-top: 4px;">Expiring in <?php echo max(0, $days_left); ?> days</div><?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($is_expiring): ?>
                                        <a href="memberships.php?q=<?php echo urlencode($membership->club_name); ?>" class="btn-sm" style="text-decoration: none; background-color: var(--secondary-color); color: white; padding: 6px 12px; border-radius: 4px; font-size: 0.8rem;">Renew</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <p class="no-data-msg" style="text-align: center; color: #777;">You don't have any active memberships.</p>
            <div style="text-align: center; margin-top: 10px;">
                <a href="memberships.php" class="btn-sm" style="text-decoration: none; background-color: var(--secondary-color); color: white; padding: 8px 16px; border-radius: 6px;">Browse Packages</a>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
async function unsubscribeFromPush() {
    if (!('serviceWorker' in navigator)) {
        alert('Push notifications are not supported in this browser.');
        return;
    }

    const registration = await navigator.serviceWorker.ready;
    const subscription = await registration.pushManager.getSubscription();

    if (!subscription) {
        alert('You are not currently subscribed to notifications.');
        return;
    }

    try {
        const endpoint = subscription.endpoint;
        await subscription.unsubscribe();
        
        // Notify server to remove from database
        await fetch('api/remove_subscription.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ endpoint: endpoint })
        });

        alert('Successfully unsubscribed from notifications.');
    } catch (error) {
        console.error('Error unsubscribing', error);
        alert('Failed to unsubscribe. Please try again.');
    }
}
</script>

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