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

/**
 * Class TB_Shared_Ent_Core_Account
 *
 * @property integer $id
 * @property string $token
 * @property string $action
 * @property array|null $action_data_js
 * @property int|null $related_account_id
 * @property DateTime $last_updated_dt
 * @property DateTime $created_dt
 */
class TB_Shared_Ent_Core_ActionData extends Francis_Db_Row
{
    const ACTION_VALIDATE_EMAIL = 'validate_email';
    const ACTION_RESET_PASSWORD = 'reset_password';

    /**
     * @param $action
     * @param array|NULL $data
     * @return TB_Shared_Ent_Core_ActionData
     */
    public static function createNew( $action, array $data = NULL, $relatedAccountId = NULL )
    {
        $entActionData = new self();
        $entActionData->token = TB_Server_Utils_Helper::getToken( 32 );
        $entActionData->action = $action;
        $entActionData->action_data_js = $data;
        $entActionData->related_account_id = $relatedAccountId;
        $entActionData->save();

        return $entActionData;
    }

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

    /**
     * @param $action
     * @param $accountId
     * @return NULL|TB_Shared_Ent_Core_ActionData
     */
    public static function getByActionAndAccountId( $action, $accountId )
    {
        $sql = 'SELECT * FROM ' . self::getTable() . ' WHERE action = :action AND :related_account_id = :related_account_id LIMIT 1';
        return self::findOne( $sql, array( ':action' => $action, ':related_account_id' => $accountId ) );
    }

    public static function deleteAllForAccountId( $accountId )
    {
        $sql = 'DELETE FROM ' . self::getTable() . ' WHERE related_account_id = :account_id';
        return self::execute( $sql, array( ':account_id' => $accountId ) );
    }

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

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