<?php

declare(strict_types=1);

namespace prj\mockup\outputs\app;

use \tts\safer_io as SafeIO;

class home_out {
    
    public static function name_demo(array & $input): array {
        $ret['model'] = $input['model'];
        unset($input['model']); // Free up some space
        
        $submitted = $input['submitted'] ?? false;
        
        if ($submitted) {
            $html_output = [];
            $errors = [];
            foreach(SafeIO::html_escape_and_sanitize($input) as $html) {
                $key = $html['name'] ?? "";
                $html_output[$key] = $html['html'];

                if (\tts\common::get_count($html['errors'])) {
                    $errors[$key] = $html['errors'][$key];
                }
            }
            
            SafeIO::clear_post_data(); // Last use of Post
            
            $age = $html_output['age'] ?? 0;        
            $first_name = $html_output['first_name'] ?? "Unknown";
            $last_name = $html_output['last_name'] ?? "Unknown";

            $ret['main'] = (\tts\common::get_count($errors)) ? "" : "Hello, {$first_name} {$last_name}, you are {$age} years old!" . PHP_EOL;
            $ret['errors'] = $errors;
        } else {
            $ret['main'] = "Welcome";
            $ret['errors'] = [];
        }
        
        unset($input); // Free up some space
        
        return $ret;
    }
  
    public static function show_errors(array $errors): string {
        if ($errors) {
            $message = "Please correct the following errors: ";
            $i = 0;
            foreach($errors as $error) {
                $i++;
                $message .= "<br/>{$i}) " . $error;
            }
            return $message;
        }
        return ""; // No Errors to return here
    }
    
    public static function show_user_details(\Generator $input): void {
        if (! $input->current()) {
            return; // No Data, so Bail here
        }
        \tts\html::show_table_from_generator(
            ['ID', 'First Name', 'Last Name', 'Age'],
            $input
        );
    }
    
}
