<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use App\Services\GoogleSheetService;

class SyncToGoogleSheets extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:sheets';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync users to google sheet';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $users = User::where('sheets_synced', 0)->get();

        $spreadsheetId = '18HzBWKcVmEg6nOTOsaXcsBW9XgY3qxtzMkAml7HeWsM';
        $range = 'Try!A1'; // Adjust range based on where you want to append data

        foreach ($users as $user) {
            //find all that have finished
            if ($this->checkIfUserHasFinishedAttempt($user)) {


                // Data to append
                $values = [
                    $user->id,
                    $user->name,
                    $user->email,
                    $user->phone,
                    $user->highschool,
                    $user->highschool_year,
                    $this->getTime($user),
                    $this->getTime($user, '%d'),
                    $user->correctAnswers,
                    $user->attempt->memory_matrix_result ?? '/',
                    $user->attempt->memory_matrix_level ?? '/',
                    $user->attempt->memory_matrix_sublevel ?? '/',
                    $user->attempt->speed_arithmetic_result ?? '/',
                    $user->created_at->format('Y-m-d'),
                    $user->final_score
                ];

                // Initialize the Google Sheet service
                $googleSheetService = new GoogleSheetService($spreadsheetId);

                // Append the data
                $response = $googleSheetService->appendRow($range, $values);

                if ($response && $response->updates && $response->updates->updatedCells > 0) {
                    $user->sheets_synced = 1;
                    $user->save();
                }
            }
        }

        return Command::SUCCESS;
    }

    private function getTime($user, $seconds = false)
    {
        if (!$user->attempt) {
            return 'Not started';
        };

        if ($user->attempt->end_time == null) {
            return 'Expired';
        }

        if ($seconds) {
            return \Carbon\Carbon::parse($user->attempt->end_time)->diffInSeconds($user->attempt->start_time);
        }

        return \Carbon\Carbon::parse($user->attempt->end_time)->diff($user->attempt->start_time)->format('%i min %s seconds');
    }

    public function checkIfUserHasFinishedAttempt($user)
    {
        if (!is_null($user->attempt->memory_matrix_result)) {
            return true;
        }
        // if ($user->questions->count() > 0 && $user->hasAnsweredAllQuestions()) {
        //     return true;
        // }

        // if ($user->attempt->start_time) {
        //     if (\Carbon\Carbon::now()->diffInSeconds(\Carbon\Carbon::parse($user->attempt->start_time)) > $user->attempt->academy->duration) {
        //         return true;
        //     }
        // }

        return false;
    }
}
