<?php

/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-1-16
 * Time: 上午9:23
 */
class Register extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('users_model', 'users');
    }

    public function index() {
        $data['provinces'] = $this->db->where('parent_id', 0)->get('city')->result_array();
        $this->load->view('register', $data);
    }

    function city($id) {
        if (!$id) {
            return false;
        }
        $city = $this->db->where('parent_id', $id)->get('city')->result_array();
        show_json($city);
    }

    function submit() {
        $username   = $this->input->post('username');
        $password   = $this->input->post('password');
        $repassword = $this->input->post('repassword');
        $city       = $this->input->post('city');

        if ($password != $repassword) {
            show_json(['error' => '两次输入的密码不相同。']);
            return;
        }

        if ($this->users->get(null, 'id', ['name' => $username])) {
            show_json(['error' => '用户名已存在，请重新输入。']);
            return;
        }

        $user = [
            'id'       => 0,
            'name'     => $username,
            'password' => md5($password),
            'avatar'   => '',
            'level'    => 1,
            'city'     => $city
        ];

        $this->db->insert('users', $user);
        $user['id'] = $this->db->insert_id();
        $this->session->set_userdata('EXM_USER', $user);
        session_write_close();
        show_json(['success' => '注册成功', 'user' => $user]);
    }

}