<?php

class NewRequestController extends Nmc_Controller_Action
{

    public function __construct()
    {
        parent::__construct();
        $this->_registerPlugin(new Nmc_Controller_Action_Plugin_Authorize());
    }

    public function __destruct()
    {

    }

    public function indexAction()
    {
        return $this->SearchAction();
    }

    public function searchAction()
    {
        $in = $this->_action->getParams();
        if($in[0] != '' && $in[1] != '') {
            return $this->searchResultsAction();
        }

        $out = new Nmc_View();
        $out->page = 'request/search';
        $out->css_files[] = '/css/request/edit_wrapper.css';
        echo $out->render();
    }

    public function searchResultsAction()
    {
        $in = $this->_action->getParams();

        $subject = Zend_Filter::getAlpha($in[0]);
        $courseNumber = Zend_Filter::getDigits($in[1]);
        $courseLetter = Zend_Filter::getAlpha($in[2]);

        $course = CourseCrosslistings::fetchBySubjectNumberLetter($subject,
                                                                  $courseNumber,
                                                                  $courseLetter);

        $out = new Nmc_View();
        $out->subject = $subject;
        $out->courseNumber = $courseNumber;
        $out->courseLetter = $courseLetter;

        if(!$course) {
            // course not found
            $out->page = 'request/create_new_course_ask';
            Nmc_Registry_Session::getInstance()->erase('course');
        } else {
            // course found
            Nmc_Registry_Session::getInstance()->erase('course');
            $out->page = 'request/course_found';
            $parentCourse = $course->getParentCourse();

            $course = clone $parentCourse;

            Nmc_Registry_Session::getInstance()->course = $course;
        }
        echo $out->render();
    }

    public function createAction()
    {
        $in = $this->_action->getParams();

        $type = Zend_Filter::getAlnum($in[0]);
        $subject = Zend_Filter::getAlpha($in[1]);
        $courseNumber = Zend_Filter::getDigits($in[2]);
        $courseLetter = Zend_Filter::getAlpha($in[3]);

        $request = Requests::getInstance()->fetchNew();
        $request->owner = Nmc_User::getInstance()->getUser()->getId();
        $request->type = RequestTypes::getInstance()->stringToType($type);

        $course = Nmc_Registry_Session::getInstance()->course;
        if(!$course) {
            $course = CourseGenerations::getInstance()->fetchNew();
            $course->subject = $subject;
            $course->courseNumber = $courseNumber;
            $course->courseLetter = $courseLetter;
        }

        $course->request = $request;
        $course->type = 'proposed';

        //print_r($course);

        Nmc_Registry_Session::getInstance()->request = $request;
        Nmc_Registry_Session::getInstance()->course = $course;

        $out = new Nmc_View();
        $out->location = '/newrequest/CourseID';
        echo $out->render();
    }

    public function loadAction()
    {
        $in = $this->_action->getParams();

        $requestId = Zend_Filter::getInt($in[0]);
        $request = Requests::getInstance()->find($requestId);
        $course = $request->getCourseGeneration();

        Nmc_Registry_Session::getInstance()->course = $course;
        Nmc_Registry_Session::getInstance()->request = $request;

        $out = new Nmc_View();
        $out->location = '/NewRequest/CourseID';
        $out->render();
    }

    public function updateAction() {

        $errors = array();

        $course = Nmc_Registry_Session::getInstance()->course;
        $request = Nmc_Registry_Session::getInstance()->request;



        $submit = Zend_Filter::getAlpha($_POST['submit']);

        if(is_array($_POST['request'])) {
        foreach($_POST['request'] as $key => $val) {
            if(!is_array($val) && $val != '') {
                //echo '$request->' . $key . ' = ' . $val . "<br />\n";
                $request->$key = $val;
            }
        } }
        unset($_POST['request']);

        unset($_POST['submit']);
        unset($_POST['p_subject']);
        unset($_POST['p_course_number']);






        /*
        foreach($_POST as $key => $val) {
            if(!is_array($val) && $key != 'courseId' && $val != '') {
                //echo '$course->' . $key . ' = ' . $val . "<br />\n";
                $course->$key = $val;
            }
        }

        foreach($_POST as $key => $val) {
            if($key == 'credits') {
                foreach($course->credits as $key => $credit) {
                    unset($course->credits[$key]);
                }
                foreach($val as $type => $hours) {
                    if($type == 1) {
                        foreach(explode(' ', $hours) as $singeValue) {
                            if(Zend_Filter::getDigits($hours) != '') {
                                $newAttribute = CourseCredits::getInstance()->fetchNew();
                                $newAttribute->type = $type;
                                $newAttribute->hours = $singeValue;
                                $course->credits[] = $newAttribute;
                            }
                        }
                        continue;
                    }
                    if(Zend_Filter::getDigits($hours) != '') {
                        $newAttribute = CourseCredits::getInstance()->fetchNew();
                        $newAttribute->type = $type;
                        $newAttribute->hours = $hours;
                        $course->credits[] = $newAttribute;
                    }
                }
            } else if(in_array($key, array('termsOffered','deliveryMethods','campuses'))) {
                $course->$key = $val;
            } else if($key == 'gradTieIn') {
                if(!$course->gradTieIn instanceof CourseGradTieIn) {
                    $course->gradTieIn = CourseGradTieIns::getInstance()->fetchNew();
                }
                foreach($val as $key2 => $val2) {
                    $course->gradTieIn->$key2 = $val2;
                }
            } else if(is_array($val)) {
                $array = $course->$key;
                foreach($val as $key2 => $val2) {
                    //either create or grab the current attribute
                    if($key2 < 0) {
                        $attributeTable = call_user_func(array('Course' . $key, 'getInstance'));
                        $currentAttribute = $attributeTable->fetchNew();
                        $array[] = $currentAttribute;
                    } else {
                        $currentAttribute = $array[$key2];
                    }
                    //delete it if marked for deletion, otherwise unset the delete field
                    if($val2['delete'] == 'yes') {
                        unset($array[$key2]);
                        continue;
                    } else {
                        unset($val2['delete']);
                    }

                    //loop over each attribute and set
                    foreach($val2 as $key3 => $val3) {
                        if($val3 == '') {
                            $val3 = null;
                        }
                        //echo '$course->' . $key . '[' . $key2 . ']->' . $key3 . ' = ' . $val3 . "<br />\n";
                        $currentAttribute->$key3 = $val3;
                    }
                    //save changes
                }
            }
        }
        */






        foreach($_POST as $key => $val) {
            if(!is_array($val) && $key != 'courseId' /*&& $val != ''*/) {
                //echo '$course->' . $key . ' = ' . $val . "<br />\n";
                $course->$key = $val;
            }
        }

        foreach($_POST as $key => $val) {
            if($key == 'credits') {
                $credits = $course->credits;
                foreach($credits as $key => $credit) {
                    unset($credits[$key]);
                }
                foreach($val as $type => $hours) {
                    if($type == 1) {
                        foreach(explode(' ', $hours) as $singeValue) {
                            if(Zend_Filter::getDigits($hours) != '') {
                                $newAttribute = CourseCredits::getInstance()->fetchNew();
                                $newAttribute->type = $type;
                                $newAttribute->hours = $singeValue;
                                $credits[] = $newAttribute;
                            }
                        }
                        continue;
                    }
                    if(Zend_Filter::getDigits($hours) != '') {
                        $newAttribute = CourseCredits::getInstance()->fetchNew();
                        $newAttribute->type = $type;
                        $newAttribute->hours = $hours;
                        $credits[] = $newAttribute;
                    }
                }
            } else if(in_array($key, array('termsOffered','deliveryMethods','campuses'))) {
                $course->$key = $val;
                //echo '$course->' . $key . ' = '; print_r($val); echo "<br />\n";
            } else if($key == 'gradTieIn') {
                if(!$course->gradTieIn instanceof CourseGradTieIn) {
                    $course->gradTieIn = CourseGradTieIns::getInstance()->fetchNew();
                }
                foreach($val as $key2 => $val2) {
                    $course->gradTieIn->$key2 = $val2;
                }
            } else if(is_array($val)) {
                $array = $course->$key;
                foreach($array as $key2 => $row) {
                    unset($array[$key2]);
                }
                foreach($val as $key2 => $val2) {
                    if($val2['delete'] == 'yes') {
                        continue;
                    }
                    $attributeTable = call_user_func(array('Course' . $key, 'getInstance'));
                    $currentAttribute = $attributeTable->fetchNew();
                    unset($val2['delete']);

                    //loop over each attribute and set
                    foreach($val2 as $key3 => $val3) {
                        if($val3 == '') {
                            $val3 = null;
                        }
                        //echo '$currentAttribute->' . $key3 . ' = ' . $val3 . "<br />\n";
                        $currentAttribute->$key3 = $val3;
                    }
                    $array[] = $currentAttribute;
                    //save changes
                }
                //print_r($array);
            }
        }








        if(is_array($_FILES['request'])) {
            $newRequestFiles = array();
            foreach($_FILES['request'] as $fieldName => $values) {
                foreach($values as $key => $value) {
                    $newRequestFiles[$key][$fieldName] = $value;
                }
            }

            foreach($newRequestFiles as $key => $file) {
                if($file['error'] != 0) {
                    unset($newRequestFiles[$key]);
                    $errors[] = 'request[' . $key . ']';
                }
            }


            $fileTypes = array(RequestFile::CROSSLIST_MEMO_TYPE,
                               RequestFile::IS_NARRATIVE_TYPE,
                               RequestFile::SYLLABUS_TYPE);
            foreach($fileTypes as $fileType) {
                if(is_array($newRequestFiles[$fileType])) {
                    $inFile = $newRequestFiles[$fileType];
                    $file = RequestFiles::getInstance()->fetchNew();

                    $file->title = $inFile['name'];
                    $file->data = file_get_contents($inFile['tmp_name']);
                    $file->mimeType = $inFile['type'];

                    $request->setFileByType($fileType, $file);
                }
            }
        }

        if($submit == 'Submit') {
            return $this->_submitRequestAction();
        }

        $out = new Nmc_View();

        $requestFormOrder = array('CourseID',
                                  'CreditHours',
                                  'TimeLocation',
                                  'GraduateTieIn',
                                  'SupportiveMaterial',
                                  //'AdditionalInformation',
                                  'SubmitRequest');

        $currentForm = $_SERVER['HTTP_REFERER'];
        $currentForm = explode('/', $currentForm);
        while($currentForm[count($currentForm) - 1] == '') {
            array_pop($currentForm);
        }
        $currentForm = array_pop($currentForm);
        $currentForm = array_search(strtolower($currentForm),
                                    array_map("strtolower", $requestFormOrder));
        if($currentForm < count($requestFormOrder) - 1) {
            $nextForm = $requestFormOrder[$currentForm + 1];
        } else {
            $nextForm = $requestFormOrder[$currentForm];
        }
        if($currentForm > 0) {
            $prevForm = $requestFormOrder[$currentForm - 1];
        } else {
            $prevForm = $requestFormOrder[$currentForm];
        }

        if($submit == 'Prev') {
            $targetForm = $prevForm;
        } else {
            $targetForm = $nextForm;
        }

        $out->assign('refresh', '/NewRequest/' . $targetForm . '/');
        if(true || $_SERVER['REMOTE_ADDR'] != '129.93.39.17') {
            echo $out->render();
        } else {
            //print_r($course);
        }
    }

    public function saveAction() {
        try {
            $course = clone Nmc_Registry_Session::getInstance()->course;
            $course->save();
        } catch(Exception $e) {
            print_r($e);
            throw $e;
        }
    }

    public function courseIdAction()
    {
        $course = Nmc_Registry_Session::getInstance()->course;
        $out = new Nmc_View();

        $out->page = 'request/edit_wrapper';
        $out->requestPage = 'course_id';
        $out->css_files[] = '/css/request/course_id.css';
        $out->js_files[] = '/tinymce/jscripts/tiny_mce/tiny_mce.js';
        $out->js_files[] = '/javascript/mce.js';

        $out->course = $course;

        echo $out->render();
    }

    public function creditHoursAction()
    {
        $out = new Nmc_View();

        $out->page = 'request/edit_wrapper';
        $out->requestPage = 'credit_hours';
        $out->css_files[] = '/css/request/credit_hours.css';

        $course = Nmc_Registry_Session::getInstance()->course;
        $out->course = $course;

        $creditsSingleValues = array();
        foreach($course->credits as $credit) {
            if($credit->type == 1) {
                $creditsSingleValues[] = $credit->hours;
            } else if($credit->type == 2) {
                $out->creditsRangeMin = $credit->hours;
            } else if($credit->type == 3) {
                $out->creditsRangeMax = $credit->hours;
            } else if($credit->type == 4) {
                $out->creditsMaxPerSemester = $credit->hours;
            } else if($credit->type == 5) {
                $out->creditsMaxPerDegree = $credit->hours;
            }
        }
        $out->creditsSingleValues = implode(' ', $creditsSingleValues);

        echo $out->render();
    }

    public function timeLocationAction()
    {
        $out = new Nmc_View();

        $out->page = 'request/edit_wrapper';
        $out->requestPage = 'time_location';
        $out->css_files[] = '/css/request/time_location.css';

        $course = Nmc_Registry_Session::getInstance()->course;
        $out->course = $course;

        echo $out->render();
    }

    public function graduateTieInAction()
    {
        $out = new Nmc_View();

        $out->page = 'request/edit_wrapper';
        $out->requestPage = 'graduate_tie_in';
        $out->css_files[] = '/css/request/graduate_tie_in.css';
        $out->js_files[] = '/tinymce/jscripts/tiny_mce/tiny_mce.js';
        $out->js_files[] = '/javascript/mce.js';

        $course = Nmc_Registry_Session::getInstance()->course;

        $hasGradTieIn = false;
        foreach($course->crosslistings as $crosslisting) {
            if($crosslisting->type == 'grad tie-in') {
                $hasGradTieIn = true;
            }
        }

        $out->hasGradTieIn = $hasGradTieIn;
        $out->course = $course;

        echo $out->render();
    }

    public function supportiveMaterialAction()
    {
        $out = new Nmc_View();

        $out->page = 'request/edit_wrapper';
        $out->requestPage = 'supportive_material';
        $out->css_files[] = '/css/request/supportave_material.css';
        $out->js_files[] = '/tinymce/jscripts/tiny_mce/tiny_mce.js';
        $out->js_files[] = '/javascript/mce.js';

        $course = Nmc_Registry_Session::getInstance()->course;
        $out->course = $course;
        $request = Nmc_Registry_Session::getInstance()->request;
        $out->request = $request;

        echo $out->render();
    }

    public function additionalInformationAction()
    {
        $out = new Nmc_View();

        $out->page = 'request/edit_wrapper';
        $out->requestPage = 'additional_information';
        $out->css_files[] = '/css/request/additional_information.css';

        $course = Nmc_Registry_Session::getInstance()->course;
        $out->course = $course;

        echo $out->render();
    }

    public function submitRequestAction()
    {
        $course = Nmc_Registry_Session::getInstance()->course;
        $request = Nmc_Registry_Session::getInstance()->request;

        $out = new Nmc_View();
        $out->course = $course;
        $out->request = $request;
        $out->page = 'request/edit_wrapper';
        $out->requestPage = 'submit';
        $out->css_files[] = '/css/request/submit.css';

        echo $out->render();
    }

    protected function _submitRequestAction()
    {
        try {
            $course = Nmc_Registry_Session::getInstance()->course;

            $course->save();

            Nmc_Registry_Session::getInstance()->erase('course');
            Nmc_Registry_Session::getInstance()->erase('request');

            $out = new Nmc_View();
            $out->refresh = '/home';
            echo $out->render();
        } catch(Exception $e) {
            throw $e;
        }
    }
}

?>