<?php

namespace App\Exports;

use DB;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Target;
use App\Models\Branch;
use App\Models\Fuletype;
use App\Models\Carmodel;
use App\Models\Teammaster;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;


class ExportTarget implements FromCollection, WithHeadings,WithStyles ,ShouldAutoSize{
    function __construct($slug) {
        $this->slug = $slug;
    }

    public function collection(){
        $collection = Target::select(
            DB::raw("DATE_FORMAT(target.date, '%Y-%m') as date"),
            'branches.name as branch',
            'target.target_type',
            'target.target_value',
            'car_model.name as model_name',
            'fule_type.title as fule_type',
            'Team_master.team_name as team_name',
            DB::raw("CONCAT(users.first_name, ' ', users.last_name) AS sales_person_name")
        )
        ->leftJoin('users', 'users.id', '=', 'target.kec_name')
        ->leftJoin('Team_master', 'Team_master.id', '=', 'target.team_id')
        ->leftJoin('car_model', 'target.model', '=', 'car_model.id')
        ->leftJoin('branches', 'branches.id', '=', 'target.branch')
        ->leftJoin('fule_type', 'fule_type.id', '=', 'target.fuel_type')
        ->groupBy('target.id')
        ->orderBy('target.id', 'desc');
        
        $data = $collection->get();
        
        if($data == null){
            throw new \ErrorException('No data found');
        }else{
            return $data;
        }
    }

    public function headings() :array{
        return ['Date','Branch','Target Type','Target Value','Model','Fuel Type','Team Name','KEC Name'];
    }

    public function styles(Worksheet $sheet){
        return [1 => ['font' => ['bold' => true]]];
    }
}