<?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';

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

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

// Validate required fields
if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or

!isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
!isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or 
!isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or 
!isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])) {
    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, null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$marksheet_template_name = (isset($postdata['marksheet_template_name']) and !empty($postdata['marksheet_template_name'])) ? (trim($postdata['marksheet_template_name'])) : null;
$marksheet_template_description = (isset($postdata['marksheet_template_description']) and !empty($postdata['marksheet_template_description'])) ? (trim($postdata['marksheet_template_description'])) : null;
$color = $postdata['color'];//background_color,border,primary_text-color,secondary-text-color,marksheet_title_color, institution_title_color,branch_title_color
$color = json_encode($color,true);
$header = trim($postdata['header']);
// $footer = trim($postdata['footer']);
// $body = $postdata['body'];
// $body = json_encode($body,true);
$body =  null;
$footer=  null;

// Check if academic session is active
$check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$check_academic_confirmation) {
    errorreturn("Access denied. Academic session not active.");
}

if ($postdata['function_type'] == "create_marksheet_template") {
    
    $sql = $conn_rjllearning_specific->prepare("SELECT id FROM marksheet_template WHERE institution_id = ? and branch_id= ? and header = ?");
    $sql->execute(array($institution_id, $branch_id,$header));
    $result = $sql->fetchAll();
    if (count($result) >= 1) {
        errorreturn("Marksheet template already exists");
    }
   
    $last_modified_by=  null;
    $sql = "INSERT INTO marksheet_template(institution_id, branch_id,marksheet_template_name,marksheet_template_description, color,header,body,footer,added_by,last_modified_by,date_created,time_created,status) 
    VALUES(?, ?, ?, ?, ?, ?, ?, ? , ?, ? , ? ,? , ?)";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute(array($institution_id, $branch_id,$marksheet_template_name,$marksheet_template_description, $color,$header,$body,$footer,$username,$last_modified_by,date('y-m-d'),time(),1));
    $marksheet_id = $conn_rjllearning_specific->lastInsertId();
    
    successreturn(array('marksheet_id' => $marksheet_id, 'successmsg' => "Successfully marksheet template added."));

}elseif ($postdata['function_type'] == "alter_marksheet_template") {
    
    $ExecuteSqlSettings = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM marksheet_template WHERE id = ? AND institution_id = ? AND branch_id = ?");
    $ExecuteSqlSettings->execute([$marksheet_id, $institution_id,$branch_id]);
    $ResultSettings = $ExecuteSqlSettings->fetchAll();
 
    if ($ResultSettings < 1) {
        errorreturn("Institution marksheet template not exists.");
    }
    
     $res = $conn_rjllearning_specific->prepare("SELECT id FROM marksheet_template WHERE id != ? and institution_id = ? and  (background = ? OR border = ? OR body = ?) ");
    $res->execute(array($id, $institution_id, $background, $border,$body));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("This marksheet template already exits. Kindly check background or message or body");
    }
    
    $last_updated_time = date("Y-m-d H:i:s", time());
    $sql = "UPDATE marksheet_template SET marksheet_template_name =? ,marksheet_template_description =? ,color= ?,header = ?,body= ?,footer= ?, last_modified_by=?, last_updated_time=?,last_modified_at = ? WHERE id = ? AND institution_id = ? and branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$marksheet_template_name,$marksheet_template_description,$color,$header,$body,$footer, $username,$last_updated_time,date('Y-m-d'), $marksheet_id, $institution_id,$branch_id]);
    successreturn("Updated marksheet template successfully.");
    
}
