<?php

namespace App\Http\Controllers;

use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ProjectController extends Controller
{
    public function index(): view
    {
        $projects       = Project::latest()->paginate(5);

        return view('project/projects_list',[
            'projects'  => $projects
        ]);
    }

    public function create(): view
    {
        return view('project/project_form');
    }

    public function store(Request $request)
    {
        $request->validate([
            'project_code'  => 'required',
            'project_name'  => 'required',
            'status'        => 'required',
        ],[
            'project_code.required' => 'Kode proyek wajib diisi'
        ]);

        $project_code        = $request->project_code;
        $project_name        = $request->project_name;
        $description         = $request->description;
        $status              = $request->status;

        Project::create([
            'project_code'  => $project_code,
            'project_name'  => $project_name,
            'description'   => $description,
            'status'        => $status
        ]);

        return redirect('/project');
    }

    public function show($project_code): view
    {
        $data    = Project::where('project_code', $project_code)->firstOrFail();
        
        return view('project/project_detail', ['data' => $data]);
    }

    public function update($project_code, Request $request)
    {
        $request->validate([
            'project_code'  => 'required',
            'project_name'  => 'required',
            'status'        => 'required',
        ],[
            'project_code.required' => 'Kode proyek wajib diisi'
        ]);

        $project_name        = $request->project_name;
        $description         = $request->description;
        $status              = $request->status;

        Project::where('project_code', $project_code)->update([
            'project_name'  => $project_name,
            'description'   => $description,
            'status'        => $status
        ]);

        return redirect('/project');
    }

    public function destroy($project_code)
    {
        Project::where('project_code', $project_code)->delete();
        
        return response()->json([
            'success' => true,
            'message' => 'Project berhasil dihapus'
        ]);
    }
}
