<?php

namespace App\Console\Commands;

use App\Models\BDTDevice;
use App\Models\Client;
use App\Models\SimpleProduct;
use Google\Service\Sheets\ValueRange;
use Google_Client;
use Illuminate\Console\Command;
use Revolution\Google\Sheets\Facades\Sheets;
use Revolution\Google\Sheets\Sheets as SheetsSheets;

class recordsToGsheet extends Command
{
  
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'records:export-to-gsheet';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Export records to gsheet';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->pushSheet();
        return 0;
    }


    function pushSheet(){

        $spreadsheetId = config('app.googleSpreadsheetId');
        $googleSpreadsheetProductsSheetName = config('app.googleSpreadsheetProductsSheetName'); 
       
        $client = $this->getApiClient();
        $service = new \Google\Service\Sheets($client);

        
        $values = $this->getValues();


        $range = $googleSpreadsheetProductsSheetName.'!A1:V1';
        $body = new ValueRange([
            'values' => $values
        ]);
        $params = [
           'valueInputOption' => 'RAW'
        ];

        $result = $service->spreadsheets_values->append($spreadsheetId, $range, $body, $params);

        $this->info(json_encode($result));

    }


    function getApiClient(){
      
        $KEY_FILE_LOCATION = storage_path('stag-gsheets-d9ead2f78b4b.json');

        $client = new Google_Client();
        $client->setApplicationName("My Rooster Admin");
        $client->setAuthConfig($KEY_FILE_LOCATION);
        
        $client->setScopes([\Google\Service\Sheets::DRIVE, \Google\Service\Sheets::SPREADSHEETS]);

        return $client;

    }


    private function getValues(){

        $values = [];

        $values[] = [
            'Device Type',
			'IMEI',
			'Issued Yet?',
			'Client',
			'Used?',
			'MCP',
			'Issue Date',
			'Last Meas. Date',
			'Last Meas. Days Ago',
			'Days with Remote Meas. this Month',
			'Days with Remote Meas. last Month',
			'Client Engagement Status Category',
			'Admin Engagement Assessment Status',
			'Mcp Engagement Assessment Status',
			'Default Na Engagement Assessment Status',
        ];

        BDTDevice::chunk(1, function($bdtDevices) use (&$values){
            foreach($bdtDevices as $bdtDevice){
                $bdtDeviceStr =  $bdtDevice->category.'~~'.
                    $bdtDevice->imei.'~~'.
                    ($bdtDevice->clientBDTDevice ? 'Yes': 'No').'~~'.
                    ($bdtDevice->clientBDTDevice?$bdtDevice->clientBDTDevice->client->displayName():'-').'~~'.
                    ($bdtDevice->clientBDTDevice && $bdtDevice->clientBDTDevice->mostRecentMeasurement ? 'Yes': 'No').'~~'.
                    ($bdtDevice->clientBDTDevice && $bdtDevice->clientBDTDevice->client->mcp ? $bdtDevice->clientBDTDevice->client->mcp->name_first.' '.$bdtDevice->clientBDTDevice->client->mcp->name_last:'-').'~~'.
                    ($bdtDevice->clientBdtDevice? friendly_date_time($bdtDevice->clientBDTDevice->created_at) : '-').'~~'.
                    ($bdtDevice->clientBDTDevice && $bdtDevice->clientBDTDevice->mostRecentMeasurement ? friendly_date_time($bdtDevice->clientBDTDevice->mostRecentMeasurement->measurement->ts_date_time) : '-').'~~'.
                    ($bdtDevice->clientBDTDevice && $bdtDevice->clientBDTDevice->mostRecentMeasurement ? (date_diff(date_create($bdtDevice->clientBDTDevice->mostRecentMeasurement->measurement->ts_date_time), date_create('now'))->days) : '-').'~~'.
                    (($bdtDevice->clientBDTDevice && $bdtDevice->clientBDTDevice->client->currentCareMonth()) ? $bdtDevice->clientBDTDevice->client->currentCareMonth()->number_of_days_with_remote_measurements:'-').'~~'.
                    (($bdtDevice->clientBDTDevice && $bdtDevice->clientBDTDevice->client->previousCareMonth()) ? $bdtDevice->clientBDTDevice->client->previousCareMonth()->number_of_days_with_remote_measurements:'-').'~~'.
                    @$bdtDevice->clientBDTDevice->client->client_engagement_status_category.'~~'.
                    @$bdtDevice->clientBDTDevice->client->adminEngagementAssessmentStatus->status_category.'~~'.
                    @$bdtDevice->clientBDTDevice->client->mcpEngagementAssessmentStatus->status_category.'~~'.
                    @$bdtDevice->clientBDTDevice->client->defaultNaEngagementAssessmentStatus->status_category.'~~';
                $values[] = explode('~~', $bdtDeviceStr);
            }
        });

        return $values;
    }

    
}

				
			
			
				
			
				
				