<?php
/**
 * Created by PhpStorm.
 * User: Omair Saleh
 * Date: 20/9/2022
 * Time: 12:20 AM
 */

namespace App\Classes\Modules\Exports\Sheets;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Container;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;


class ContainersSheet implements WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize, FromQuery, WithTitle
{

    use Exportable;

    public function headings(): array
    {
        return [
            'Container No.',
            'Loaded Date',
            'ETD',
            'ETA',
            'Delay',
            'Unstuffing date',
            'Status',
            'CTN',
            'CBM'
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        return Container::query();
    }

    /**
     * @param $container
     * @return array
     */
    public function map($container): array
    {

        $transport = $container->transports()->first();
        $currentSchedule = $transport ? $transport->schedules()->where('status', '!=', ApprovalStatus::EXPIRED)->first() : null;
        $scheduleHistory = $transport ? $transport->schedules()->where('status', ApprovalStatus::EXPIRED)->get() : null;

        $status = 'Loaded';

        if($currentSchedule) {
            if(Carbon::parse($currentSchedule->etd) >= Carbon::today()){
                $status = 'Shipping';
            }

            if(Carbon::parse($currentSchedule->eta) >= Carbon::today()){
                $status = 'Arrived?';
            }

            if($transport->drop_date){
                $status = 'Pending deliveries';
                if(!$container->packinglists()->whereDoesntHave('transports')->get()){
                    $status = 'Complete';
                }
            }


        }

        return [
            $container->reference,
            $container->loading_date,
            $currentSchedule ? $currentSchedule->etd : null,
            $currentSchedule ? $currentSchedule->eta : null,
            $scheduleHistory ? count($scheduleHistory) : 0,
            $transport ? $transport->drop_date : null,
            $status,
            $container->packages()->sum('quantity'),
            $container->packages()->sum(DB::raw('(width/100) * (height/100) * (length/100) * quantity')),

        ];
    }

    /**
     * @return string
     */
    public function title(): string
    {
        return 'Containers';
    }
}