<?php

namespace App\Console\Commands;

use App\Log;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class FetchData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch:data {date}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fetch Monthly Data';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('Starting task......');
        $argument = $this->argument('date');
        $date = null;
        if(empty($argument)){
            $this->error('You must specify the date!');
            exit(-1);
        };
        try {
            $date = Carbon::parse($argument);
        } catch (\Throwable $t) {
            $this->error('The date is invalid!');
            exit(-1);
        }

        $folder = storage_path('dataset');
        if(!file_exists($folder))
            mkdir($folder);

        $path = storage_path('dataset/'.$date->format('Y_m_d'));
        if(file_exists($path))
            @unlink($path);

        $this->info("Fetching data for $argument.......");

        for ($i=0; $i<30; $i++) {
            Excel::create($date->format('Y_m_d'), function ($excel) use ($date) {
                // Set the title
                $excel->setTitle('data');
                // Chain the setters
                $excel->setCreator('Alphonse')->setCompany('Npontu');
                $excel->setDescription('Deywuro Data');

                $excel->sheet('Sheet 1', function ($sheet) use ($date) {
                    $sheet->setOrientation('landscape');
                    $j = 1;
                    $headers = [
                        'Msisdn',
                        'Message'
                    ];
                    $sheet->appendRow(1, $headers);

                    $sheet->cells('A1:B1', function ($cells) {
                        $cells->setBackground('#333333');
                        $cells->setFontWeight('bold');
                        $cells->setFontColor('#ffffff');
                    });

                    $start_date = $date->copy();
                    $start_date->setTime(0, 0, 0);
                    $end_date = $start_date->copy()->addDay()->subSecond()->copy();

                    DB::table('logs')
                        ->where('message', 'LIKE', 'Your Acc %')
                        ->where('submit_date', '>=', $start_date->toDateTimeString())
                        ->where('submit_date', '<=', $end_date->toDateTimeString())
                        ->select(['message', 'msisdn'])
                        ->orderBy('submit_date')->chunk(500, function($jo) use (&$j, &$sheet) {
                            $this->info('Fetched '.count($jo).' record(s)');

                            foreach ($jo as $joo) {
                                try {
                                    $message = $joo->message;
                                    $msisdn = $joo->msisdn;
                                    $this->info('===> '.$message);

                                    $headers = [
                                        $msisdn,
                                        $message
                                    ];
                                    $sheet->appendRow(++$j, $headers);
                                } catch (\Throwable $t) {
                                    $this->error($t->getTraceAsString());
                                }
                            }
                        });
                });
            })->store('xls', $folder, true);
            $date->addDay();
        }

        $this->info('Task Complete!');
    }
}
