<?php
class PeopleController extends AppController {

	var $name = 'People';
    var $helpers = array('Html', 'Form');

    function beforeFilter() {
        parent::beforeFilter();
        #$this->Auth->allow('add', 'edit');

       if ($this->action == 'add' || $this->action == 'edit') {
            $this->Auth->authenticate = $this->Person;
       }
    }

	function index() {
		$this->Person->recursive = 0;
		$this->set('people', $this->paginate());
	}
	
    function login() {
		#$this->Auth->login();
    }
	
    function logout() {
        $this->Auth->logout();
        $this->redirect('/');
    }

    /**
     * Expects a file with on each line following information:
     * - prolly an ID, but first column is ignored
     * - username (login)
     * - name (display name)
     * - password, and if empty, will be default
     */
    function upload() {
        if (! empty($this->data)) {
            $raw = file_get_contents($this->data['File']['raw']['tmp_name']);
            $raw = mb_convert_encoding($raw, 'UTF-8', mb_detect_encoding($raw));
            $lines = explode("\n", $raw);
            $line_nr = 1;

            $this->Person->begin();
            $success = true;
            foreach ($lines as $line) {
                $line = trim($line);
                if (!$line) { # skip empty lines
                    continue;
                }
                $line_parts = explode("\t", $line);
                foreach ($line_parts as &$item) {
                    $item = preg_replace('/^"|"$/', '', $item);
                }
                list($id, $name, $username, $email) = $line_parts;
                list(,$domain) = explode('@', $email);

                $password = Configure::read('default.password');
                $password_confirm = $password; # make sure the validation actually works
                $this->Person->create();
                if (! $this->Person->save(array(
                    'Person' => compact('name', 'username', 'password', 'password_confirm'),
                ))) {
                    $this->Person->rollback();
                    $this->Session->setFlash("Could not save person on line #$line_nr: '$line'".pr(compact('name', 'username', 'password', 'password_confirm'), true));
                    $success = false;
                    break;
                }
                $line_nr++;
            }
            if ($success) {
                $this->Person->commit();
            }
        }
    }

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid person', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('person', $this->Person->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Person->create();
			foreach($this->data['Person']['project_id'] as $project) {
				$this->data['Project'][] = $project;
			}
			if ($this->Person->save($this->data)) {
				$this->Session->setFlash(__('The person has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The person could not be saved. Please, try again.', true));
			}
		} else {
			$roles = array('normal' => 'normal', 'admin' => 'admin', 'guest' => 'guest');
			$projects = $this->Person->Project->find('list');
			$this->set(compact('roles', 'projects'));
		}
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid person', true));
			$this->redirect('/');
		}
		$this->Person->id = $id;
		$projects = $this->Person->Project->find('list');
		$projects_for_person = $this->Person->query("SELECT DISTINCT p.name, p.id FROM projects p
			INNER JOIN projectpeople prp ON prp.project_id = p.id
			WHERE prp.person_id = " . $id);
		
		$projects_for_person_list = Set::combine($projects_for_person, '{n}.p.id', '{n}.p.name');
		
		$other_projects = array();
		foreach ($projects as $key => $value) {
			if (!in_array($value, $projects_for_person_list)) {
				$other_projects[$key] = $value;
			}
		}
		if (!empty($this->data)) {
		
			$projects_to_delete = $this->data['People']['projects_to_delete'];
			if (!empty($projects_to_delete)) {
				foreach($projects_to_delete as $key => $value) {
					unset($projects_for_person_list[$value]);
				}
			}			
			
			$projects_to_add = $this->data['People']['projects_to_add'];
			
			unset($this->data['Project']);
			
			foreach($projects_for_person_list as $key => $value) {
				$this->data['Project'][] = $key;
			}
			
			if (!empty($projects_to_add)) {
				foreach ($projects_to_add as $key => $value) {
					$this->data['Project'][] = $value;
				}
			}
			
            if (empty($this->data['Person']['password'])) {
                unset($this->data['Person']['password']);
            }
			if ($this->Person->save($this->data)) {
				$this->Session->setFlash(__('The person has been saved', true));
				$this->redirect('/');
			} else {
				$this->Session->setFlash(__('The person could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Person->read(null, $id);
			
		}
        $roles = array('normal' => 'normal', 'admin' => 'admin', 'guest' => 'guest');
		$this->set(compact('roles', 'projects_for_person_list', 'other_projects'));
	}

	 function invalidate($id = null) {
        if (!$this->RequestHandler->isAjax()) { # if no AJAX, it might be just a crawler
            $this->redirect('/', 500);
        }
        if (!$id) {
            $this->Session->setFlash(__('Invalid user', true));
            $this->redirect(array('action' => 'index'));
        }
        $person = $this->Person->read(null, $id);
        $person['Person']['allowlogin'] = $person['Person']['allowlogin'] == 0 ? 1 : 0;
		$this->Person->id = $id;
        if ($this->Person->saveField('allowlogin',$person['Person']['allowlogin'])) {
            $this->Session->setFlash(__('Person saved.', true));
        } else {
            $this->Session->setFlash(__('Person not saved.', true));
            $this->redirect('/', 500);
        }
    }
	
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for person', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Person->delete($id)) {
			$this->Session->setFlash(__('Person deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Person was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
?>
