<?php

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

function formatExcelDate(int $timestamp)
{
    $diff = intval($timestamp);
    $today=new Carbon('1900-01-01');
    $day = $today->addDays($diff-2);
    return $day->toDateString();
}

function diff($array1,$array2,string $identification,array $mapping,bool $intactDetached = false):array
{
    $changes = [
        'attached' => [], 'detached' => [], 'updated' => [],
    ];
    $map = [];
    foreach ($array2 as $item){
        if (is_array($item))$map[$item[$identification]] = $item;
        else $map[$item->$identification] = json_decode($item,true);
    }
    foreach ($array1 as $item){
        /** @var \stdClass|array|Model $item */
        if (!is_array($item) && !is_subclass_of($item,Model::class))$item = (array)$item;
        if (!isset($map[$item[$mapping[$identification]]])){
            $obj = [];
            foreach ($mapping as $column2=>$column1)$obj[$column2] = $item[$column1];
            $changes['attached'][] = $obj;continue;
        }
        $sign = false;
        $obj = [];
        foreach ($mapping as $column2=>$column1){
            $obj[$column2] = $item[$column1];
            if ($map[$item[$mapping[$identification]]][$column2] != $item[$column1])$sign = true;
        }
        if ($sign)$changes['updated'][] = $obj;
        unset($map[$item[$mapping[$identification]]]);
    }
    if ($map){
        if ($intactDetached){
            foreach ($map as $item){
                $obj = [];
                foreach ($mapping as $column2=>$column1)$obj[$column2] = $item[$column2];
                $changes['detached'][] = $obj;
            }
        }else $changes['detached'][] = array_keys($map);
    }
    return $changes;
}