<?php
/*
//20140108 - ADDED NEW ARTICLE SECTION SO THAT USER CAN ADD ARTICLES AS DOCS
//20140109 - UPDATED SAVE FUNCTION SO THAT USER CAN TAKE DOC FROM ARTICLES

NOTE UID = CourseCode + NOT + Obf = "ABCNOT123456"
 *

 */

include_once("_nemo.list.cls.php");

class DownloadableContent extends NemoList
{
   private $ID = 0;

   public function __construct($DataKey=null)
   {

      $this->Filters[frSearch]->tag = "input";
      $this->Filters[frSearch]->html->value = "";
      $this->Filters[frSearch]->html->type = "text";
      $this->Filters[frSearch]->html->class = "controlText";

      parent::__construct($DataKey);

      $this->isPageable =
      $this->isSortable = 0;
      $this->isSelectable = 1;
   }

   public function getList($strFilename)
   {
      global $SystemSettings;
      //print_rr($strFilename);
      $Where = "";

      if(!isset($strFilename))
      {
         if($this->Filters[frSearch]->html->value != "")
         {
            $like = "LIKE(". $this->db->qs("%".$this->Filters[frSearch]->html->value."%") .")";
            $Where .= " AND (modDownloadContent.UniqueID $like OR modDownloadContent.strFilename $like OR tblCourse.strCourse $like OR tblCourse.strCourseCode $like OR modModule.strModuleName $like )";
         }
      }
      else
      {
         $Where = " AND modDownloadContent.strFilename = '$strFilename'";
      }

      $strPathLearner = $SystemSettings[DownloadableContentDirLearner];
      // GET LIST
      $this->ListSQL("
         SELECT   modDownloadContent.DownloadID, 
                  tblCourse.strCourse AS Course,
                  tblCourse.strCourseCode AS Code,
                  modModule.strModuleName AS module,
                  'Note' AS Type,
                  modDownloadContent.strFilename AS Filename
         FROM modDownloadContent
            INNER JOIN modNote ON modNote.NoteID = modDownloadContent.UniqueID
            INNER JOIN modModule ON modNote.refModuleID = modModule.ModuleID
            LEFT JOIN tblCourse ON modModule.refCourseID = tblCourse.CourseID
         WHERE 1=1 $Where

         UNION ALL

         SELECT   modDownloadContent.DownloadID, 
                  tblCourse.strCourse AS Course,
                  tblCourse.strCourseCode AS Code,
                  modModule.strModuleName AS module,
                  'Practical' AS Type,
                  modDownloadContent.strFilename AS Filename
         FROM modDownloadContent
            INNER JOIN modPractical ON modPractical.PracticalID = modDownloadContent.UniqueID
            INNER JOIN modModule ON modPractical.refModuleID = modModule.ModuleID
            LEFT JOIN tblCourse ON modModule.refCourseID = tblCourse.CourseID
         WHERE 1=1 $Where

         UNION ALL

         SELECT   modDownloadContent.DownloadID, 
                  tblCourse.strCourse AS Course,
                  tblCourse.strCourseCode AS Code,
                  modModule.strModuleName AS module,
                  'Assignment' AS Type,
                  modDownloadContent.strFilename AS Filename
         FROM modDownloadContent
            INNER JOIN modAssignment ON modAssignment.AssignmentID = modDownloadContent.UniqueID
            INNER JOIN modModule ON modAssignment.refModuleID = modModule.ModuleID
            LEFT JOIN tblCourse ON modModule.refCourseID = tblCourse.CourseID
         WHERE 1=1 $Where

         ORDER BY DownloadID Asc", 0);

      return $this->renderTable("Downloadable Content Database");
   }

   public static function GetDCManager($UniqueID)
   {
      include_once("_nemo.details.cls.php");
      global $SystemSettings, $xdb;

      $DownloadableContent = new NemoDetails();
      $rowDC = $xdb->getRowSQL("SELECT * FROM modDownloadContent WHERE UniqueID = ". $xdb->qs($UniqueID));

      $DownloadableContent->AssimulateTable("modDownloadContent", $rowDC->DownloadID);
      $DownloadableContent->Fields["DownloadID"]->Control->type = "hidden";
      $DownloadableContent->Fields["fuDC"] = nCopy($DownloadableContent->Fields["strFilename"]);

      $DownloadableContent->Fields["strFilename"]->Control->readonly = "readonly";
      $DownloadableContent->Fields["strFilename"]->Control->class = "controlText controlLabel controlWide";
      if($rowDC)
         $DownloadableContent->Fields["strFilename"]->Control->comment = "<a href='". $SystemSettings[DownloadableContentDirAdmin] . $DownloadableContent->Fields["strFilename"]->VALUE ."' target=_blank >- Download / View -</a>";
      $DownloadableContent->Fields["strFilename"]->jsValidate = "";

      $DownloadableContent->Fields["fuDC"]->jsValidate = "";
      $DownloadableContent->Fields["fuDC"]->Label = "Upload New";
      $DownloadableContent->Fields["fuDC"]->Control->name = "fuDC";
      $DownloadableContent->Fields["fuDC"]->Control->type = "file";
      $DownloadableContent->Fields["fuDC"]->Control->comment = "<input type='checkbox' name='chkEnableArticles' id='chkEnableArticles' onClick='jsSearchArticles(this);' />- Select from Articles - ";
      unset($DownloadableContent->Fields["UniqueID"]); // clashes w modX.blnActive

      $DownloadableContent->renderControls();

      //20140108 - ADDED NEW ARTICLE SECTION SO THAT USER CAN ADD ARTICLES AS DOCS
      $articleSearch = "<div class='divPreview' style='width: 98%; display:none; padding:1% !important; ' id='divArticleSearch'>
                           <table width='100%' border='0' cellpadding='0' cellspacing='0'  style='margin: 0px;'>
                              <caption>Article Search</caption>
                              <tr>
                                 <td align=right width='100px'>Search: </td>
                                 <td><input type=text class='controlText' name='SearchArticle' id='SearchArticle' onkeyup='jsUpdateResults()' /></td>
                              </tr>
                              <tr>
                                 <td id='searchResults' colspan='2'></td>
                              </tr>
                           </table>
                           <input type='hidden' id='chosenArticle' name='chosenArticle' />
                        </div>

                        <script>

                        function jsCopyHTML()
                        {
                           test = 'asdasd';
                           window.clipboardData.setData('text',test )
                        }

                        function jsSearchArticles()
                        {  
                           if($('#chkEnableArticles').is(':checked'))
                           {
                              $('#divArticleSearch').show('fast');
                           }
                           else
                           {
                              $('#divArticleSearch').hide('fast');
                           }
                        }

                        function jsAddHyperlink(filename)
                        {
                           $('#chosenArticle').val(filename);
                           $('#strFilename').val(filename);
                           $('#divArticleSearch').hide('fast');
                        }

                        function jsUpdateResults()
                        {

                           strSearch = $('#SearchArticle').val();

                           if(strSearch == '')
                           {
                              $('#searchResults').empty();
                           }
                           else
                           {
                              $.ajax({
                                 type: 'POST',
                                 url: 'ajaxfunctions.php',
                                 data: 'header=text&type=SearchArticles&strSearch='+ strSearch,
                                 success: function(data)
                                 {
                                    $('#searchResults').empty();
                                    $('#searchResults').append(data);
                                 }
                              });
                           }

                        }
                        </script>";

      return $DownloadableContent->renderTable("Downloadable Content Manager") . $articleSearch;// no js val! . $DownloadableContent->getJsNemoValidateSave();
   }

   public static function Update()
   {
      global $SystemSettings;
//print_rr($_POST);
      if($_POST[chkEnableArticles] == "on")
      {
         foreach($_POST[chkSelect] as $key => $value)
         {
            $db = new NemoDatabase("modDownloadContent", $key, null, 0);
            $db->Fields["strFilename"] = $_POST[chosenArticle];

            $result = $db->Save();
            
            $message = "Content Updated. ";

         }
      }
      else if($_FILES['fuDC']['name'] != "")
      {
         foreach($_POST[chkSelect] as $key => $value)
         {
            $db = new NemoDatabase("modDownloadContent", $key, null, 0);

            $strOldFilename = $db->Fields["strFilename"];
            $db->Fields["strFilename"] =
            $strFileName = $db->Fields["UniqueID"] ."_". $_FILES["fuDC"]["name"];
            $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

            $strPath = $SystemSettings[DownloadableContentDirAdmin];

            chmod($_FILES['fuDC']['tmp_name'] , 0777);
            if(move_uploaded_file($_FILES['fuDC']['tmp_name'], $strPath . $strFileName))
            {
               if($strOldFilename != "" && $strOldFilename != $strFileName)
               {
                  unlink($strPath.$strOldFilename);
               }
                     
               $message = "Content Updated. ";
            }

            $result = $db->Save();

            
         }
         if($result->Error == 1)
               return $result->Message;
            else
               return $message;
      }
      else
      {
         $message = "No File Selected. ";
         return $message;
      }
   }

   //20140109 - UPDATED SAVE FUNCTION SO THAT USER CAN TAKE DOC FROM ARTICLES
   public static function Save($UniqueID)
   {
      global $SystemSettings;
 
      // CHECK TO SEE IF UNIQUE ID IS AVAILABLE
      if($UniqueID != "")
      {  
         // IF CHECKED TAKE DOC FROM ARTICLES ELSE SEE IF USER UPLOADED NEW DOC
         if($_POST[chkEnableArticles] == "on")
         {
            $db = new NemoDatabase("modDownloadContent", $DownloadID=0, null, 0);

            $db->Fields[UniqueID] = $UniqueID;
            $db->Fields["strFilename"] = $_POST[chosenArticle];
            $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;
            $db->doQuery("DELETE FROM modDownloadContent WHERE UniqueID = ". $db->qs($UniqueID));
            $result = $db->Save();

            if($result->Error == 1)
               return $result->Message;
            else
               return $message;
         }
         else
         {
            //IF USER UPLOADED NEW DOC
            if($_FILES['fuDC']['name'] != "")
            {

               $db = new NemoDatabase("modDownloadContent", $DownloadID=0, null, 0);
               $strOldFilename = $db->getRowSQL("SELECT * FROM modDownloadContent WHERE UniqueID = ". $db->qs($UniqueID))->strFilename;

               $db->Fields[UniqueID] = $UniqueID;
               $db->Fields["strFilename"] =
                  $strFileName = $UniqueID ."_". $_FILES["fuDC"]["name"];
               $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

               $strPath = $SystemSettings[DownloadableContentDirAdmin];

               chmod($_FILES['fuDC']['tmp_name'] , 0777);
               if(move_uploaded_file($_FILES['fuDC']['tmp_name'], $strPath . $strFileName))
               {
                  if($strOldFilename != "" && $strOldFilename != $strFileName)
                  {
                     unlink($strPath.$strOldFilename);
                  }
                     
                  $message = "New File Uploaded. ";
               }

               $db->doQuery("DELETE FROM modDownloadContent WHERE UniqueID = ". $db->qs($UniqueID));
               $result = $db->Save();

               if($result->Error == 1)
                  return $result->Message;
               else
                  return $message;

            }
         }
      }
   
      
      // if($_FILES['fuDC']['name'] != "" && $UniqueID != "")
      // {
      //    $db = new NemoDatabase("modDownloadContent", $DownloadID=0, null, 0);
      //    $strOldFilename = $db->getRowSQL("SELECT * FROM modDownloadContent WHERE UniqueID = ". $db->qs($UniqueID))->strFilename;

      //    $db->Fields[UniqueID] = $UniqueID;
      //    $db->Fields["strFilename"] =
      //       $strFileName = $UniqueID ."_". $_FILES["fuDC"]["name"];
      //    $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

      //    $strPath = $SystemSettings[DownloadableContentDirAdmin];
      //       //echo $strPath . $strFileName;
      //    chmod($_FILES['fuDC']['tmp_name'] , 0777);
      //    if(move_uploaded_file($_FILES['fuDC']['tmp_name'], $strPath . $strFileName))
      //    {
      //       if($strOldFilename != "" && $strOldFilename != $strFileName)
      //          unlink($strPath.$strOldFilename);
      //       $message = "New File Uploaded. ";
      //    }
      //    $db->doQuery("DELETE FROM modDownloadContent WHERE UniqueID = ". $db->qs($UniqueID));
      //    $result = $db->Save();

      //    if($result->Error == 1)
      //       return $result->Message;
      //    else
      //       return $message;
      // }

   }

}
?>
