<?php

class CriteriaController extends \BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function fetchCriterion()
    {
        return Criterion::find(Input::get('id'));
    }

    public function fetchCriterionWithTrashed()
    {
        return Criterion::withTrashed()->find(Input::get('id'));
    }


    public function isCriterionUnique($input, $existing_criterion = NULL)
    {
        // dd($input);
        Log::info('isCriterionUnique');

        if(Input::get('program_id')!=0)
            $program_id = $input['program_id'];
        else
            $program_id = NULL;

        $saved_criterion = Criterion::
            withTrashed()
            ->where('name', '=', $input['name'])
            ->where('outcome_id', '=', $input['outcome_id'])
            ->where('program_id', '=', $program_id)
            // ->where('description12', '=', $input['description12'])
            // ->where('description34', '=', $input['description34'])
            // ->where('description56', '=', $input['description56'])
            // ->where('description78', '=', $input['description78'])
            ->first();

    

        if($saved_criterion)
            return false;
        else
            return true;
    }

    private function cleanInput()
    {
        $clean_input = array();

        $clean_input['name'] = trim(preg_replace('/\t+/', '', Input::get('name')));


        $trimmed = trim(preg_replace('/\t+/', '', Input::get('subcriteria')));

        Log::info('trimmed 1 -->'.$trimmed.'<--');


        if($trimmed ==''){
            $trimmed = NULL;
        }
        else{
            $trimmed = json_encode(preg_split('/\r\n/', $trimmed));
        }

        Log::info('trimmed 2 -->'.$trimmed.'<--');


        $clean_input['subcriteria'] = $trimmed;
        $clean_input['outcome_id'] = trim(preg_replace('/\t+/', '', Input::get('outcome_id')));
        $clean_input['program_id'] = trim(preg_replace('/\t+/', '', Input::get('program_id')));
        $clean_input['description12'] = trim(preg_replace('/\t+/', '', Input::get('description12')));
        $clean_input['description34'] = trim(preg_replace('/\t+/', '', Input::get('description34')));
        $clean_input['description56'] = trim(preg_replace('/\t+/', '', Input::get('description56')));
        $clean_input['description78'] = trim(preg_replace('/\t+/', '', Input::get('description78')));
        $clean_input['copyright'] = trim(preg_replace('/\t+/', '', Input::get('copyright')));
        $clean_input['notes'] = trim(preg_replace('/\t+/', '', Input::get('notes')));

        return $clean_input;
    }

    private function makeValidator($clean_input)
    {
        /** Validation rules */
        return Validator::make(
            array(
                'name' => $clean_input['name'],
                'subcriteria' => $clean_input['subcriteria'],
                'outcome_id' => $clean_input['outcome_id'],
                'description12' => $clean_input['description12'],
                'description34' => $clean_input['description34'],
                'description56' => $clean_input['description56'],
                'description78' => $clean_input['description78'],
                'notes' => $clean_input['notes'],
                'copyright' => $clean_input['copyright'],
            ),
            array(
                'name' => 'required|string',
                'subcriteria' => 'string',
                'outcome_id' => 'required|numeric|integer',
                'description12' => 'required|string',
                'description34' => 'required|string',
                'description56' => 'required|string',
                'description78' => 'required|string',
                'notes' => 'string',
                'copyright' => 'string',
            ),
            array(
                'description12.required' => 'The Beginning (1-2) field is required.',
                'description34.required' => 'The In Progress (3-4) field is required.',
                'description56.required' => 'The Satisfactory (5-6) field is required.',
                'description78.required' => 'The Excellent (7-8) field is required.',
            )
        );
    }

    /**
     * Create a new criterion.
     *
     * @return Redirect Redirect back to form page
     */
    public function create()
    {
        $clean_input = $this->cleanInput();

        /** Validation rules */
        $validator = $this->makeValidator($clean_input);

        /** If validation fails */
        if ($validator->fails())
        {
            /** Prepare error message */
            $message = '<p>Error(s) creating a new Criterion:</p><ul>';

            foreach ($validator->messages()->all('<li>:message</li>') as $validationError)
            {
                $message.=$validationError;
            }

            $message.='</ul>';

            /** Send error message and old data */
            Session::flash('status', 'danger');
            Session::flash('message', $message);
            return Redirect::to('criteria')->withInput();
        }
        else
        {
            // Check criterion uniqueness
            if(!$this->isCriterionUnique($clean_input))
            {
                /** Send error message and old data */
                Session::flash('status', 'danger');
                Session::flash('message', 'This criterion is a duplicate of an already saved criterion because its name and associated program are the same.');
                return Redirect::to('criteria')->withInput();
            }

            /** Instantiate new criterion */
            $criterion = new Criterion;
            $criterion->name= $clean_input['name'];
            $criterion->subcriteria = $clean_input['subcriteria'];
            $criterion->outcome_id= $clean_input['outcome_id'];
            $criterion->description12 = $clean_input['description12'];
            $criterion->description34 = $clean_input['description34'];
            $criterion->description56 = $clean_input['description56'];
            $criterion->description78 = $clean_input['description78'];

            if(Input::get('copyright'))
                $criterion->copyright = $clean_input['copyright'];

            if(Input::get('notes'))
                $criterion->notes = $clean_input['notes'];

            // Set program
            if(Input::get('program_id')!=0)
                $criterion->program_id = $clean_input['program_id'];
            else
                $criterion->program_id = NULL;


            /** If criterion is saved, send success message */
            if($criterion->save())
            {
                Session::flash('status', 'success');
                Session::flash('message', 'Criterion created: "'.$criterion->name.'".');
                return Redirect::to('criteria')->withInput(Input::only('outcome_id'));
            }

            /** If saving fails, send error message and old data */
            else
            {
                Session::flash('status', 'danger');
                Session::flash('message', '<p>Error creating Criterion. Please try again later.</p>');
                return Redirect::to('learning-outcomes-criteria')->withInput();
            }
        }
    }

    public function edit()
    {
        $title = "Criteria";
        $outcomes = Outcome::orderBy('name', 'ASC')->get();
        $schools = School::orderBy('name', 'ASC')->get();
        $criteria = Criterion::withTrashed()->orderBy('name', 'ASC')->get();
        $programs = Program::orderBy('name', 'ASC')->get();

        return View::make('local.managers.admins.criteria', compact('title', 'outcomes', 'schools', 'criteria', 'programs'));
    }

    public function update()
    {
        $criterion = Criterion::withTrashed()->find(Input::get('id'));

        $clean_input = $this->cleanInput();

        /** Validation rules */
        $validator = $this->makeValidator($clean_input);

        /** If validation fails */
        if ($validator->fails())
        {
            /** Prepare error message */
            $message = 'Error(s) updating the Criterion: <ul>';

            foreach ($validator->messages()->all('<li>:message</li>') as $validationError)
            {
                $message.=$validationError;
            }

            $message.='</ul>';

            /** Send error message and old data */
            Session::flash('status', 'danger');
            Session::flash('message', $message);
            return Redirect::back()->withInput();
        }
        else
        {

            // // Check criterion uniqueness
            // if(!$this->isCriterionUnique($clean_input, $criterion))
            // {
            //     /** Send error message and old data */
            //     Session::flash('status', 'danger');
            //     Session::flash('message', 'This criterion is a duplicate of an already saved criterion because its name, assoaciated school or program, and progress indicators are the same.');
            //     return Redirect::to('criteria')->withInput();
            // }

            /** Set info */
            $criterion->name= $clean_input['name'];
            $criterion->subcriteria = $clean_input['subcriteria'];
            $criterion->outcome_id= $clean_input['outcome_id'];
            $criterion->description12 = $clean_input['description12'];
            $criterion->description34 = $clean_input['description34'];
            $criterion->description56 = $clean_input['description56'];
            $criterion->description78 = $clean_input['description78'];

            // Set program
            if(Input::get('program_id')!=0)
                $criterion->program_id = Input::get('program_id');
            else
                $criterion->program_id = NULL;

            // Set status
            if(Input::get('status')==0)
                $criterion->deleted_at = date('Y-m-d H:i:s');
            else
                $criterion->deleted_at = NULL;

            if(Input::get('copyright'))
                $criterion->copyright = $clean_input['copyright'];
            else
                $criterion->copyright=NULL;

            if(Input::get('notes'))
                $criterion->notes = $clean_input['notes'];
            else
                $criterion->notes=NULL;

            /** If criterion is updated, send success message */
            if($criterion->save())
            {
                Session::flash('status', 'success');
                Session::flash('message', 'Updated criterion: "'.$criterion->name.'"');
                return Redirect::back();
            }

            /** If saving fails, send error message and old data */
            else
            {
                Session::flash('status', 'danger');
                Session::flash('message', 'Error updating the Criterion. Please try again later.');
                return Redirect::back()->withInput();
            }
        }
    }

    public function index()
    {
        // el ID de los semestres que el usuario tiene seleccionado.
        $semesters_ids = Session::get('semesters_ids');
        // buscar informacion de los semestres seleccionados
        $semesters = Semester::whereIn('id',$semesters_ids)->get();

        $title = "Learning Outcomes and Criteria";
        $outcomes = Outcome::orderBy('name', 'ASC')->get();
        $schools = School::orderBy('name', 'ASC')->get();
        $criteria = Criterion::withTrashed()->orderBy('name', 'ASC')->get();

        // se annadio la nueva variable
        return View::make('global.view-learning-outcomes-criteria', compact('title', 'outcomes', 'schools', 'criteria', 'semesters'));

    }

    // copie index() y lo edite
    public function objectivesIndex()
    {
        if(Auth::user()->role==1)
        {
          //uscar todos los objetivos
          $objectives = DB::table('program_user')
                                ->join('objectives','objectives.program_id','=','program_user.program_id')
                                ->join('programs','programs.id','=','program_user.program_id')
                                ->select('objectives.id','objectives.text','programs.name')
                                ->orderBy('objectives.text', 'asc')
                                ->get();
        }
        elseif(Auth::user()->role==2)
        {
          //buscar los objetivos de la departamento (school)
          $objectives = DB::table('program_user')
                                ->join('objectives','objectives.program_id','=','program_user.program_id')
                                ->join('programs','programs.id','=','program_user.program_id')
                                ->where('programs.school_id',Auth::user()->school_id)
                                ->select('objectives.id','objectives.text','programs.name')
                                ->orderBy('objectives.text', 'asc')
                                ->get();
        }
        elseif((Auth::user()->role==3) || (Auth::user()->role==4))
        {
          //buscar los objetivos de los programas cuales el profesor esta
          $objectives = DB::table('program_user')
                                ->join('objectives','objectives.program_id','=','program_user.program_id')
                                ->join('programs','programs.id','=','program_user.program_id')
                                ->where('program_user.user_id',Auth::user()->id)
                                ->select('objectives.id','objectives.text','programs.name')
                                ->orderBy('objectives.text', 'asc')
                                ->get();
        }

        $title = "Learning Objectives and Criteria";

        return View::make('global.view-objectives-criteria', compact('title', 'objectives'));
    }

    public function destroy()
    {
        $criterion = Criterion::withTrashed()->find(Input::get('id'));
        if(!$criterion->trashed())
        {
            try
            {
                $criterion->delete();
                Session::flash('status', 'success');
                Session::flash('message', 'Deactivated criterion: "'.$criterion->name.'"');
            }
            catch (Exception $e)
            {
                Session::flash('status', 'danger');
                Session::flash('message', 'Error deactivating criterion."'.$criterion->name.'"');
            }
            return Redirect::back();
        }
        else
        {
            try
            {
                $criterion->restore();
                Session::flash('status', 'success');
                Session::flash('message', 'Reactivated criterion: "'.$criterion->name.'"');
            }
            catch (Exception $e)
            {
                Session::flash('status', 'danger');
                Session::flash('message', 'Error reactivating criterion: "'.$criterion->name.'".');
            }
            return Redirect::back();

        }
    }

    public function filterCriteria()
    {
        switch (Input::get('filter'))
        {
            case 'all':
                return Criteria::all();
                break;

            case 'school':
                // If scoord
                if(Auth::user()->role == '2')
                {

                    // Fetch all the programs whose school is the user's
                    $program_ids = DB::table('programs')->where('school_id', Auth::user()->school_id)->lists('id');

                    // Return all criteria belonging to any of those programs
                    return Criterion::
                        whereIn('program_id', $program_ids)
                        ->orderBy('name', 'ASC')
                        ->get();
                }

                // If pcoord
                else
                {
                    // Fetch all the programs from the user's school;
                    $program_ids = DB::table('programs')->where('school_id', Auth::user()->programs[0]->school->id)->lists('id');

                    return Criterion::
                        whereIn('program_id', $program_ids)
                        ->orderBy('name', 'ASC')
                        ->get();
                }

                break;

            case 'program':
                return Criterion::
                    whereIn('program_id', Auth::user()->programs->lists('id'))
                    ->orderBy('name', 'ASC')
                    ->get();
                break;

            default:
                return Criteria::all();
                break;
        }
    }
}
