<?php

namespace App\Http\Controllers\Backend;

use App\Models\ProjectCategory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Project;
use App\Models\Company;

class ProjectController extends Controller
{
    public function index(Request $request)
    {
        $query = !empty($request->get('q')) ? $request->get('q') : null;
        $company = !empty($request->get('company')) ? $request->get('company') : null;
        $projectsQuery = Project::with(['category', 'company']);
        if($query) {
            $projectsQuery = $projectsQuery->search($query, null, true);
        }
        if($company) {
            $projectsQuery = $projectsQuery->where('company_id', $company);
        }
        $projects = $projectsQuery->paginate(20);
        $companies = Company::pluck('name', 'id');
        return view('backend.projects.index', compact('projects', 'companies'));
    }

    public function create()
    {
        $categories = ProjectCategory::pluck('name', 'id');
        $companies = Company::pluck('name', 'id');
        return view('backend.projects.create', compact('categories', 'companies'));
    }

    public function store(Request $request)
    {
        $project = Project::create($request->input());
        //$project->company_id = auth()->user()->company_id;
        $project->slug = str_slug($request->input('name'), '-');
        $project->save();

        return redirect()->route('backend.projects.show', $project->id );
    }

    public function show($id)
    {
        $project = Project::findOrFail($id);
        return view('backend.projects.show', compact('project'));
    }

    public function edit($id)
    {
        $categories = ProjectCategory::pluck('name', 'id');
        $companies = Company::pluck('name', 'id');
        $project = Project::findOrFail($id);
        return view('backend.projects.edit', compact('project', 'categories', 'companies'));
    }

    public function update(Request $request, $id)
    {
        $project = Project::findOrFail($id);
        $project->fill($request->input());
        $project->save();

        return redirect()->route('backend.projects.show', $project->id );
    }

    public function delete($id)
    {
        $project = Project::findOrFail($id);
        $project->delete();

        return redirect()->route('backend.projects.index');
    }
}
