File: /var/www/ivs.kaunokolegija.lt/laravel/app/Models/FutureActivityPlanning.php
<?php
namespace App\Models;
use Carbon\Carbon;
use DateTimeInterface;
use App\Traits\Auditable;
use Illuminate\Support\Str;
use Spatie\GoogleCalendar\Event;
use Spatie\MediaLibrary\HasMedia;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\InteractsWithMedia;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Google_Client;
use Google_Service_Calendar;
use Google_Service_Calendar_Event;
class FutureActivityPlanning extends Model implements HasMedia
{
use SoftDeletes, InteractsWithMedia, Auditable, HasFactory;
protected $appends = [
'attachments',
];
public $table = 'future_activity_plannings';
protected $dates = [
'activity_start',
'activity_end',
'created_at',
'updated_at',
'deleted_at',
];
protected $fillable = [
'social_partner_id',
'activity_start',
'activity_end',
'description',
'additional_info',
'accountable_id',
'created_at',
'updated_at',
'deleted_at',
];
public function syncToGoogleCalendar()
{
$user = auth()->user();
if (!$user || !$user->google_token) {
\Log::error('Google Calendar sync failed: User is not authenticated with Google.');
return;
}
// dd(['dateTime' => Carbon::parse($this->activity_start)->setTimezone('Europe/Vilnius')->toRfc3339String(),]);
// dd(Carbon::parse($this->activity_start)->setTimezone('Europe/Vilnius')->toRfc3339String(), $this->activity_end ? Carbon::parse($this->activity_end)->setTimezone('Europe/Vilnius')->toRfc3339String() : Carbon::parse($this->activity_start)->addHour()->setTimezone('Europe/Vilnius')->toRfc3339String());
try {
$client = new Google_Client();
$client->setAuthConfig(storage_path('app/google-oauth-client.json'));
$client->setAccessToken([
'access_token' => $user->google_token,
'refresh_token' => $user->google_refresh_token,
]);
if ($client->isAccessTokenExpired()) {
$newToken = $client->fetchAccessTokenWithRefreshToken($user->google_refresh_token);
if (isset($newToken['access_token'])) {
$user->update([
'google_token' => $newToken['access_token'],
'google_refresh_token' => $newToken['refresh_token'] ?? $user->google_refresh_token,
]);
}
}
$service = new Google_Service_Calendar($client);
$startDateTime = Carbon::parse($this->activity_start)->setTimezone('Europe/Vilnius')->toRfc3339String();
$endDateTime = $this->activity_end
? Carbon::parse($this->activity_end)->setTimezone('Europe/Vilnius')->toRfc3339String()
: Carbon::parse($this->activity_start)->addHour()->setTimezone('Europe/Vilnius')->toRfc3339String();
$event = new Google_Service_Calendar_Event([
'summary' => Str::limit(strip_tags($this->description), 100),
'start' => ['dateTime' => $startDateTime],
'end' => ['dateTime' => $endDateTime],
'attendees' => $this->sharing_withs->map(fn($user) => ['email' => $user->email])->toArray(),
]);
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
\Log::info('Creating Google Calendar Event:', [
'start' => Carbon::parse($this->start_date)->toRfc3339String(),
'end' => Carbon::parse($this->end_date)->toRfc3339String(),
'attendees' => $this->sharing_withs ?? []
]);
\Log::info('Sharing with users:', $this->sharing_withs->toArray());
} catch (\Exception $e) {
\Log::error('Google Calendar sync failed: ' . $e->getMessage());
}
}
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
public function registerMediaConversions(Media $media = null): void
{
$this->addMediaConversion('thumb')->fit('crop', 50, 50);
$this->addMediaConversion('preview')->fit('crop', 120, 120);
}
public function social_partner()
{
return $this->belongsTo(Company::class, 'social_partner_id');
}
public function getActivityStartAttribute($value)
{
return $value ? Carbon::createFromFormat('Y-m-d H:i:s', $value)->format(config('panel.date_format') . ' ' . config('panel.time_format')) : null;
}
public function setActivityStartAttribute($value)
{
$this->attributes['activity_start'] = $value ? Carbon::createFromFormat(config('panel.date_format') . ' ' . config('panel.time_format'), $value)->format('Y-m-d H:i:s') : null;
}
public function getActivityEndAttribute($value)
{
return $value ? Carbon::createFromFormat('Y-m-d H:i:s', $value)->format(config('panel.date_format') . ' ' . config('panel.time_format')) : null;
}
public function setActivityEndAttribute($value)
{
$this->attributes['activity_end'] = $value ? Carbon::createFromFormat(config('panel.date_format') . ' ' . config('panel.time_format'), $value)->format('Y-m-d H:i:s') : null;
}
public function accountable()
{
return $this->belongsTo(User::class, 'accountable_id');
}
public function sharing_withs()
{
return $this->belongsToMany(User::class);
}
public function getAttachmentsAttribute()
{
return $this->getMedia('attachments');
}
}