<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../resources/base_path_include.php';
require_once $base_path_to_learning_resources . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

// Decode JSON post data
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

$required_fields = [
    'api_signature',
    'function_type',
    'jwt_token'
];

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || empty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

if (!$jwt_validate) {
    errorreturn('Invalid JWT token.');
}

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

if($role == 'principal' or $role == 'teacher'){
    $institution_id = $jwt_validate->data->institution_id;
    $branch_id = $jwt_validate->data->branch_id;
}

if($role == 'admin' or $role == 'superadmin'){
      if(!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
         !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id'])
      ){
           errorreturn("All fields are required.");
      }else{
            $institution_id = $postdata['institution_id'];
            $branch_id = trim($postdata['branch_id']);
      }
}

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin','admin','teacher','principal'], null);

if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);

if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

// Only run if function_type is fetch_left_faculty
if ($postdata['function_type'] == "fetch_left_faculty") {

    try {
        $sql = "SELECT lt.id, lt.teacher_id, fi.name AS teacher_name, fi.userid, fi.role, 
                       lt.date_of_leaving, lt.reason, lt.remarks, lt.attachment, 
                       lt.marked_by, lt.marked_on
                FROM left_teachers lt
                JOIN faculty_info fi ON lt.teacher_id = fi.id
                WHERE lt.institution_id = ? AND lt.branch_id = ?
                ORDER BY lt.marked_on DESC";

        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$institution_id, $branch_id]);
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (!$data) {
            successreturn(['data' => [], 'successmsg' => "No left faculty found."]);
        } else {
            // Decode attachment JSON if exists
            foreach ($data as &$row) {
                if (!empty($row['attachment'])) {
                    $row['attachment'] = json_decode($row['attachment'], true);
                }
            }
            successreturn(['data' => $data, 'successmsg' => "Fetched left faculty successfully."]);
        }

    } catch (Exception $e) {
        errorreturn("Database error: " . $e->getMessage());
    }
}
