<?php
    $page = preg_split('/[\/]/', $_SERVER['REQUEST_URI']);
    $long_page = count($page) - 1;
    $valid_segments = ['albums', 'chansons'];
    $url = '';
    
    for ($i = $long_page; $i >= 0; $i--) {
        if (in_array($page[$i], $valid_segments)) {
            $url = implode('/', array_slice($page, $i));
            break;
        }
    }
?>
<section class="album-details">
    <div class="album-content">
        <div class="album-image">
            <?php
            echo '<img src="data:image/jpeg;base64,' . base64_encode($albums->coverImage) . '" style="width: 300px; height: 300px;" alt="Album cover"/>';
            ?>
            <br>
            <br>
            <h4><?php echo $albums->name; ?></h4>
            <p><?php echo "Artiste : " . $albums->artist->name; ?></p>
            <p><?php echo "Année : " . $albums->year; ?></p>
        </div>
        <div class="album-songs">
            <?php
            echo "<table>";
            echo "<thead>";
            echo "<tr>";
            echo "<th>Titre</th>";
            echo "<th>Durée</th>";
            if ($this->session->userdata('logged_in')){  
                echo "<th>Action</th>";
            }
            echo "</tr>";
            echo "</thead>";
            echo "<tbody>";
            foreach ($albums->songs as $index => $song) {
                $artistName = $albums->artist->name; 
                $duration = isset($albums->tracks[$index]->duration) ? convertirSecondesEnMinutes($albums->tracks[$index]->duration) : ''; 
                echo "<tr>";
                echo "<td>" . $song . "</td>";
                echo "<td>" . $duration . "</td>";
                echo "<td>";
                if ($this->session->userdata('logged_in')){        
                    if($this->model_music->SongInPlaylist($albums->tracks[$index]->trackId)){
                        echo anchor("chansons/deleteSongtoPlaylist/{$albums->tracks[$index]->trackId}?page=$url", "<i class='fa fa-trash'></i>", ['title' => 'Supprimer de la playlist']);
                    }
                    echo anchor("chansons/addSongtoPlaylist/{$albums->tracks[$index]->trackId}?page=$url", "<i class='fa fa-plus'></i>", ['title' => 'Ajouter à la playlist']);
                }
                echo "</td>";
                echo "</tr>";
            }
            echo "</tbody>";
            echo "</table>";

            function convertirSecondesEnMinutes($secondes) {
                $minutes = floor($secondes / 60);
                $secondesRestantes = $secondes % 60;
                return sprintf('%02d:%02d', $minutes, $secondesRestantes);
            }
            ?>
        </div>
    </div>
</section>