<?php
require_once 'config.php';

function getAccessToken(): ?string {
    $tokensFile = '/home/megaloa1/dj.megaload.co.za/tokens.json';

    if (!file_exists($tokensFile)) {
        error_log("❌ tokens.json not found");
        return null;
    }

    $tokens = json_decode(file_get_contents($tokensFile), true);
    $access_token = $tokens['access_token'] ?? null;
    $refresh_token = $tokens['refresh_token'] ?? null;

    // Validate token
    $test = curl_init("https://api.spotify.com/v1/me");
    curl_setopt_array($test, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer $access_token"]
    ]);
    curl_exec($test);
    $http_code = curl_getinfo($test, CURLINFO_HTTP_CODE);
    curl_close($test);

    if ($http_code === 401 && $refresh_token) {
        $new_tokens = refreshAccessToken($refresh_token);
        if (!empty($new_tokens['access_token'])) {
            $tokens['access_token'] = $new_tokens['access_token'];
            file_put_contents($tokensFile, json_encode($tokens));
            return $new_tokens['access_token'];
        }
    }

    return $access_token;
}

function refreshAccessToken(string $refresh_token): ?array {
    $postFields = http_build_query([
        'grant_type' => 'refresh_token',
        'refresh_token' => $refresh_token,
        'client_id' => SPOTIFY_CLIENT_ID,
        'client_secret' => SPOTIFY_CLIENT_SECRET
    ]);

    $ch = curl_init('https://accounts.spotify.com/api/token');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => $postFields
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}

function fetchLikedTracks($access_token, $offset = 0, $limit = 50) {
    $url = "https://api.spotify.com/v1/me/tracks?limit=$limit&offset=$offset";
    $headers = ["Authorization: Bearer $access_token"];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}


function fetchAllLikedTracks(): array {
    $access_token = getAccessToken();
    $limit = 50;
    $offset = 0;
    $allTracks = [];

    do {
        $url = "https://api.spotify.com/v1/me/tracks?limit=$limit&offset=$offset";
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ["Authorization: Bearer $access_token"]
        ]);
        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);
        if (!isset($data['items'])) break;

        foreach ($data['items'] as $item) {
            $allTracks[] = $item['track'];
        }

        $offset += $limit;
    } while (count($data['items']) === $limit);

    return $allTracks;
}
?>