<?php

declare(strict_types=1);

namespace prj\mockup\models\app;

class home_model extends \tts\model {
    protected $pdo;
    protected $table = "test_names";
        
    public function __construct($dbh) {
//        \tts\DB_Exception::$error_message = "Home Model Error";
        $this->pdo = $dbh;
    }
   
    public function pre_save(): bool {
        $missing = $this->get_missing();
        if (count($missing)) {
            echo "Required fields not set " . implode(",", $missing) . "!";
            return false;
        }
        
        if ($this->dump_diff()) {
            return false; // Opps forgot a field!
        }
        return true;
    }
    
    public function init_name_demo_table(): void {
        $create_table_sql = "CREATE TABLE IF NOT EXISTS `{$this->table}`(
                `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                `first_name` TEXT,
                `last_name` TEXT,
                `age` INTEGER
        )";
      try {
        $this->pdo->query($create_table_sql);
      } catch (\PDOException $e) {
        echo \tts\DB_Exception::customMessage($e, "Unable to make table!");
      }  
    }
    
    public function populate($rows): void {
        $dummy = new \tts\dummy_data($this->pdo);
        $data = [ 'first_name' => \tts\rnd_names::get_first_names(),
                  'last_name' => \tts\rnd_names::get_last_names(),
                  'age' => \tts\rnd_names::mock_age() ];
      try {  
        $dummy->add_dummy_data($this->table, $rows, $data);
      } catch (\PDOException $e) {
        echo \tts\DB_Exception::customMessage($e, "Unable to populate table!");
      }
    }
    
    public function save_new_user(array $input): bool {
        $set = $this->set_members_by_generator($input);
        if ($set === false) {
            return false; // Found Validation issues in input
        }
      try {
        $status = $this->save();
      } catch (\PDOException $e) {
        echo \tts\DB_Exception::customMessage($e, "Unable to save changes!");
      }  
        if ($status === self::successful_save) {
            return true; // It saved
        }
        return false; // It did not save
    }
   
    public function get_users(int $number_of_users_to_get = 12): \Generator {
       if ($number_of_users_to_get === 0) {
            return self::empty_generator();
        }
      try {  
        $sql = "SELECT * FROM {$this->table} LIMIT {$number_of_users_to_get}";
        $result = $this->pdo->query($sql);
        return self::pdo_fetch_lazy($result);
      } catch (\PDOException $e) {
        echo \tts\DB_Exception::customMessage($e);
      }
    }
}