<?php
session_start();

require_once '../Config/Database.php';
require_once '../Model/Course.php';
require_once '../Model/Program.php';
$course = new Course();
$program = new Program();

$courses = $course->read_all_courses();

if(isset($_GET['all_courses'])){
    echo json_encode(
        array("data"=>$courses)
    ); 
}

if(isset($_POST['add_course'])){
    $course_name = $_POST['course_name'];
    $program_name = $_POST['program_name'];
    $program_id = '';
    $program_detail = $program->get_program_by_name($program_name);
    if($program_detail){
        $program_id = $program_detail[0]['program_id'];
    }
    $data = array(
        "course_name"=>$course_name,
        "program_id"=>$program_id
    );
    
    $success = $course->add_course($data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

if(isset($_POST['update_course'])){
    $course_id = $_POST['course_id'];
    $course_name = $_POST['course_name'];
    $program_name = $_POST['program_name'];
    $program_id = '';
    $program_detail = $program->get_program_by_name($program_name);
    if($program_detail){
        $program_id = $program_detail[0]['program_id'];
    }
    $data = array(
        "course_name"=>$course_name,
        "program_id"=>$program_id
    );
    $key = array(
        "course_id"=>$course_id
    );
    $success = $course->update_course($key,$data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}


if(isset($_POST['remove_course'])){
    $course_id = $_POST['course_id'];
    $data = $course->remove_course($course_id);
    if(!$data){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}