<?php

namespace App\Http\Controllers;

class PageController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function home()
    {
        $reviews = \App\Console\Commands\SyncGoogleReviews::getCachedReviews();

        // filter all reviews no comments or no five stars and limit to 3
        $reviews = array_filter($reviews, function($review) {
            return !empty($review['comment']) && $review['starRating'] == "FIVE";
        });
        $reviews = array_slice($reviews, 0, 3);

        // clean comments and sort by date
        $reviews = array_map(function($review) {
            if(!isset($review['comment'])) {
                $review['comment'] = null; // ensure comment is set
            } else {
                $review['comment'] = self::cleanComment($review['comment']);
            }
            return $review;
        }, $reviews);

        // recreate object (not array) with comment, date and author
        $reviews = array_map(function($review) {
            return (object) [
                'comment' => $review['comment'] ?? null,
                'photo' => $review['reviewer']['profilePhotoUrl'] ?? null,
                'date' => $review['updateTime'],
                'author' => $review['reviewer']['displayName'] ?? 'Anonyme',
            ];
        }, $reviews);

        return view('home', array(
            'reviews' => $reviews,
        ));
    }

    protected static function cleanComment(?string $comment): ?string
    {
        if (!$comment) return null;

        // Séparer par lignes
        $lines = preg_split('/\r\n|\n|\r/', $comment);

        // Supprimer tout après "(Translated by Google)"
        $cleanedLines = [];
        foreach ($lines as $line) {
            if (stripos($line, 'translated by google') !== false) {
                break; // stop à partir d'ici
            }
            $cleanedLines[] = $line;
        }

        // Nettoyage final
        return trim(implode("\n", $cleanedLines));
    }
}
