<?php
//sleep(4);
require_once("../../epconfig/TaquaLB/Ajax/CGI/PHP/config.php");
require("../../epconfig/GenScript/PHP/getinfo.php");
/*$rtn = array('enablednum'=>30,'enabledbody'=>'<tr>
<td>1</td><td>35363673773</td><td>47474747</td><td>SCHOOL FEE DB</td>
</tr>','failednum'=>10,'failedbody'=>'<tr>
<td>1</td><td>35363673773</td><td>47474747</td><td>SCHOOL FEE DB</td><td>Testing</td>
</tr>');*/

function Success($Title,$Code,$CH){
  global $rtn;
  $rtn['migratednum'] += 1;
  $rtn['migratedbody'] .= '<tr>
  <td>'.$rtn['migratednum'].'</td><td>'.$Title.'</td><td>'.$Code.'</td><td>'.$CH.'</td></tr>';
}

function Failed($failed,$Title="",$Code=""){
    global $rtn;
    $rtn['fmigratednum'] += 1;
    $rtn['fmigratedbody'] .= '<tr>
    <td>'.$rtn['fmigratednum'].'</td><td>'.$Title.'</td><td>'.$Code.'</td><td>'.$failed.'</td>
    </tr>'; 
}
$rtn = array('migratednum'=>0,'migratedbody'=>'','fmigratednum'=>0,'fmigratedbody'=>'','migratedfrom'=>'','migratedto'=>'');

//get the from and to progID frompID="+escape(frompID)+"&topID="+escape(topID)
extract($_POST);
//get the from programme details
$fromdet = $dbo->SelectFirstRow("programme_tb","","ProgID=".$frompID);
if(is_array($fromdet)){
  $rtn['migratedfrom'] = $fromdet['ProgName'];
  //get the to programme details
  $todet = $dbo->SelectFirstRow("programme_tb","","ProgID=".$topID);
  if(is_array($todet)){
    $rtn['migratedto'] = $todet['ProgName'];
  //get all from courses
    $fromcourses = $dbo->Select("course_tb","","DeptID=".$frompID);
    if(is_array($fromcourses)){
       if($fromcourses[1] > 0){
          //loop through all the from couse and insert in new
          while($frmcourse = $fromcourses[0]->fetch_array(MYSQLI_ASSOC)){
            
             //check if already exist
             $courseExist = $dbo->SelectFirstRow("course_tb","","DeptID=".$topID." AND CourseCode LIKE '".$frmcourse['CourseCode']."'");
             if(is_array($courseExist)){
              Failed("Already Exist",$frmcourse['Title'],$frmcourse['CourseCode']);
             }else{
              $frmcourse['CourseID'] = 0;
              $frmcourse['DeptID'] = $todet['ProgID'];
              $inst = $dbo->Insert("course_tb",$frmcourse);
              if($inst == "#"){
                Success($frmcourse['Title'],$frmcourse['CourseCode'],$frmcourse['CH']);
              }else{
                Failed("Failed: ".$inst,$frmcourse['Title'],$frmcourse['CourseCode']);
              }
             }
          }
       }else{
        Failed("No From Courses Found","-","-");
       }
    }else{
      Failed("Error Loading From Courses","-","-");
    }

  }else{
    Failed("Destination Programme Details not Found","-","-");
  }
    
}else{
  Failed("Source Programme Details not Found","-","-");
}



exit(json_encode($rtn));

?>