<?php
include 'includes/header.php';

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

$user_id = $_SESSION['user_id'];

// Get current user data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Update user profile
if($_POST) {
    $phone = $_POST['phone'] ?? '';
    $location = $_POST['location'] ?? '';
    
    try {
        // Handle profile photo upload
        $profile_photo = $user['profile_photo'];
        if(isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === 0) {
            $upload_dir = 'assets/uploads/profiles/';
            if(!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if(in_array(strtolower($file_extension), $allowed_extensions)) {
                $new_filename = 'profile_' . $user_id . '_' . time() . '.' . $file_extension;
                $upload_path = $upload_dir . $new_filename;
                
                if(move_uploaded_file($_FILES['profile_photo']['tmp_name'], $upload_path)) {
                    // Delete old profile photo if exists
                    if($profile_photo && file_exists($profile_photo)) {
                        unlink($profile_photo);
                    }
                    $profile_photo = $upload_path;
                }
            }
        }
        
        $stmt = $pdo->prepare("UPDATE users SET phone = ?, location = ?, profile_photo = ? WHERE id = ?");
        $stmt->execute([$phone, $location, $profile_photo, $user_id]);
        
        $_SESSION['success'] = "Profile updated successfully!";
        header('Location: profile.php');
        exit;
        
    } catch(Exception $e) {
        $_SESSION['error'] = "Error updating profile: " . $e->getMessage();
    }
}
?>

<div class="container">
    <h1>My Profile</h1>
    
    <div class="profile-container">
        <div class="profile-sidebar">
            <div class="profile-photo">
                <img src="<?php echo $user['profile_photo'] ?: 'assets/default-avatar.jpg'; ?>" 
                     alt="Profile Photo" id="profile-preview">
                <form id="photo-form" enctype="multipart/form-data">
                    <input type="file" name="profile_photo" id="profile-photo-input" accept="image/*" 
                           onchange="previewImage(this)">
                    <label for="profile-photo-input" class="btn btn-secondary">Change Photo</label>
                </form>
            </div>
            
            <div class="profile-stats">
                <h3>Voting Stats</h3>
                <?php
                // Get voting statistics
                $total_votes_stmt = $pdo->prepare("
                    SELECT COUNT(*) as total_votes 
                    FROM votes 
                    WHERE user_id = ? AND player_id IS NOT NULL
                ");
                $total_votes_stmt->execute([$user_id]);
                $total_votes = $total_votes_stmt->fetchColumn();
                
                $game_weeks_stmt = $pdo->prepare("
                    SELECT COUNT(DISTINCT game_week) as total_weeks 
                    FROM votes 
                    WHERE user_id = ?
                ");
                $game_weeks_stmt->execute([$user_id]);
                $total_weeks = $game_weeks_stmt->fetchColumn();
                
                $last_vote = $pdo->prepare("SELECT MAX(created_at) as last_vote FROM votes WHERE user_id = ?");
                $last_vote->execute([$user_id]);
                $last_vote_data = $last_vote->fetch(PDO::FETCH_ASSOC);
                ?>
                
                <div class="stat-item">
                    <span>Total Votes:</span>
                    <strong><?php echo $total_votes; ?></strong>
                </div>
                <div class="stat-item">
                    <span>Game Weeks:</span>
                    <strong><?php echo $total_weeks; ?></strong>
                </div>
                <div class="stat-item">
                    <span>Last Vote:</span>
                    <strong><?php echo $last_vote_data['last_vote'] ? date('M j, Y', strtotime($last_vote_data['last_vote'])) : 'Never'; ?></strong>
                </div>
            </div>
        </div>
        
        <div class="profile-content">
            <form method="POST" enctype="multipart/form-data" id="profile-form">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Username:</label>
                        <input type="text" value="<?php echo htmlspecialchars($user['username']); ?>" disabled>
                        <small>Username cannot be changed</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Email:</label>
                        <input type="email" value="<?php echo htmlspecialchars($user['email']); ?>" disabled>
                        <small>Email cannot be changed</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Phone Number:</label>
                        <input type="tel" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" 
                               placeholder="Enter your phone number">
                    </div>
                    
                    <div class="form-group">
                        <label>Location:</label>
                        <input type="text" name="location" value="<?php echo htmlspecialchars($user['location'] ?? ''); ?>" 
                               placeholder="Enter your location">
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">Update Profile</button>
                    <a href="change-password.php" class="btn btn-secondary">Change Password</a>
                </div>
            </form>
            
            <!-- Enhanced Voting History -->
            <div class="voting-history">
                <h3>My Voting History</h3>
                <?php
                // Get detailed voting statistics
                $total_votes_stmt = $pdo->prepare("
                    SELECT COUNT(*) as total_votes 
                    FROM votes 
                    WHERE user_id = ? AND player_id IS NOT NULL
                ");
                $total_votes_stmt->execute([$user_id]);
                $total_votes = $total_votes_stmt->fetchColumn();
                
                $game_weeks_stmt = $pdo->prepare("
                    SELECT COUNT(DISTINCT game_week) as total_weeks 
                    FROM votes 
                    WHERE user_id = ?
                ");
                $game_weeks_stmt->execute([$user_id]);
                $total_weeks = $game_weeks_stmt->fetchColumn();
                
                $recent_votes_stmt = $pdo->prepare("
                    SELECT v.game_week, v.created_at, 
                           COUNT(DISTINCT v.id) as vote_count,
                           GROUP_CONCAT(DISTINCT p.name SEPARATOR ', ') as players,
                           c.name as coach
                    FROM votes v 
                    LEFT JOIN players p ON v.player_id = p.id 
                    LEFT JOIN coaches c ON v.coach_id = c.id 
                    WHERE v.user_id = ? 
                    GROUP BY v.game_week, v.created_at, c.name
                    ORDER BY v.created_at DESC
                    LIMIT 10
                ");
                $recent_votes_stmt->execute([$user_id]);
                $voting_history = $recent_votes_stmt->fetchAll(PDO::FETCH_ASSOC);
                ?>
                
                <div class="voting-stats" style="background: #f8f9fa; padding: 1rem; border-radius: 8px; margin-bottom: 1.5rem;">
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem;">
                        <div class="stat-card">
                            <div class="stat-number"><?php echo $total_votes; ?></div>
                            <div class="stat-label">Total Player Votes</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number"><?php echo $total_weeks; ?></div>
                            <div class="stat-label">Game Weeks Voted</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number"><?php echo count($voting_history); ?></div>
                            <div class="stat-label">Recent Votes</div>
                        </div>
                    </div>
                </div>
                
                <?php if($voting_history): ?>
                    <div class="history-list">
                        <?php foreach($voting_history as $history): ?>
                        <div class="history-item">
                            <div class="history-header">
                                <strong>Game Week <?php echo $history['game_week']; ?></strong>
                                <span><?php echo date('M j, Y g:i A', strtotime($history['created_at'])); ?></span>
                            </div>
                            <div class="history-details">
                                <span><strong>Players Voted:</strong> <?php echo $history['players'] ?: 'None'; ?></span>
                                <span><strong>Coach:</strong> <?php echo $history['coach'] ?: 'None'; ?></span>
                            </div>
                            <div class="history-footer">
                                <small>Total votes in this submission: <?php echo $history['vote_count']; ?> players + 1 coach</small>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p>No voting history yet. <a href="vote.php">Cast your first vote!</a></p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function previewImage(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('profile-preview').src = e.target.result;
            // Auto-submit the form when photo is selected
            document.getElementById('profile-form').submit();
        }
        reader.readAsDataURL(input.files[0]);
    }
}

// Show file name when selected
document.getElementById('profile-photo-input').addEventListener('change', function(e) {
    const fileName = e.target.files[0]?.name;
    if(fileName) {
        const label = document.querySelector('label[for="profile-photo-input"]');
        label.textContent = 'Selected: ' + fileName;
    }
});
</script>

<style>
.profile-container {
    display: grid;
    grid-template-columns: 300px 1fr;
    gap: 3rem;
    margin-top: 2rem;
}

.profile-sidebar {
    background: white;
    padding: 2rem;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    height: fit-content;
}

.profile-photo {
    text-align: center;
    margin-bottom: 2rem;
}

.profile-photo img {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    object-fit: cover;
    margin-bottom: 1rem;
    border: 5px solid var(--light);
}

.profile-stats {
    border-top: 1px solid #e0e0e0;
    padding-top: 1.5rem;
}

.stat-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 1rem;
    padding: 0.5rem 0;
}

.stat-item:not(:last-child) {
    border-bottom: 1px solid #f0f0f0;
}

.profile-content {
    background: white;
    padding: 2rem;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1.5rem;
}

.form-actions {
    display: flex;
    gap: 1rem;
    margin-top: 2rem;
    padding-top: 2rem;
    border-top: 1px solid #e0e0e0;
}

.voting-history {
    margin-top: 3rem;
    padding-top: 2rem;
    border-top: 1px solid #e0e0e0;
}

.history-list {
    margin-top: 1rem;
}

.history-item {
    background: #f8f9fa;
    padding: 1rem;
    border-radius: 5px;
    margin-bottom: 1rem;
}

.history-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
}

.history-details {
    display: flex;
    justify-content: space-between;
    font-size: 0.9rem;
    color: #666;
}

.history-footer {
    margin-top: 0.5rem;
    padding-top: 0.5rem;
    border-top: 1px solid #e0e0e0;
    font-size: 0.8rem;
    color: var(--gray);
}

.stat-card {
    background: white;
    padding: 1rem;
    border-radius: 8px;
    text-align: center;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.stat-number {
    font-size: 1.8rem;
    font-weight: bold;
    color: var(--primary-blue);
    margin-bottom: 0.5rem;
}
.stat-label {
    color: var(--gray);
    font-size: 0.9rem;
}

@media (max-width: 768px) {
    .profile-container {
        grid-template-columns: 1fr;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .form-actions {
        flex-direction: column;
    }
    
    .history-details {
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .history-header {
        flex-direction: column;
        gap: 0.5rem;
    }
}
</style>

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