<?php
/**
 * Created by IntelliJ IDEA.
 * User: DennysO
 * Date: 6/3/2015
 * Time: 11:10 AM
 */
require_once "generic.php";

class Templates extends Generic
{
    protected $primaryKey = 'id';
    protected $table = 'emailtemplates';
    protected $fillable = ['id', 'title', 'subject', 'body', 'created', 'lastupdated'];

    function getEmailTemplatesInfo()
    {
        $table = $this->select('id', 'title', 'subject', 'body')
        ->orderBy('title')
        ->get();

        return $table;
    }

    public function deleteEmailTemplate($id)
    {
        $row = (new Users())->getById($id);
        $row->delete();
    }

    public function loadEmailTemplates()
    {
        $term = (new Terms())->getActiveTerm();
        $dataURL = $term->srprojecturl . "/getAll/" . $term->srprojecttoken;
        $auth = base64_encode('dennys_orozco@ultimatesoftware.com:Do82418963258633');
        $a = array(
            'http' => array(
                'proxy' => 'tcp://fl1wbsgw01-wcg.us.corp:8080',
                'request_fulluri' => true,
                'header' => "Proxy-Authorization: Basic $auth",
            ),
        );
        $c = stream_context_create($a);
        $data = file_get_contents($dataURL, False, $c);
        $data = json_decode($data);
        $added = 0;
        $modified = 0;
        $inactive = 0;
        foreach ($data as &$student) {
            $curStudent = $this->where('id', $student->id)
            ->where('termid', $term->id)
            ->first();

            $curProject = (new Projects())->where('id', $student->projectID)->first();
            $user = new Users();
            if ($curProject == null) {
                $newProject = new Projects();
                $newProject->id = $student->projectID;
                $newProject->name = $student->projectTitle;
                $newProject->save();
            } else {
                if ($student->projectTitle != $curProject->name) {
                    $curProject->name = $student->projectTitle;
                    $curProject->save();
                }
            }

            if ($curStudent == null) {
                $user->id = $student->id;
                $user->email = $student->email . "@fiu.edu";
                $user->fname = $student->firstName;
                $user->lname = $student->lastName;
                $user->termid = $term->id;
                $user->roleid = 1;
                $user->projectid = $student->projectID;
                $user->save();

                $added++;
            } else {
                $curStudent->email = $student->email . "@fiu.edu";
                $curStudent->fname = $student->firstName;
                $curStudent->lname = $student->lastName;
                $curStudent->termid = $term->id;
                $curStudent->roleid = 1;
                $curStudent->projectid = $student->projectID;
                $curStudent->save();

                $modified++;
            }
        }
        return '{"Added":"' . $added . '","Modified":"' . $modified . '","Dropped":"' . $inactive . '"}';
    }

    function obscureId($id)
    {
        return ($id * 155.2) * 10 + 9999;
    }

    function recoverId($id)
    {
        return (($id - 9999) / 10) / 155.2;
    }

    public function getEmailSubject($id, $templateId, $send = false, $email, $sentid)
    {
        if ($id != null) {
            $term = (new Terms())->getActiveTerm();
            $termId = $term->id;
            $obscuredId = ($id * 155.2) * 10 + 9999;

            $template = (new Templates())->getById($templateId);
            $tBody = $template->body;
            $tSubject = $template->subject;

            $user = (new Users())->getById($id);

            $projects = (new Projects())->where('termid', $termId)->orderBy("name")->get();
            $projectList = '<ul>';
            foreach ($projects as & $project) {
                $projectList .= "<li>" . $project->name . "</li>";
            }
            $projectList .= "</ul>";
            $questions = (new Questions())->orderBy("text")->get();
            $questiontList = "<ul>";
            foreach ($questions as & $question) {
                $questiontList .= "<li>" . $question->text . "</li>";
            }
            $questiontList .= "</ul>";
            $accept = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailInvite/' . obscureId($id) . '/'.$sentid.' ">Accept</a>';
            $decline = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailReject/' . obscureId($id) . '/'. $sentid.'">Decline</a>';
            $remove = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailRemove/' . obscureId($id) . '/'. $sentid.'">Remove</a>';
            $resetPass = '<a href="http://'.$_SERVER['SERVER_NAME'].'/forgotPass/' . obscureId($id) . '/'. $sentid.'">Reset Password</a>';
            //$deadline = ;
            $mjurl = '<a href="'.$term->liveurl.'" target="_blank">Mobile Judge Web site</a>';
            $mjdevurl = '<a href="'.$term->devurl.'" target="_blank">Mobile Judge Development Web site</a>';
            $NumberOfProjects = (new Projects())->where('termid', $term->id)->count();
            $NumberOfStudents = (new Users())->where('roleid', 1)->where('termid', $term->id)->count();
            $placeHolders = array(
                "email" => $user->email,
                "fname" => $user->fname,
                "lname" => $user->lname,
                "title" => $user->title,
                "affiliation" => $user->affiliation,
                "name" => $term->name,
                "studentsperjudge" => $term->studentsperjudge,
                "start" => date('F j, Y g:i a', strtotime($term->start)),
                "end" => date('F j, Y g:i a', strtotime($term->end)),
                "location" => $term->location,
                "mapimage" => $term->mapimage,
                "students" => '',
                "projects" => '',
                "questions" => '',
                "mjurl" => '',
                "mjdevurl" => '',
                "accept" => '',
                "decline" => '',
                "remove" => '',
                "resetPass" => '',
                "NumberOfStudents" => $NumberOfStudents,
                "NumberOfProjects" => $NumberOfProjects,
                "deadline" => date('F j, Y g:i a', strtotime($term->deadline))
            );

            foreach ($placeHolders as $key => $value) {
                //echo $key . "<br />";
                //echo $value . "<br />";
                //$tBody = str_ireplace("[[" . $key . "]]", $value, $tBody);
                $tSubject = str_ireplace("[[" . $key . "]]", $value, $tSubject);
            }
        } else {
            $term = (new Terms())->getActiveTerm();
            $termId = $term->id;
            $obscuredId = ($id * 155.2) * 10 + 9999;
            $id = null;
            $template = (new Templates())->getById($templateId);
            $tBody = $template->body;
            $tSubject = $template->subject;
            $projects = (new Projects())->orderBy("name")->get();
            $projectList = '<ul>';
            foreach ($projects as & $project) {
                $projectList .= "<li>" . $project->name . "</li>";
            }
            $projectList .= "</ul>";
            $questions = (new Questions())->orderBy("text")->get();
            $questiontList = "<ul>";
            foreach ($questions as & $question) {
                $questiontList .= "<li>" . $question->text . "</li>";
            }
            $questiontList .= "</ul>";
            $NumberOfProjects = (new Projects())->where('termid', $term->id)->count();
            $NumberOfStudents = (new Users())->where('roleid', 1)->where('termid', $term->id)->count();
            $accept = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailInvite/' . obscureId($id) . '/'.$sentid.' ">Accept</a>';
            $decline = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailReject/' . obscureId($id) . '/'. $sentid.'">Decline</a>';
            $remove = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailRemove/' . obscureId($id) . '/'. $sentid.'">Remove</a>';
            $resetPass = '<a href="http://'.$_SERVER['SERVER_NAME'].'/forgotPass/' . obscureId($id) . '/'. $sentid.'">Reset Password</a>';
            //$deadline = ;
            $mobilejudgesite = '<a href="'.$term->liveurl.'" target="_blank">Mobile Judge Web site</a>';
            $mobilejudgestagingsite = '<a href="'.$term->devurl.'" target="_blank">Mobile Judge Development Web site</a>';
            $placeHolders = array(
                "email" => '',
                "fname" => '',
                "lname" => '',
                "title" => '',
                "affiliation" => '',
                "name" => $term->name,
                "studentsperjudge" => $term->studentsperjudge,
                "start" => date('F j, Y g:i a', strtotime($term->start)),
                "end" => date('F j, Y g:i a', strtotime($term->end)),
                "location" => $term->location,
                "mapimage" => '',
                "projects" => '',
                "students" => '',
                "questions" => '',
                "mobilejudgesite" => '',
                "mobilejudgestagingsite" => '',
                "accept" => '',
                "decline" => '',
                "remove" => '',
                "resetPass" => '',
                "NumberOfStudents" => $NumberOfStudents,
                "NumberOfProjects" => $NumberOfProjects,
                "deadline" => date('F j, Y g:i a', strtotime($term->deadline))
            );


            foreach ($placeHolders as $key => $value) {
                //echo $key . "<br />";
                //echo $value . "<br />";
                //$tBody = str_ireplace("[[" . $key . "]]", $value, $tBody);
                $tSubject = str_ireplace("[[" . $key . "]]", $value, $tSubject);
            }
        }


        return $tSubject;
    }

    public function getEmailBody($id, $templateId, $send = false, $email, $sentid)
    {
        if ($id != null) {
            $term = (new Terms())->getActiveTerm();
            $termId = $term->id;
            $obscuredId = ($id * 155.2) * 10 + 9999;

            $template = (new Templates())->getById($templateId);
            $tBody = $template->body;
            $tSubject = $template->subject;

            $user = (new Users())->getById($id);

            $students = (new Users())->where('termid', $termId)->where('roleid', 1)->orderBy('lname')->orderBy('fname')->get();
            $studentsList = '<ol>';
            foreach ($students as & $student) {
                $studentsList .= "<li>".$student->lname.", ".$student->fname."</li>";
            }
            $studentsList .= "</ol>";

            $projects = (new Projects())->where('termid', $termId)->orderBy("name")->get();
            $projectList = '<ol>';
            foreach ($projects as & $project) {
                $projectList .= "<li>" . $project->name . "</li>";
            }
            $projectList .= "</ol>";
            $questions = (new Questions())->orderBy("text")->get();
            $questiontList = "<ol>";
            foreach ($questions as & $question) {
                $questiontList .= "<li>" . $question->text . "</li>";
            }
            $questiontList .= "</ol>";
            $accept = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailInvite/' . obscureId($id) . '/'.$sentid.' ">Accept</a>';
            $decline = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailReject/' . obscureId($id) . '/'. $sentid.'">Decline</a>';
            $remove = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailRemove/' . obscureId($id) . '/'. $sentid.'">Remove</a>';
            $resetPass = '<a href="http://'.$_SERVER['SERVER_NAME'].'/forgotPass/' . obscureId($id) . '/'. $sentid.'">Reset Password</a>';
            //$deadline = ;
            $mjurl = '<a href="'.$term->liveurl.'" target="_blank">Mobile Judge Web site</a>';
            $mjdevurl = '<a href="'.$term->devurl.'" target="_blank">Mobile Judge Development Web site</a>';
            $NumberOfProjects = (new Projects())->where('termid', $term->id)->count();
            $NumberOfStudents = (new Users())->where('roleid', 1)->where('termid', $term->id)->count();
            $placeHolders = array(
                "email" => $user->email,
                "fname" => $user->fname,
                "lname" => $user->lname,
                "title" => $user->title,
                "affiliation" => $user->affiliation,
                "name" => $term->name,
                "studentsperjudge" => $term->studentsperjudge,
                "start" => date('F j, Y g:i a', strtotime($term->start)),
                "end" => date('F j, Y g:i a', strtotime($term->end)),
                "location" => $term->location,
                "mapimage" => $term->mapimage,
                "projects" => $projectList,
                "students" => $studentsList,
                "questions" => $questiontList,
                "mjurl" => $mjurl,
                "mjdevurl" => $mjdevurl,
                "accept" => $accept,
                "decline" => $decline,
                "remove" => $remove,
                "resetPass" => $resetPass,
                "NumberOfStudents" => $NumberOfStudents,
                "NumberOfProjects" => $NumberOfProjects,
                "deadline" => date('F j, Y g:i a', strtotime($term->deadline))
            );

            if (strpos($tBody, "[[accept]]") != false && $send == true && ($user->roleid <= 3 || $user->roleid == 12)) {
                $user->roleid = 2;
                $user->statesid = 2;
                $user->termid = $term->id;
                $user->update();
            }

            foreach ($placeHolders as $key => $value) {
                //echo $key . "<br />";
                //echo $value . "<br />";
                $tBody = str_ireplace("[[" . $key . "]]", $value, $tBody);
                //$tSubject = str_ireplace("[[" . $key . "]]", $value, $tSubject);
            }
        } else {
            $term = (new Terms())->getActiveTerm();
            $termId = $term->id;
            $obscuredId = ($id * 155.2) * 10 + 9999;
            $id = null;
            $template = (new Templates())->getById($templateId);
            $tBody = $template->body;
            $tSubject = $template->subject;
            $projects = (new Projects())->orderBy("name")->get();
            $projectList = '<ol>';

            $students = (new Users())->where('termid', $termId)->where('roleid', 1)->orderBy('lname')->orderBy('fname')->get();
            $studentsList = '<ol>';
            foreach ($students as & $student) {
                $studentsList .= "<li>".$student->lname.", ".$student->fname."</li>";
            }
            $studentsList .= "</ol>";

            foreach ($projects as & $project) {
                $projectList .= "<li>" . $project->name . "</li>";
            }
            $projectList .= "</ol>";
            $questions = (new Questions())->orderBy("text")->get();
            $questiontList = "<ol>";
            foreach ($questions as & $question) {
                $questiontList .= "<li>" . $question->text . "</li>";
            }
            $questiontList .= "</ol>";
            if(strpos($tBody, "[[accept]]") != false && $send == true)
            {
                $user = new Users();
                $user->email = $email;
                $user->projectid = 0;
                $user->locationid = 1;
                $user->roleid = 2;
                $user->termid = (new Terms())->getActiveTerm()->id;
                $user->statesid =  2;
                $user->save();
                $id = $user->id;
            }
            $NumberOfProjects = (new Projects())->where('termid', $term->id)->count();
            $NumberOfStudents = (new Users())->where('roleid', 1)->where('termid', $term->id)->count();
            $accept = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailInvite/' . obscureId($id) . '/'.$sentid.' ">Accept</a>';
            $decline = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailReject/' . obscureId($id) . '/'. $sentid.'">Decline</a>';
            $remove = '<a href="http://'.$_SERVER['SERVER_NAME'].'/emailRemove/' . obscureId($id) . '/'. $sentid.'">Remove</a>';
            $resetPass = '<a href="http://'.$_SERVER['SERVER_NAME'].'/forgotPass/' . obscureId($id) . '/'. $sentid.'">Reset Password</a>';
            //$deadline = ;
            $mobilejudgesite = '<a href="'.$term->liveurl.'" target="_blank">Mobile Judge Web site</a>';
            $mobilejudgestagingsite = '<a href="'.$term->devurl.'" target="_blank">Mobile Judge Development Web site</a>';
            $placeHolders = array(
                "email" => '',
                "fname" => '',
                "lname" => '',
                "title" => '',
                "affiliation" => '',
                "name" => $term->name,
                "studentsperjudge" => $term->studentsperjudge,
                "start" => date('F j, Y g:i a', strtotime($term->start)),
                "end" => date('F j, Y g:i a', strtotime($term->end)),
                "location" => $term->location,
                "mapimage" => $term->mapimage,
                "projects" => $projectList,
                "students" => $studentsList,
                "questions" => $questiontList,
                "mobilejudgesite" => $mobilejudgesite,
                "mobilejudgestagingsite" => $mobilejudgestagingsite,
                "accept" => $accept,
                "decline" => $decline,
                "remove" => $remove,
                "resetPass" => $resetPass,
                "NumberOfStudents" => $NumberOfStudents,
                "NumberOfProjects" => $NumberOfProjects,
                "deadline" => date('F j, Y g:i a', strtotime($term->deadline))
            );


            foreach ($placeHolders as $key => $value) {
                //echo $key . "<br />";
                //echo $value . "<br />";
                $tBody = str_ireplace("[[" . $key . "]]", $value, $tBody);
                //$tSubject = str_ireplace("[[" . $key . "]]", $value, $tSubject);
            }
        }


        return $tBody;
    }
}