<?php

namespace App\Repositories;

use App\Models\Project;

class ProjectRepository
{
    public static function fetchLatestItems()
    {
        return Project::orderBy('id', 'desc')->select(['title', 'media', 'slug'])->limit(8)->get();
    }

    public static function fetchAllItems()
    {
        return Project::orderBy('id', 'desc')->get();
    }

    public static function fetchItems($filters)
    {
        return Project::orderBy('id', 'desc')->simplePaginate(20);
    }

    public static function fetchProject($filters)
    {
        return Project::where('id', $filters['id'])->first();
    }

    public static function fetchProjectBySlug($slug)
    {
        return Project::where('slug', $slug)->first();
    }

    public static function saveProject($payload)
    {

        $project = new Project();
        if (isset($payload['id'])) {
            $project = self::fetchProject(['id' => $payload['id']]);
        }
        $project->title = $payload['title'];
        $project->client = $payload['client'];
        $project->start_date = $payload['start_date'];
        $project->end_date = $payload['end_date'];
        if (isset($payload['media']) && $payload['media']) {
            $project->media = $payload['media'];
        }
        $project->slug = $payload['slug'];
        $project->price = $payload['price'];
        $project->description = $payload['description'];

        return $project->save();
    }

    public static function deleteProject($filters)
    {
        $project = self::fetchProject(['id' => $filters['id']]);
        if ($project) {
            if ($project['media']) {
                $file_path = public_path('images').'/'.$project['media'];
                if (file_exists($file_path)) {
                    unlink($file_path);
                }
            }

            return Project::where('id', $filters['id'])->delete();
        }

        return false;
    }
}
