<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use Google\Client as GoogleClient;

class GoogleOAuthController extends Controller
{
    public function test() {
        $reviews = \App\Console\Commands\SyncGoogleReviews::getCachedReviews();

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

        // clean comments and sort by date
        $reviews = array_map(function($review) {
            $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'],
                'date' => $review['updateTime'],
                'author' => $review['reviewer']['displayName'] ?? 'Anonyme',
                'photo' => $review['reviewer']['profilePhotoUrl'] ?? null,
            ];
        }, $reviews);

        dd($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));
    }

    public function redirect()
    {
        $client = new GoogleClient();
        $client->setClientId(config('services.google.client_id'));
        $client->setClientSecret(config('services.google.client_secret'));
        $client->setRedirectUri(route('google.callback'));
        $client->addScope('https://www.googleapis.com/auth/business.manage');
        $client->setAccessType('offline');
        $client->setPrompt('consent');

        return redirect()->away($client->createAuthUrl());
    }

    public function handleCallback(Request $request)
    {
        $client = new GoogleClient();
        $client->setClientId(config('services.google.client_id'));
        $client->setClientSecret(config('services.google.client_secret'));
        $client->setRedirectUri(route('google.callback'));

        $token = $client->fetchAccessTokenWithAuthCode($request->input('code'));

        // 🔁 Le refresh_token est là une fois pour toutes
        dd($token); // -> ['access_token' => ..., 'refresh_token' => ..., etc.]
    }
}
