<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\RequestMaterial;
use App\Models\Activity;
use Carbon\Carbon;

class AssignMaterial extends Model
{
    protected $table = 'assign_material_to_activity';

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    protected $fillable = [
        'proyek_id', 'activity_id', 'material_id', 'qty_planning', 'budget', 'plan_date','created_at', 'created_by', 'updated_at', 'updated_by'
	];

	protected $casts = [
        'id' => 'integer',
        'budget' => 'string',
    ];

	public static function boot() {
		parent::boot();

		static::created(function($data) {
			$activity = Activity::find($data->activity_id);
			$material = RequestMaterial::where("id", $data->material_id)->first();
			$old = $activity->rencana_biaya;
			$activity->rencana_biaya += floatval($material->price) * floatval($data->qty_planning);
			$activity->save();

			$msg = Carbon::now()->toDateTimeString() . ": ".$activity->id." ".$activity->name.PHP_EOL;
			$msg .= "Added: ".$material->desc." (".floatval($material->price)." * ".floatval($data->qty_planning)."), Cost plan old: ".$old." | +".$activity->rencana_biaya.PHP_EOL;
			$msg .= "Data type (".gettype(floatval($material->price))." * ".gettype(floatval($material->qty_planning))."), ".gettype(floatval($old))." | ".gettype(floatval($activity->rencana_biaya)).PHP_EOL;
			$msg .= "Data type origin (".gettype($material->price)." * ".gettype($material->qty_planning)."), ".gettype($old)." | ".gettype($activity->rencana_biaya).PHP_EOL;
			$msg .= "------".PHP_EOL;
			file_put_contents('activity_log.txt', $msg, FILE_APPEND | LOCK_EX);

		});

		static::deleted(function($data) {
			$activity = Activity::where('id', $data->activity_id)->first();
			$old = $activity->rencana_biaya;
			$activity->rencana_biaya -= floatval($data->budget) * floatval($data->qty_planning);
			$activity->save();
			$material = RequestMaterial::where("id", $data->material_id)->first();

			$msg = Carbon::now()->toDateTimeString() . ": ".$activity->id." ".$activity->name.PHP_EOL;
			$msg .= "Deleted: ".$material->desc." (".floatval($data->budget)." * ".floatval($data->qty_planning)."), Cost plan old: ".$old." | -".$activity->rencana_biaya.PHP_EOL;
			$msg .= "Data type (".gettype(floatval($data->budget))." * ".gettype(floatval($data->qty_planning))."), ".gettype(floatval($old))." | ".gettype(floatval($activity->rencana_biaya)).PHP_EOL;
			$msg .= "Data type origin (".gettype($data->budget)." * ".gettype($data->qty_planning)."), ".gettype($old)." | ".gettype($activity->rencana_biaya).PHP_EOL;
			$msg .= "------".PHP_EOL;
			file_put_contents('activity_log.txt', $msg, FILE_APPEND | LOCK_EX);
		});

	}
}