<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProjectCreateRequest;
use App\Http\Requests\ProjectUpdateRequest;
use App\Models\Client;
use App\Models\Project;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    private function createOrEdit(Project $project)
    {
        $statuses = __('enums.project_status');
        $clients = Client::all()->pluck('name', 'id');
        $projects = collect(['' => '無'])->union(Project::all()->pluck('title', 'id'));
        return view('project.edit', ['project' => $project, 'projectStatuses' => $statuses, 'clients' => $clients, 'projects' => $projects]);
    }

    public function index(Request $request)
    {
        $builder = Project::orderBy('id', 'DESC');
        $search = $request->input('s');
        $projectStatus = $request->input('project_status', '');
        if($search) {
            $builder->where('title', 'LIKE', "%{$search}%");
        }
        if($projectStatus != '') {
            $builder->where('status', $projectStatus);
        }
        $clientId = $request->input('client_id');
        if($clientId) {
            $builder->where('client_id', $clientId);
        }
        $projects = $builder->get();
        $statuses = collect(['' => '所有狀態'])->union(__('enums.project_status'));
        return view('project.index', ['projects' => $projects, 'statuses' => $statuses]);
    }

    public function create()
    {
        $project = new Project();
        return $this->createOrEdit($project);
    }

    public function store(ProjectCreateRequest $request)
    {
        $validated = $request->validated();
        if(!$validated) {
            return redirect()->back()->withInput()->withErrors($request->messages());
        }
        $project = Project::create($request->all());
        return redirect()->route('adm.project.edit', ['project' => $project->id]);
    }

    public function show($id)
    {
        $project = Project::find($id);
        $notes = $project->notes()->latest()->get();
        return view('project.view', ['project' => $project, 'notes' => $notes]);
    }

    public function edit($id)
    {
        $project = Project::find($id);
        return $this->createOrEdit($project);
    }

    public function update(ProjectUpdateRequest $request, $id)
    {
        $validated = $request->validated();
        if(!$validated) {
            return redirect()->back()->withInput()->withErrors($request->messages());
        }
        $project = Project::find($id);
        $project->fill($request->all());
        $project->save();
        session()->flash('success_alert', 'Updated');
        return redirect()->route('adm.project.show', ['project' => $project->id]);
    }

    public function destroy($id)
    {
        //
    }
}
