<?php
ini_set('memory_limit', '-1');
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
// ob_start();
// https://wpwebinfotech.com/blog/how-to-build-simple-rest-api-in-php/
require_once('config.php');
require_once('students.php');

// Create an instance of the student class
$studentObj = new Student($conn);

// Get request method
$method = $_SERVER['REQUEST_METHOD'];
// Get the requested emdpoint
$endpoint = $_SERVER['PATH_INFO'];
// Set the response content type
header('Content-Type: appliaction/json');
// Process the request
switch ($method){
    case 'GET':
        if($endpoint === '/students'){
            // Get all students
            $students = $studentObj->getAllStudents();
            echo json_encode($students);
        }elseif($endpoint === '/students_passport'){
            // Get all students
            $students = $studentObj->studentPassports();
            echo json_encode($students);
        }elseif(preg_match('/^\/students\/(\w+)$/', $endpoint, $matches)){
            // Get student by Id
            $studentId = $matches[1];
            $student = $studentObj->getStudentById($studentId);
            echo json_encode($student);
        }
        break;
    case 'POST':
        if($endpoint === '/students'){
            //Add new student
            $data = json_decode(file_get_contents('php://input'), true);
            $result = $studentObj->addStudent($data);
            // $data =[
            //     'emp_name' => 'Muhammad Kabir Abubakar',
            //     'emp_code' => 001,
            //     'emp_email'=> 'muhammadkabircs@gmail.com',
            //     'emp_phone'=> '07068704737',
            //     'emp_address' => 'Gombe',
            //     'emp_designation' => 'Director',
            //     'emp_joining_date' => '2024-01-01'
            // ];
            echo json_encode(['success' => $result]);
        }
        break;
    case 'PUT':
        if(preg_match('/^\/students\/(\d+)$/', $endpoint, $matches)){
            // Get student by Id
            $studentId = $matches[1];
            $data = json_decode(file_get_contents('php://input'), true);
            $student = $studentObj->updateStudent($studentId, $data);
            echo json_encode(['success' => $result]);
        }
        break;
    case 'DELETE':
        if(preg_match('/^\/students\/(\d+)$/', $endpoint, $matches)){
            // Get student by Id
            $studentId = $matches[1];
            $result = $studentObj->deleteStudentById($studentId);
            echo json_encode(['success' => $result]);
        }
        break;
}