<?php

namespace App\Listeners\Company;

use App\Events\Company\ApprovedTimesheetEvent;
use App\Models\ProjectDailyExpense;
use App\Models\ProjectWorkersTimesheet;
class CalculateProjectDailyExpenseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(ApprovedTimesheetEvent $event)
    {

        if ($event->transaction == "timesheet" && $event->action == "approve") 
        {
            $timesheet = ProjectWorkersTimesheet::select(
                'project_workers_timesheet.date',
                'project_workers_timesheet.rate',
                'project_workers_timesheet.total_hours',
                'project_workers_timesheet.total_billing_per_day',
                'project_workers_timesheet.worker_type',
                '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();
            
            $daily_expense = ProjectDailyExpense::where('date', $timesheet->date)
                ->where('project_id', $timesheet->project_id)
                ->first();

            $internal_expense = 0;
            $external_expense = 0;

            if ($timesheet->worker_type == 'inhouse') 
            {
                $internal_expense += ($timesheet->rate * $timesheet->total_hours);
            } 
            else 
            {
                $external_expense += $timesheet->total_billing_per_day;
            }

            if ($daily_expense) 
            {
                $success = ProjectDailyExpense::where('id', $daily_expense->id)
                    ->update(
                        [
                            'inhouse' => $daily_expense->inhouse + $internal_expense,
                            'external' => $daily_expense->external + $external_expense,
                        ]
                    );

            } 
            else 
            {
                $success = ProjectDailyExpense::create(
                    [
                        'date'       => $timesheet->date,
                        'project_id' => $timesheet->project_id,
                        'inhouse'    => $internal_expense,
                        'external'   => $external_expense,
                    ]
                );
            }
        }
    }
}
