@extends('layouts.master')

@section('navigation')
    @if (Auth::user()->role == 1)
        @include('local.managers.admins._new_navigation')
    @elseif(Auth::user()->role == 2)
        @include('local.managers.sCoords._new_navigation')
    @elseif(Auth::user()->role == 3)
        @include('local.managers.pCoords._new_navigation')
    @endif
@stop

@section('main')
    <div class="row">
        <div class="col-md-12">
            <div id="plan" data-plan-id="{{ $plan->id }}"></div>
            <div id="quinquennium" data-quinquennium-id="{{ $current_quinquennium->id }}"></div>
            <div id="program" data-program-id="{{ $program->id }}"></div>

            <div class="text-right">
                <button id="button-create-rubric" class="btn btn-primary save">
                    <span class="glyphicon glyphicon-floppy-disk"></span>
                    Save
                </button>
                <a href="{{ URL::action('FiveYearPlansController@show', ['program' => $program->id, 'plan' => $plan->id]) }}"
                    id="button-create-rubric" class="btn btn-primary">
                    <span class="glyphicon glyphicon-arrow-left"></span>
                    Back to Plan
                </a>
                <br><br>
            </div>

            @foreach ($plan->fypParts as $mini_plan)
                <div class="mini-plan">
                    <table class="table table-bordered">
                        <thead>
                            <tr class="bg-danger text-center">
                                <th class="text-center col-md-1">Academic Year</th>
                                <th class="text-center col-md-3">Learning Outcome to be assessed</th>
                                <th class="text-center col-md-4">Learning Objectives</th>
                                <th class="text-center col-md-4">Courses to use for assessment</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($mini_plan->fypPartOutcomes as $index => $fyp_outcome)
                                <tr>
                                    <!-- If outcome is the first, include multi-row year column -->
                                    @if ($index == 0)
                                        <th class="active academic-year text-center"
                                            rowspan="{{ count($mini_plan->fypPartOutcomes) }}">
                                            <span class="year-start">{{ $mini_plan->year_start }}</span>
                                            -<span class="year-end">{{ $mini_plan->year_end }}</span>
                                        </th>
                                    @endif

                                    <td class="outcome-cell">
                                        <select name="outcome" class="outcome form-control">
                                            @foreach ($outcomes as $outcome)
                                                @if ($fyp_outcome->outcome_id == $outcome->id)
                                                    <option selected value="{{ $outcome->id }}">{{ $outcome->name }}
                                                    </option>
                                                @else
                                                    <option value="{{ $outcome->id }}">{{ $outcome->name }}</option>
                                                @endif
                                            @endforeach
                                        </select>
                                    </td>
                                    <td class="objectives-cell">
                                        @foreach (json_decode($fyp_outcome->objectives) as $fyp_objective)
                                            <div class="objective-select-wrapper">
                                                <select name="objectives[]" class="objective shortened-select form-control">
                                                    @foreach (Objective::where('outcome_id', $fyp_outcome->outcome_id)->get() as $objective)
                                                        @if ($fyp_objective->original_id == $objective->id)
                                                            <option selected value="{{ $objective->id }}">
                                                                {{ $objective->text }}</option>
                                                        @else
                                                            <option value="{{ $objective->id }}">
                                                                {{ $objective->text }}</option>
                                                        @endif
                                                    @endforeach
                                                </select>
                                                <span
                                                    class="glyphicon glyphicon-remove text-danger icon-btn remove-objective"></span>
                                                <br><br>
                                            </div>
                                        @endforeach
                                        <button class="add-objective btn btn-success pull-right btn-xs"><span
                                                class="glyphicon glyphicon-plus"></span></button>
                                    </td>
                                    <td>
                                        @foreach (json_decode($fyp_outcome->courses) as $fyp_course)
                                            <div class="course-select-wrapper">
                                                <select name="courses[]" class="course shortened-select form-control">
                                                    @foreach ($courses as $course)
                                                        @if ($fyp_course->code == $course->code && $fyp_course->number == $course->number && $fyp_course->name == $course->name)
                                                            <option selected value="{{ $course->id }}"
                                                                data-course-code="{{ $course->code }}"
                                                                data-course-number="{{ $course->number }}"
                                                                data-course-name="{{ $course->name }}">
                                                                {{ $course->code }}{{ $course->number }}:
                                                                {{ $course->name }}</option>
                                                        @else
                                                            <option value="{{ $course->id }}"
                                                                data-course-code="{{ $course->code }}"
                                                                data-course-number="{{ $course->number }}"
                                                                data-course-name="{{ $course->name }}">
                                                                {{ $course->code }}{{ $course->number }}:
                                                                {{ $course->name }}</option>
                                                        @endif
                                                    @endforeach
                                                </select>
                                                <span
                                                    class="glyphicon glyphicon-remove text-danger icon-btn remove-course"></span>
                                                <br><br>
                                            </div>
                                        @endforeach
                                        <button class="add-course btn btn-success pull-right btn-xs"><span
                                                class="glyphicon glyphicon-plus"></span></button>
                                    </td>
                                    <td>
                                        @if ($index != 0)
                                            <span
                                                class="glyphicon glyphicon-remove text-danger icon-btn remove-outcome"></span>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                    <div>
                        <button class="add-outcome btn btn-success pull-right btn-sm"><span
                                class="glyphicon glyphicon-plus"></span>Add Learning Outcome</button>
                        <br><br><br>
                    </div>
                </div>
            @endforeach

            <div class="text-right">
                <button id="button-create-rubric" class="btn btn-primary save">
                    <span class="glyphicon glyphicon-floppy-disk"></span>
                    Save
                </button>
                <a href="{{ URL::action('FiveYearPlansController@show', ['program' => $program->id, 'plan' => $plan->id]) }}"
                    id="button-create-rubric" class="btn btn-primary">
                    <span class="glyphicon glyphicon-arrow-left"></span>
                    Back to Plan
                </a>
                <br><br>
            </div>
        </div>
    </div>

@stop

@section('included-js')

@stop

@section('javascript')

    // --------------------------------------------------------------------------
    // Page Load
    // --------------------------------------------------------------------------

    // Hide 'x' buttons for courses and objectives that are alone
    $('.objective-select-wrapper:only-of-type, .course-select-wrapper:only-of-type')
    .find('.remove-course, .remove-objective')
    .hide();



    // --------------------------------------------------------------------------
    // Events
    // --------------------------------------------------------------------------

    // On clicking a button to add outcome
    $('.add-outcome').on('click', function(e)
    {
    var table = $(this).closest('.mini-plan').find('table');
    addOutcome(table);
    });

    // On clicking a button to remove a course
    $('table').on('click', '.remove-objective', function(e)
    {
    removeObjective($(this));
    });

    // On clicking a button to remove a course
    $('table').on('click', '.remove-course', function(e)
    {
    removeCourse($(this));
    });

    // On clicking the x to remove an outcome from the plan
    $('table').on('click', '.remove-outcome', function(e)
    {
    var table = $(this).closest('.mini-plan').find('table');
    var row = $(this).closest('tr');
    removeOutcome(table, row);
    });

    // On clicking a button to add a objective
    $('.add-objective').on('click', function(e)
    {
    var table = $(this).closest('.mini-plan').find('table');
    var objective_select_wrapper = $(this).parent().find('.objective-select-wrapper:last');
    var select = $(this).parent().find('select:last');
    var selected_objective_id = select.find(':selected').val();
    var clone = objective_select_wrapper.clone();
    clone.insertAfter(objective_select_wrapper);
    objective_select_wrapper.parent().find('.remove-objective').show();
    });

    // On clicking a button to add a course
    $('.add-course').on('click', function(e)
    {
    var table = $(this).closest('.mini-plan').find('table');
    var course_select_wrapper = $(this).parent().find('.course-select-wrapper:last');
    var select = $(this).parent().find('select:last');
    var selected_course_id = select.find(':selected').val();
    var clone = course_select_wrapper.clone();
    clone.insertAfter(course_select_wrapper);
    course_select_wrapper.parent().find('.remove-course').show();
    });

    // When user selects another outcome
    $('.outcome').on('change', function(e)
    {
    fetchObjectives($(this));
    });

    // Gather, structure and send data to server for saving
    $('.save').on('click', function(e)
    {
    var five_year_plan = new Object();
    five_year_plan.plan_id = $('#plan').data('plan-id');
    five_year_plan.quinquennium_id = $('#quinquennium').data('quinquennium-id');
    five_year_plan.program_id = $('#program').data('program-id');
    five_year_plan.mini_plans = new Array();

    $('.mini-plan').each(function(index){

    var mini_plan = new Object();

    mini_plan.year_start = $(this).find('.year-start').text();
    mini_plan.year_end = $(this).find('.year-end').text();

    // Array for outcome objects
    mini_plan.outcomes = new Array();

    $(this).find('.outcome').each(function(index){

    // Outcome object
    var outcome = new Object();

    outcome.id = $(this).find(':selected').val();
    outcome.objectives = new Array();
    outcome.courses = new Array();

    // Gather objective information
    $(this).closest('tr').find('.objective').each(function()
    {
    var objective = new Object();

    objective.original_id = $(this).find(':selected').val();
    objective.text = $(this).find(':selected').text();

    outcome.objectives.push(jQuery.extend({}, objective));

    objective = null;
    });

    // Gather course information
    $(this).closest('tr').find('.course').each(function()
    {
    var course = new Object();

    course.code = $(this).find(':selected').data('course-code');
    course.number = $(this).find(':selected').data('course-number');
    course.name = $(this).find(':selected').data('course-name');

    outcome.courses.push(jQuery.extend({}, course));
    course = null;
    });

    mini_plan.outcomes.push(jQuery.extend({}, outcome));
    outcome = null;

    });

    five_year_plan.mini_plans.push(jQuery.extend({}, mini_plan));
    mini_plan = null;
    });

    console.log(five_year_plan);

    $.post(
    "{{ URL::action('FiveYearPlansController@update', [$program->id]) }}",
    {
    five_year_plan: JSON.stringify(five_year_plan)
    },
    function(data)
    {
    console.log(data);
    var response = data;

    console.log('status: '+response.status);
    if(response.status == 'success')
    {
    console.log('success');
    window.location = response.redirect_url;
    }
    else
    {
    jsError(response.message);
    }
    },
    "json"
    )
    .fail( function(xhr, status, error) {

    console.log('fail:'+error);
    // Always scroll to the top
    $(this).scrollTop(0);
    $('html').animate({scrollTop:0}, 1);
    $('body').animate({scrollTop:0}, 1);

    jsError(error);

    // Show js error with default message
    $('#js-error-row').fadeIn('slow', function () {
    $(this).delay(3000).fadeOut('slow');
    });
    }
    );
    });

    // --------------------------------------------------------------------------
    // Functions
    // --------------------------------------------------------------------------

    // Removes a objective
    function removeObjective(button)
    {
    var objective_select_wrapper = button.parent();

    // If only one objective will remain, hide 'x' button
    if(objective_select_wrapper.siblings('.objective-select-wrapper').length == 1)
    {
    objective_select_wrapper.siblings('.objective-select-wrapper').find('.remove-objective').hide();
    }

    // Remove objective
    objective_select_wrapper.remove();
    }

    // Removes a course
    function removeCourse(button)
    {
    var course_select_wrapper = button.parent();

    // If only one course will remain, hide 'x' button
    if(course_select_wrapper.siblings('.course-select-wrapper').length == 1)
    {
    course_select_wrapper.siblings('.course-select-wrapper').find('.remove-course').hide();
    }

    // Remove course
    course_select_wrapper.remove();
    }


    // Checks whether a mini plan has outcomes
    function hasOutcomes(table)
    {
    if(table.find('.outcome-cell').length > 0)
    return true;
    else
    return false;
    }

    // Add an outcome to a mini (annual) plan
    function addOutcome(table)
    {
    var header_rowspan = Number(table.find('.academic-year').attr('rowspan'));

    var clone = table.find('tbody tr:first').clone(true, true);

    // Remove academic year
    clone.children(':first').remove();

    // Remove all objectives and course except the first ones
    clone.find('.objective-select-wrapper').not(':first').remove();
    clone.find('.course-select-wrapper').not(':first').remove();

    // Add removal button
    clone.children(':last').append('<span class="glyphicon glyphicon-remove text-danger icon-btn remove-outcome"></span>');

    if(hasOutcomes(table))
    {
    table.find('tbody').append(clone);

    table.find('.academic-year').attr('rowspan', header_rowspan+1);
    }
    }

    // Remove an Outcome
    function removeOutcome(table, row)
    {
    var header_rowspan = Number(table.find('.academic-year').attr('rowspan'));

    row.remove();
    table.find('.academic-year').attr('rowspan', header_rowspan-1);
    }

    // Fetch objectives associated to an outcome and program
    function fetchObjectives(outcome)
    {
    var outcome_id = outcome.find(':selected').val();
    var program_id = $('#program').data('program-id');

    $.post(
    "{{ URL::action('ObjectivesController@fetch') }}",
    {
    outcome_id: outcome_id,
    program_id: program_id,
    format: 'select'
    },
    function(data)
    {
    var select = outcome.closest('tr').find('.objective');
    if(data == '')
    {
    select.prop('disabled', true);
    select.empty().append('<option value="0"><span class="glyphicon glyphicon-remove"></span> None</option>');
    }
    else
    {
    select.prop('disabled', false);
    select.empty().append(data);
    }

    if(select.length > 1) {
    select.first().parent().siblings('.objective-select-wrapper').remove();
    }
    }
    );
    }

@stop
