<?php

namespace App\Listeners\Company;

use App\Events\Company\ApprovedTimesheetEvent;
use App\Models\ProjectWorkersTimesheet;
use App\Models\TimesheetNotification;
use Carbon\Carbon;

use App\Events\Company\TimesheetEvent;


class ApprovedTimesheetListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(ApprovedTimesheetEvent $event)
    {
        $timesheet = ProjectWorkersTimesheet::select(
            'project_workers_timesheet.*',
            'assigned_workers.project_id'
        )
            ->join('assigned_workers', 'assigned_workers.id', 'project_workers_timesheet.project_worker_id')
            ->where('project_workers_timesheet.id', $event->reference_id)
            ->first();

        $approved_notification = [
            "project_id"   => $timesheet->project_id,
            "worker_id"    => $timesheet->worker_id,
            "timesheet_id" => $timesheet->id,
            "message"      => "Your timesheet for " . $timesheet->date . " have been approved by " . $timesheet->approved_by,
            "date"         => Carbon::now(),
            'is_read'      => false,
        ];

        $timesheet_notification = TimesheetNotification::create($approved_notification);

        event(new TimesheetEvent(['new_notif' => true, 'data' => $timesheet_notification, 'type' => 'timesheet']));
    }
}
