<?php
require_once '../../core/bootstrap.php';

if (!isset($_SESSION['user_id'])) {
    exit('');
}

$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) ?: 1;
$limit = 6;
$offset = ($page - 1) * $limit;

$db = new Database();

// Get user's clubs from memberships (Same logic as index.php)
$db->query("SELECT club_id FROM memberships WHERE user_id = :uid AND expiry_date >= CURDATE()");
$db->bind(':uid', $_SESSION['user_id']);
$memberships = $db->resultSet();
$club_ids = array_map(fn($m) => $m->club_id, $memberships);

if (empty($club_ids)) {
    exit('');
}

$in_clubs = implode(',', array_map('intval', $club_ids));

$all_feed_items = [];

// Fetch Fixtures (Recent Results & Upcoming)
// Using a wider date range (-60 to +30 days) to allow scrolling back in time
// JOINing clubs table to get Club Names and Logos
$query = "SELECT f.*, 
                 hc.name as home_team_name, ht.club_id as home_club_id,
                 ac.name as away_team_name, at.club_id as away_club_id,
                 hc.logo as home_team_logo, ac.logo as away_team_logo
          FROM fixtures f
          JOIN teams ht ON f.home_team_id = ht.id
          LEFT JOIN clubs hc ON ht.club_id = hc.id
          JOIN teams at ON f.away_team_id = at.id
          LEFT JOIN clubs ac ON at.club_id = ac.id
          WHERE (ht.club_id IN ($in_clubs) OR at.club_id IN ($in_clubs))
          AND f.match_datetime BETWEEN DATE_SUB(NOW(), INTERVAL 60 DAY) AND DATE_ADD(NOW(), INTERVAL 2 DAY)
          ORDER BY f.match_datetime DESC";

$db->query($query);
$fixtures_feed = $db->resultSet();

foreach ($fixtures_feed as $f) {
    $match_timestamp = strtotime($f->match_datetime);
    $time_diff = $match_timestamp - time();
    if ($f->status === 'finished') {
        $type = 'match_report';
    } elseif ($time_diff <= 3600 && $f->status !== 'finished') {
        $type = 'lineups_announced';
    } else {
        $type = 'match_preview';
    }
    $all_feed_items[] = ['type' => $type, 'timestamp' => $match_timestamp, 'data' => $f, 'id' => $f->id];
}

// Fetch recent suspensions for these clubs
$db->query("SELECT ps.*, u.first_name, u.last_name, u.profile_picture, t.name as team_name, c.name as club_name, c.logo as club_logo
          FROM player_suspensions ps
          JOIN players p ON ps.player_id = p.user_id
          JOIN users u ON p.user_id = u.id
          JOIN teams t ON p.team_id = t.id
          JOIN clubs c ON t.club_id = c.id
          WHERE t.club_id IN ($in_clubs)
          AND ps.created_at BETWEEN DATE_SUB(NOW(), INTERVAL 60 DAY) AND NOW()
          ORDER BY ps.created_at DESC");
$suspensions_feed = $db->resultSet();

foreach ($suspensions_feed as $s) {
    $all_feed_items[] = ['type' => 'suspension', 'timestamp' => strtotime($s->created_at), 'data' => $s, 'id' => $s->id];
}

// Fetch injury recoveries for these clubs
$db->query("SELECT i.*, u.first_name, u.last_name, u.profile_picture, t.name as team_name, c.name as club_name, c.logo as club_logo
          FROM injuries i
          JOIN players p ON i.player_id = p.user_id
          JOIN users u ON p.user_id = u.id
          JOIN teams t ON p.team_id = t.id
          JOIN clubs c ON t.club_id = c.id
          WHERE t.club_id IN ($in_clubs)
          AND i.status = 'Fit'
          AND i.expected_return_date BETWEEN DATE_SUB(NOW(), INTERVAL 60 DAY) AND NOW()
          ORDER BY i.expected_return_date DESC");
$recoveries_feed = $db->resultSet();

foreach ($recoveries_feed as $r) {
    $all_feed_items[] = ['type' => 'injury_recovery', 'timestamp' => strtotime($r->expected_return_date), 'data' => $r, 'id' => $r->id];
}

// Sort all items and then paginate
usort($all_feed_items, fn($a, $b) => $b['timestamp'] <=> $a['timestamp']);
$paginated_items = array_slice($all_feed_items, $offset, $limit);

if (empty($paginated_items)) {
    exit('');
}

foreach ($paginated_items as $item) {
    $data = $item['data'];
    $id = $item['id'];
    $timestamp = $item['timestamp'];
    $type = $item['type'];
    
    $type_label = ucwords(str_replace('_', ' ', $type));
    if ($type === 'match_report') {
        $title = "Report: {$data->home_team_name} {$data->home_team_score}-{$data->away_team_score} {$data->away_team_name}";
        $desc = "Full match analysis, player ratings, and key moments from the game.";
        $img = $data->home_team_logo;
    } elseif ($type === 'lineups_announced') {
        $title = "Lineups: {$data->home_team_name} vs {$data->away_team_name}";
        $desc = "Confirmed starting XIs and substitutes. See who made the cut.";
        $img = $data->home_team_logo;
    } elseif ($type === 'suspension') {
        $title = "Suspension: {$data->first_name} {$data->last_name}";
        $desc = "{$data->first_name} {$data->last_name} has received a suspension following a disciplinary incident.";
        $img = $data->profile_picture ?? $data->club_logo;
    } elseif ($type === 'injury_recovery') {
        $title = "Injury Update: {$data->first_name} {$data->last_name}";
        $desc = "Good news for {$data->club_name} as {$data->first_name} {$data->last_name} returns to full fitness.";
        $img = $data->profile_picture ?? $data->club_logo;
    } else {
        $title = "Preview: {$data->home_team_name} vs {$data->away_team_name}";
        $desc = "Team news, tactical analysis, and lineup predictions for the upcoming clash.";
        $img = $data->away_team_logo;
    }
    
    // Output HTML for the card
    ?>
    <a href="feed_post.php?type=<?php echo $type; ?>&id=<?php echo $id; ?>" class="feed-card">
        <div class="feed-img-container">
            <img src="<?php echo htmlspecialchars($img); ?>" alt="Club Logo" class="feed-bg-logo">
            <span class="feed-tag"><?php echo $type_label; ?></span>
        </div>
        <div class="feed-content">
            <h3><?php echo htmlspecialchars($title); ?></h3>
            <p><?php echo $desc; ?></p>
            <span class="feed-time"><?php echo date('d M, H:i', $timestamp); ?></span>
        </div>
    </a>
    <?php
}
?>
