<?php

namespace HwapX\Core\Library;

use HwapX\Core\Library\Validator;

use \F3;
use \Prefab;
use \DB\SQL;

class Form extends Prefab {
  protected $f3        = null;
  protected static $db = null;
  protected $errors    = array();
  protected $hasError  = false;

  public function __construct() {
    $this->f3 = F3::instance();
  }

  public function validate($rules, $data = null) {
    $data = is_null($data) ? $this->f3->get('POST') : $data;
    $validator = Validator::createFrom($rules, $data);

    $this->hasError = !$validator->validate();

    $this->errors   = $validator->errors();

    foreach ($rules as $group => $value) {
      if(isset($value['table'])) {
        $r = $value['table'];
        foreach ($data[$group] as $idx => $table) {
          $validator = Validator::createFrom($r, $table);

          if(!$validator->validate()) {
            $this->errors[$group][$idx] = $validator->errors();
            $this->hasError             = true;
          }
        }
      }
    }

    return !$this->hasError;
  }

  public function errors() {
    return $this->errors;
  }

  public function create($rules, $data = null) {
    $id = null;
    if($this->validate($rules, $data)) {
      foreach ($rules as $group => $value) {
        if(isset($value['table'])) {
          $r = $value['table'];
          foreach ($data[$group] as $idx => $table) {
            $validator = Validator::createFrom($r, $table);

            if(!$validator->validate()) {
              $this->errors[$group][$idx] = $validator->errors();
              $this->hasError             = true;
            }
          }
        }
      }
    }



    return $id;
  }

  public function edit($rules, $data = null, $id = null) {
    
  }

  public function delete($rules, $data = nul, $id = nulll) {
    
  }
}