<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use App\Models\Developer;
use App\Models\Team;
use App\Models\Project;
use App\Models\Agent;
use App\User;

use App\Helpers\DBFunctions;

use DB;
use Auth;
use JavaScript;

class ProjectController extends Controller
{
    public function index()
    {
        $prjs = Project::whereNull('deleted_at')->orderBy('id', 'DESC')->get();
        $devs = Developer::orderBy('name', 'asc')->get();;
        //dd($teams);
        return view('admin.projects.projects', compact('prjs', 'devs'));
    }

    public function getNewProject() {

    }

    public function postNewProject(Request $request)
    {
        /*dd($request->all());
        $this->validate($request, [
            'code' => 'required|unique',
            'name' => 'required|unique'
            //'full_name'=>'required',
            //'email'=>'required|email|unique:users',
            //'role'=>'required',
            //'password'=>'required|min:5'
        ]);*/

        try {

            DB::beginTransaction();

            $prj = new Project();
            $prj->code = strtoupper($request['code']);
            $prj->name = strtoupper($request['name']);
            $prj->developer_id = $request['developer_id'];
            $prj->active = "Yes";
            $prj->save();

            DB::commit();

            return redirect()->route('projects')->with('info', 'New Project was created.');

        } catch (\Exception $e) {

            DB::rollBack();
            return redirect()->route('projects')->with('info', $e->getMessage());
        }
    }

    public function postUpdateProject(Request $request) {

        $id = $request['id'];

        try {

            DB::beginTransaction();

            $this->validate($request, [
                'code'          => 'required',
                'name'          => 'required',
                'developer_id'  => 'required'
            ]);

            $prj   = Project::where('id', $id)->first();

            $prj->code         = strtoupper($request['code']);
            $prj->name         = strtoupper($request['name']);
            $prj->developer_id = $request['developer_id'];
            $prj->update();

            DB::commit();

            return redirect()->route('projects')->with('info', 'Project was successfully updated.');

        } catch (\Exception $e) {

            DB::rollBack();
            return redirect()->route('projects')->with('info', $e->getMessage());
            //"{{ route('teams.edit',[$id]) }}"
        }

    }

    public function postDeleteProject(Request $request){
        $id     = $request['id'];
        $team   = Project::where('id', $id)->first();

        $team->delete();

        return redirect()->back()->with('info', "The selected project have been deleted.");
    }

}