<?php declare(strict_types=1); namespace App\Domain\ArticleToProject\Services; use App\Models\Article; use App\Models\ArticleToProject; use App\Models\PaymentDistribution; use App\Models\Project; use App\Models\ProjectGroup; use Illuminate\Support\Facades\Log; class ArticleToProjectService { public function allProjects($id, $request) { $query = ProjectGroup::query() ->where('model_id', $id) ->whereHas('projects.articleProjectLinks', function ($query) { $query->whereNotNull('article_id'); }) ->with(['projects' => function ($query) { $query->whereHas('articleProjectLinks'); }]); if ($request->get('search')) { $search = mb_convert_case($request->get('search'), MB_CASE_LOWER); $query->where(function($q) use ($search) { $q->whereRaw('LOWER(name) LIKE ?', ["%{$search}%"]) ->orWhereHas('projects', function($q) use ($search) { $q->whereHas('articleProjectLinks', function($q) { $q->whereNotNull('article_id'); }) ->where(function($subQ) use ($search) { $subQ->whereRaw('LOWER(offer_number) LIKE ?', ["%{$search}%"]) ->orWhereRaw('LOWER(short_description) LIKE ?', ["%{$search}%"]); }); }); }); } return $query->get(); } public function index($projectId, $articleType) { return ArticleToProject::query() ->where('project_id', $projectId) ->with(['article' => function ($query) use ($articleType) { $query->where('article_type', $articleType); }]) ->whereHas('article', function ($query) use ($articleType) { $query->where('article_type', $articleType); }) ->get(); } public function create(array $data): bool { try { return (bool)ArticleToProject::query()->create($data); } catch (\Exception $e) { return false; } } public function update($articleId, $projectId, $amountLimit) { $item = ArticleToProject::query()->where(['article_id' => $articleId, 'project_id' => $projectId])->first(); Log::info('item' . json_encode($item)); return $item->update(['amount_limit' => $amountLimit]); } public function delete($articleId, $projectId, $newArticleId): bool { $article = Article::query()->with('paymentDistributions')->where('id', $articleId)->first(); if ($article) { $article->paymentDistributions ->where('project_id', $projectId) ->each(function (PaymentDistribution $pd) use ($newArticleId) { $pd->update([ 'article_id' => $newArticleId, ]); }); } return (bool)ArticleToProject::query()->where(['article_id' => $articleId, 'project_id' => $projectId])->delete(); } }