<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/

/**
 * Class TB_Shared_Ent_Core_Account
 *
 * @property integer $id
 * @property string $email
 * @property string $pass
 * @property bool $is_validated
 * @property bool $subscribed_newsletter
 * @property DateTime $last_updated_dt
 * @property DateTime $created_dt
 */
class TB_Shared_Ent_Core_Account extends Francis_Db_Row {

    const PASSWORD_MINIMUM_CHARS = 4;
    const PASSWORD_MAXIMUM_CHARS = 32;

    /**
     * @param $email
     * @param $pass
     * @return NULL|TB_Shared_Ent_Core_Account
     */
    public static function getByCredentials( $email, $pass ) {
        $sql = 'SELECT * FROM ' . self::getTable() . ' WHERE email = :email AND pass = :pass LIMIT 1';
        return self::findOne( $sql, array( ':email' => $email, ':pass' => $pass ) );
    }

    /**
     *
     * @param $email
     * @return NULL|TB_Shared_Ent_Core_Account
     */
    public static function getByEmail( $email ) {
        $sql = 'SELECT * FROM ' . self::getTable() . ' WHERE email = :email LIMIT 1';
        return self::findOne( $sql, array( ':email' => $email) );
    }

    /**
     * @param array $accountIds
     * @return array
     */
    public static function getEmailsForAccountIds( array $accountIds )
    {
        $emails = array();
        if ( 0 === count( $accountIds ) ) return $emails;

        $dbh = self::getDbh();
        $in  = str_repeat('?,', count( $accountIds ) - 1) . '?';
        $sql = "SELECT id, email FROM " . self::getTable() . " WHERE id IN ($in)";
        $stmt = $dbh->prepare( $sql );
        $stmt->execute( $accountIds  );
        $emails = $stmt->fetchAll( PDO::FETCH_ASSOC );

        return $emails;
    }

    /**
     * Delete by account id
     *
     * @param $accountId
     * @return bool
     */
    public static function deleteByAccountId( $accountId ) {
        $sql = 'DELETE FROM ' . self::getTable() . ' WHERE id = :account_id LIMIT 1';
        return self::execute( $sql, array( ':account_id' => $accountId ) );
    }

    /**
     * Deletes core references
     */
    public function deleteReferences()
    {
        TB_Shared_Ent_Core_ActionData::deleteAllForAccountId( $this->id );
        TB_Shared_Ent_Core_DeviceReg::deleteByAccountId( $this->id );
        TB_Shared_Ent_Core_Session::deleteByAccountId( $this->id );
    }

    /**
     * Return table name
     *
     * @return null|string
     */
    public static function getTable() {
        return 'account';
    }

    /**
     * Return db handler
     *
     * @return Francis_Db_MySql|null
     */
    public static function getDbh() {
        return TB_Shared_Db_Core::get();
    }

} 