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

require_once '../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

$postdata = json_decode(file_get_contents("php://input"), true);
// print_r($postdata);
checkIfNoPhpContentsReceive();


if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_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.");
}
validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$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']);
$sidebar_background_color = (isset($postdata['sidebar_background_color']) and !empty($postdata['sidebar_background_color'])) ? trim($postdata['sidebar_background_color']) : null;
$sidebar_menu_secondary_font_color = (isset($postdata['sidebar_menu_secondary_font_color']) and !empty($postdata['sidebar_menu_secondary_font_color'])) ? trim($postdata['sidebar_menu_secondary_font_color']) : null;
$sidebar_menulist_bg = (isset($postdata['sidebar_menulist_bg']) and !empty($postdata['sidebar_menulist_bg'])) ? trim($postdata['sidebar_menulist_bg']) : null;
$sidebar_menu_primary_font_color = (isset($postdata['sidebar_menu_primary_font_color']) and !empty($postdata['sidebar_menu_primary_font_color'])) ? trim($postdata['sidebar_menu_primary_font_color']) : null;

$heading_primary_font_color = (isset($postdata['heading_primary_font_color']) and !empty($postdata['heading_primary_font_color'])) ? trim($postdata['heading_primary_font_color']) : null;
$heading_secondary_font_color = (isset($postdata['heading_secondary_font_color']) and !empty($postdata['heading_secondary_font_color'])) ? trim($postdata['heading_secondary_font_color']) : null;
$button_primary_color = (isset($postdata['button_primary_color']) and !empty($postdata['button_primary_color'])) ? trim($postdata['button_primary_color']) : null;
$button_secondary_color = (isset($postdata['button_secondary_color']) and !empty($postdata['button_secondary_color'])) ? trim($postdata['button_secondary_color']) : null;

// Validate width
$width = (isset($postdata['width']) && !empty($postdata['width'])) ? trim($postdata['width']) : null;
if ($width !== null && (!is_numeric($width) || $width > 250)) {
    errorreturn('Invalid width. It must be numeric and not exceed 250.');
}

// Validate height
$height = (isset($postdata['height']) && !empty($postdata['height'])) ? trim($postdata['height']) : null;
if ($height !== null && !is_numeric($height)) {
    errorreturn('Invalid height. It must be numeric.');
}

// Validate logo alignment
$logo_alignment = (isset($postdata['logo_alignment']) && !empty($postdata['logo_alignment'])) ? trim($postdata['logo_alignment']) : null;

// If further validation is needed for $logo_alignment (e.g., specific allowed values)
$valid_alignments = ['left', 'center', 'right'];
if ($logo_alignment !== null && !in_array($logo_alignment, $valid_alignments)) {
    errorreturn('Invalid logo alignment. It must be one of: left, center, right.');
}

$avatar_bg_color = (isset($postdata['avatar_bg_color']) and !empty($postdata['avatar_bg_color'])) ? trim($postdata['avatar_bg_color']) : null;
$avatar_primary_font_color = (isset($postdata['avatar_primary_font_color']) and !empty($postdata['avatar_primary_font_color'])) ? trim($postdata['avatar_primary_font_color']) : null;
$avatar_secondary_font_color = (isset($postdata['avatar_secondary_font_color']) and !empty($postdata['avatar_secondary_font_color'])) ? trim($postdata['avatar_secondary_font_color']) : null;
$sidebar_font_color = (isset($postdata['sidebar_font_color']) and !empty($postdata['sidebar_font_color'])) ? trim($postdata['sidebar_font_color']) : null;
 
// Construct the array
$site_ui_settings = [
    'sidebar_background_color' => $sidebar_background_color,
    'sidebar_menu_secondary_font_color' => $sidebar_menu_secondary_font_color,
    'sidebar_menulist_bg' => $sidebar_menulist_bg,
    'sidebar_menu_primary_font_color' => $sidebar_menu_primary_font_color,
    'heading_primary_font_color' => $heading_primary_font_color,
    'heading_secondary_font_color' => $heading_secondary_font_color,
    'button_primary_color' => $button_primary_color,
    'width' => $width,
    'height' => $height,
    'logo_alignment' => $logo_alignment,
    'avatar_bg_color' => $avatar_bg_color,
    'avatar_primary_font_color' => $avatar_primary_font_color,
    'avatar_secondary_font_color' => $avatar_secondary_font_color,
    'sidebar_font_color' => $sidebar_font_color,
    'button_secondary_color'=>$button_secondary_color,
];

// Convert the array to JSON format
$site_ui_settings_json = json_encode($site_ui_settings);

if ($postdata['function_type']  == "create_site_settings") {

    //Check if setting already exists
    $res = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM site_settings WHERE institution_id = ?");
    $res->execute([$institution_id]);
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        // errorreturn("Institution site setting already exists.");
        $deleteStmt = $conn_rjllearning_specific->prepare("DELETE FROM site_settings WHERE institution_id = ?");
        $deleteStmt->execute([$institution_id]);
    }

    $last_updated_time =  null;
    $last_modified_by =  null;

    try {

        $sql = "INSERT INTO site_settings(institution_id,site_ui_settings,added_by,last_modified_by,last_updated_time,status)
            VALUES(?,?,?,?,?,?)";
        $stmt =  $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array($institution_id, $site_ui_settings_json, $username, $last_modified_by, $last_updated_time, 1));
        $id = $conn_rjllearning_specific->lastInsertId();


        successreturn(array('site_id' => $id, 'successmsg' => 'Successfully site settings added.'));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
} 
// else if ($postdata['function_type']  == "alter_site_settings") {
//     if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])) {
//         errorreturn('Error in updating the site settings.');
//     } else {
//         $setting_id = $postdata['setting_id'];
//     }

//     $status = trim($postdata['status']);

//     $sql = "UPDATE site_settings SET  sidebar_menulist_bg =?,sidebar_menu_primary_font_color =?,sidebar_menu_secondary_font_color =?,sidebar_background_color=?,heading_primary_font_color = ?,heading_secondary_font_color = ?,
//      button_primary_color = ?,button_secondary_color = ?,avatar_bg_color = ?,avatar_primary_font_color = ?,avatar_secondary_font_color = ?,sidebar_font_color = ?,status = ?, last_modified_by=?, last_updated_time=? WHERE id = ? AND institution_id = ?";
//     $stmt = $conn_rjllearning_specific->prepare($sql);

//     // Get the current timestamp and format it as a date string
//     $last_updated_time = date("Y-m-d H:i:s", time());

//     // Execute the SQL query with the formatted date string
//     $stmt->execute([$sidebar_menulist_bg, $sidebar_menu_primary_font_color, $sidebar_menu_secondary_font_color, $sidebar_background_color, $heading_primary_font_color, $heading_secondary_font_color,
//     $button_primary_color, $button_secondary_color, $avatar_bg_color, $avatar_primary_font_color, $avatar_secondary_font_color, $sidebar_font_color,
//     $status, $username, $last_updated_time, $setting_id, $institution_id]);

//     // Return success message
//     successreturn("Updated institution global settings successfully.");
// }
