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


/**
 * Class TB_Shared_Ent_TeamData_Notification
 *
 * @property integer $id
 * @property string $ref_id
 * @property integer|null $creator_profile_id
 * @property string $message
 * @property DateTime $last_updated_dt
 * @property DateTime $created_dt
 *
 */
class TB_Shared_Ent_TeamData_Chat extends Francis_Db_Row
{
    /**
     * @param $profileId
     * @return array
     */
    public static function getForRefId( $refId, $lastId = NULL )
    {
        $sqlParams = array( ':ref_id' => $refId );

        $sql  = 'SELECT p.first_name AS first_name, p.last_name AS last_name, p.pic_url AS pic_url, ';
        $sql .= 'c.* FROM ' . self::getTable() . ' AS c ';
        $sql .= 'LEFT JOIN ' . TB_Shared_Ent_TeamData_Profile::getTable() . ' AS p ';
        $sql .= 'ON p.id = c.creator_profile_id ';
        $sql .= 'WHERE ref_id= :ref_id ';
        if ( !is_null( $lastId ) )
        {
            $sql .= 'AND c.id > :last_id ';
            $sqlParams[ ':last_id' ] = $lastId;
        }
        $sql .= 'ORDER BY created_dt ASC';

        $dbh = self::getDbh();
        $stmt = $dbh->prepare( $sql );
        $stmt->execute( $sqlParams );
        $res = $stmt->fetchAll( PDO::FETCH_ASSOC );
        return $res;
    }

    /**
     * Delete all profile related news entries
     *
     * @param int $profileId
     * @return bool
     */
    public static function deleteByAuthorProfileId( $profileId ) {
        $sql = 'DELETE FROM ' . self::getTable() . ' WHERE creator_profile_id = :profile_id';
        return self::execute( $sql, array( ':profile_id' => $profileId ) );
    }


    public static function deleteAllFromCreatorForAppointment( $appointmentId, $profileId )
    {
        $sql  = 'DELETE FROM ' . self::getTable() . ' WHERE creator_profile_id = :profile_id ';
        $sql .= 'AND ref_id = :ref_id';
        return self::execute( $sql, array( ':profile_id' => $profileId, ':ref_id' => 'appointment- '. $appointmentId ) );
    }

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

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