<?php
// Enable error display for debugging
ini_set('display_errors', 1);

// Include necessary files
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 . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

require_once $base_path_to_learning . 'admin_api/global_settings/print_settings/print_setting_function.php';

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

// Check if no data was received
checkIfNoPhpContentsReceive();

// Validate required fields
$requiredFields = ['branch_id', 'institution_id','class_id','section_id', 'selected_template','api_signature','function_type','jwt_token'];
foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
// Extract user details from JWT token
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

// Validate user access and get specific database name
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

// if(!is_array($postdata['student_id'])){
    
//     errorreturn("Student field is required.");
// }

$institution_id = trim($postdata['institution_id']);  
$branch_id = trim($postdata['branch_id']);
$class_id = trim($postdata['class_id']);
$section_id = trim($postdata['section_id']);
$student_id = $postdata['student_id'];
$selected_template = trim($postdata['selected_template']);
$data_printed = ($postdata['data_printed']); // jsonencode

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

$res = $conn_rjllearning_specific->prepare("SELECT id FROM class_info WHERE id = ? and institution_id=? ");
$res->execute(array($class_id, $institution_id));
$result1 = $res->fetchAll();
if (count($result1) != 1) {
    errorreturn("Class not found.");
}

$sql_codes = $conn_rjllearning_specific->prepare("Select count(*) as total from  section_info WHERE id = ? AND institution_id=?");
$sql_codes->execute(array($section_id,$institution_id));
$result_branch = $sql_codes->fetchAll()[0]['total'];
if ($result_branch != 1) {
    errorreturn("Section Not Found.");
}

if ($student_id != 'all') {

    if (!is_array($student_id) or count($student_id) <= 0) {
        errorreturn("Select atleast one section.");
    }

    $imploded_student_ids = "('" . implode("','", $student_id) . "')";
    $count_ids = count($student_id);

    $sql_students = $conn_rjllearning_specific->prepare("Select count(*) as total from  students WHERE id IN $imploded_student_ids and institution_id=?");
    $sql_students->execute(array($institution_id));
    $result_student = $sql_students->fetchAll()[0]['total'];
    if ($result_student != $count_ids) {
        errorreturn("Student Not Found.");
    }
    $imploded_studentsids = "'" . implode("','", $student_id) . "'";
} else {

    $imploded_studentsids = $student_id;
}
$data_with_empty_values = array_fill_keys($data_printed, '');
// $data_printed = serialize($data_printed);
$data_printed = json_encode($data_with_empty_values);
// print_r($data_printed);die();
if($postdata['function_type'] == "create_student_id_cards") {
    
    $res = $conn_rjllearning_specific->prepare("SELECT id FROM student_id_cards WHERE institution_id =? AND branch_id= ? AND academic_id= ? AND class_id= ? AND section_id =? AND selected_template = ? ");
    $res->execute(array($institution_id,$branch_id, $academic_id, $class_id, $section_id,$selected_template));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Student ID cards already exists.");
    }
     
    try {

        $sql = "INSERT INTO student_id_cards(institution_id,branch_id,academic_id,class_id,section_id,student_id,selected_template,generated_by,generated_on,data_printed,status,date_created)
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt =  $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array($institution_id,$branch_id, $academic_id, $class_id, $section_id, $imploded_studentsids, $selected_template, $username, time(), $data_printed, '1',date('Y-m-d')));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }

    $id = $conn_rjllearning_specific->lastInsertId();
    updateIDCardTemplateSelected($conn_rjllearning_specific, $selected_template, $institution_id, $branch_id);
    successreturn(array('id' => $id, 'successmsg' => "Successfully students cards  added."));
    
}if($postdata['function_type'] == "alter_student_id_cards") {
    
    if (!isset($postdata['cards_id']) or !checkIfIssetAndNotEmpty($postdata['cards_id'])) {
        errorreturn('Error in updating the student id cards.');
    } else {
        $cards_id = $postdata['cards_id'];
    }
    
    $sql = $conn_rjllearning_specific->prepare("SELECT id FROM student_id_cards WHERE id =  ? AND institution_id =? AND branch_id= ? AND academic_id= ? AND class_id= ? AND section_id =?  AND student_id =?  AND selected_template = ?");
    $sql->execute(array($cards_id,$institution_id,$branch_id, $academic_id, $class_id, $section_id, $student_id,$selected_template));
    $result = $sql->fetchAll();
    if (count($result) != 1) {
        errorreturn("Student ID cards not exists.");
    }
    
    $sql_users = "UPDATE student_id_cards SET branch_id = ?,class_id =?,section_id= ?,student_id=?,selected_template = ?,data_printed = ? WHERE id=? and institution_id=?";
    $conn_rjllearning_specific->prepare($sql_users)->execute(array($branch_id,$class_id, $section_id, $student_id, $selected_template,$data_printed, $cards_id, $institution_id));
    successreturn("Updated homework Successfully");
}

