<?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 . 'functions/get_branch_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
$requiredFields = ['branch_id', 'institution_id', 'attendance_system', '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","principal","teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

// Sanitize input data
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$attendance_system = trim($postdata['attendance_system']);

// 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.");
}


$isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
if (!$isBranchClassSubjectValid) {
    errorreturn("Invalid branch_id.");
}
// Validate attendance settings
if (!isset($postdata['faculty_attendance_setting'])) {
    errorreturn("Attendance settings are required.");
}

// Validate attendance settings
if (!isset($postdata['faculty_attendance_setting']) || empty($postdata['faculty_attendance_setting'])) {
    errorreturn("Attendance settings are required.");
}

$attendance_setting = $postdata['faculty_attendance_setting'];
$attendance_fields = [
    'self_mark' => [0, 1], // 0 for no self-attendance required, 1 for required
    'methods' => [
        'gps' => [0, 1] // 1 for required, 0 for not required
    ]
];

// Validate `self_mark` field
if (!isset($attendance_setting['self_mark']) || !in_array((int)$attendance_setting['self_mark'], $attendance_fields['self_mark'])) {
    errorreturn("Invalid value for self_mark. Must be 0 or 1.");
}

// If self_mark is 1, validate `methods` fields
if ((int)$attendance_setting['self_mark'] === 1) {
    foreach ($attendance_fields['methods'] as $method => $valid_values) {
        if (!isset($attendance_setting['methods'][$method]) || !in_array((int)$attendance_setting['methods'][$method], $valid_values)) {
            errorreturn("Invalid value for $method. Must be 0 or 1.");
        }
    }
}

// Create the attendance settings array
$attendance_settings_array = [
    'self_mark' => (int)$attendance_setting['self_mark']
];

if ((int)$attendance_setting['self_mark'] === 1) {
    $attendance_settings_array['methods'] = [
        'gps' => (int)$attendance_setting['methods']['gps']
    ];
}

// JSON encode the attendance settings
$attendance_setting_json = json_encode($attendance_settings_array);

$other_setting = isset($postdata['birthday_mail']) ? $postdata['birthday_mail'] : null;

if ($other_setting === null) {
    // If no birthday_mail settings are provided, treat them as null
    $other_settings_array = [
        'send_birthday_mails_automatically' => null,
        'birthday_mail' => null,
    ];
} else {
    // Define valid values for `send_birthday_mails_automatically`
    $valid_send_values = [1, 0];

    // Set `send_birthday_mails_automatically` to null if not provided
    if (!isset($other_setting['send_birthday_mails_automatically'])) {
        $other_setting['send_birthday_mails_automatically'] = null;
    } elseif (!in_array($other_setting['send_birthday_mails_automatically'], $valid_send_values)) {
        errorreturn("Invalid value for send_birthday_mails_automatically. Must be 1 or 0.");
    }

    $default_birthday_mail_template = 'Dear {$student_name$},  

    Warmest birthday wishes from all of us at {$institution_name$}!  
    As a valued part of our {$branch_name$}, we want you to know how proud we are of your journey and accomplishments.  

    On your special day, may you be surrounded by love, happiness, and endless opportunities. Remember, your potential is limitless, and we are here to support you every step of the way.  

    Wishing you a year ahead filled with joy, success, and wonderful memories.  

    Best regards,  
    {$principal_name$}  
    Principal, {$institution_name$}  
    ';

    // Check if a custom birthday message is provided
    if (isset($other_setting['custom_birthday_mail']) && !empty(trim($other_setting['custom_birthday_mail']))) {
        $birthday_mail_template = trim($other_setting['custom_birthday_mail']);
    } else {
        $birthday_mail_template = $default_birthday_mail_template;
    }

    // Prepare the "other settings" array
    $other_settings_array = [
        'send_birthday_mails_automatically' => $other_setting['send_birthday_mails_automatically'],
        'birthday_mail' => $birthday_mail_template,
    ];
}

$other_setting_json = json_encode($other_settings_array);


if ($postdata['function_type'] == "update_institution_global_settings") {
    // Check if setting already exists
    // $res = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM institution_global_settings WHERE  id = ?  AND institution_id = ? AND branch_id = ?");
    // $res->execute([$setting_id, $institution_id,$branch_id]);
    // $result1 = $res->fetchAll();
    // if (count($result1) != 1) {
    //     errorreturn("Institution setting not exists.");
    // }

    $sql = $conn_rjllearning_specific->prepare("SELECT id FROM branch WHERE id = ? AND institution_id = ?");
    $sql->execute([$branch_id, $institution_id]);
    $result = $sql->fetchAll();
    if (count($result) != 1) {
        errorreturn("Branch not found.");
    }
    
    // Update setting
    $sql = "UPDATE institution_global_settings SET  attendance_system=?,faculty_attendance_setting=?,other=?, last_modified_by=?, last_updated_time=? WHERE institution_id = ? AND branch_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([$attendance_system,$attendance_setting_json,$other_setting_json, $username, $last_updated_time, $institution_id,$branch_id]);
    
    // Return success message
    successreturn("Updated institution global settings successfully.");

}
?>
