<?php

namespace Controller;

class User {

    private $db;
    
    function __construct() {
        // $this->db = new \DB\SQL('sqlite:data/login.sqlite');

        // $this->db->exec("CREATE TABLE IF NOT EXISTS users
        //   (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
        //    email varchar(128) NULL DEFAULT 'anonymous',
        //    password varchar(128) NULL,
        //    balance REAL
        //   )"
        // );

        $this->db = new \DB\Jig('data/');
        
    }

    function login() {
        $f3 = \Base::instance();
        $audit = \Audit::instance();
        
        $username = $f3->get('GET.uname');
        $password = $f3->get('GET.psw');

        
        $mapper = new \DB\Jig\Mapper($this->db, 'users');
        $auth = new \Auth(
            $mapper,
            array('id' => 'email', 'pw' => 'password')
        );


        if ( $auth->login($username,$password) ) {
            $mapper->load(array("@email = ?", $username));
        
            new \Session();
            $f3->mset(array(
                'SESSION.login.email' => $mapper->email,
                'SESSION.login.balance' => 100
            ));

            $f3->reroute('/dashboard');
        } else {
            echo "no success";
        }

        
        $f3->set('template', "login.htm");
        
    }

    function register() {
        $f3 = \Base::instance();
        $audit = \Audit::instance();
        //var_dump($f3->get("GET"));

        if ( $f3->get('GET.psw') == $f3->get('GET.psw-repeat')) {
            $password = $f3->get('GET.psw');
        }
        $email = $f3->get('GET.email');

        
        
        if ( $password && $email) {
            $mapper = new \DB\Jig\Mapper($this->db, 'users');
            
            $mapper->email = $email;
            $mapper->password = $password;
            $mapper->save();

            $f3->reroute('/login');
        }
        
        
        $f3->set('template', "register.htm");
    }
}
