<?php

namespace App\Services;

use App\Models\Team;
use App\Traits\ImageFunctions;

class TeamsService extends BaseServices
{
    use ImageFunctions;

    protected $model;

    public function __construct()
    {
        $this->model = new Team();
    }

    public function storeTeam($data)
    {
        return $this->model->create([
            'name_en' => $data->name_en,
            'name_ar' => $data->name_ar,
            'title_en' => $data->title_en,
            'title_ar' => $data->title_ar,
            'description_en' => $data->description_en,
            'description_ar' => $data->description_ar,
            'image' => $this->storeImagePath($data->image, 'teams'),
            'order' => $data->order,
            'links' => [
                'facebook' => $data->facebook,
                'twitter' => $data->twitter,
                'instagram' => $data->instagram,
                'linkedin' => $data->linkedin,
                'github' => $data->github,
            ]
        ]);
    }

    public function updateTeam(int $id, $data)
    {
        $team = $this->model->findOrFail($id);
        $team->name_en = $data->name_en;
        $team->name_ar = $data->name_ar;
        $team->title_en = $data->title_en;
        $team->title_ar = $data->title_ar;
        $team->description_en = $data->description_en;
        $team->description_ar = $data->description_ar;
        $team->order = $data->order;
        $team->links = [
            'facebook' => $data->facebook,
            'twitter' => $data->twitter,
            'instagram' => $data->instagram,
            'linkedin' => $data->linkedin,
            'github' => $data->github,
        ];

        if($data->image) {
            $team->image = $this->replaceImage($team->image, $data->image, 'teams');
        }

        if($team->isDirty()) {
            $team->save();
        }

        return $team;
    }

    public function deleteTeam($id)
    {
        $team = $this->model->findOrFail($id);
        $this->deleteIfExist($team->image);
        $team->delete();
    }
}
