<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Carbon\Carbon;

class SystemCalendarController extends Controller
{
    public $sources = [
        [
            'model'      => '\App\Models\ServiceComplaint',
            'date_field' => 'service_date',
            'field'      => 'complaint',
            'prefix'     => '',
            'suffix'     => '',
            'route'      => 'admin.service-complaints.edit',
        ],
        [
            'model'      => '\App\Models\AmcContract',
            'date_field' => 'amc_expiry_date',
            'field'      => 'amc_expiry_date',
            'prefix'     => 'Expires On',
            'suffix'     => '',
            'route'      => 'admin.amc-contracts.edit',
        ],
        [
            'model'      => '\App\Models\Asset',
            'date_field' => 'warranty_end_date',
            'field'      => 'serial_no',
            'prefix'     => 'Warrenty Expires On',
            'suffix'     => '',
            'route'      => 'admin.assets.edit',
        ],
    ];

    public function index()
    {
        $events = [];
        foreach ($this->sources as $source) {
            foreach ($source['model']::all() as $model) {
                $crudFieldValue = $model->getAttributes()[$source['date_field']];

                if (! $crudFieldValue) {
                    continue;
                }

                $events[] = [
                    'title' => trim($source['prefix'] . ' ' . $model->{$source['field']} . ' ' . $source['suffix']),
                    'start' => $crudFieldValue,
                    'url'   => route($source['route'], $model->id),
                ];
            }
        }

        return view('admin.calendar.calendar', compact('events'));
    }
}
