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


/**
 * Class TB_Shared_Ent_TeamData_Job
 * @property integer $id
 * @property integer $ref_id
 * @property string $job_status
 * @property string $job_name
 * @property NULL|array $job_data_js
 * @property DateTime $trigger_dt
 * @property DateTime $last_updated_dt
 * @property DateTime $created_dt
 */
class TB_Shared_Ent_TeamData_Job extends Francis_Db_Row
{
    const JOB_STATUS_READY = 'READY';
    const JOB_STATUS_PROCESSING = 'PROCESSING';
    const JOB_STATUS_DONE = 'DONE';

    const JOB_NAME_DAILY_CLEANUP = 'dailyCleanup';
    const JOB_NAME_APPOINTMENT_REMINDER = 'appointmentReminder';

    /**
     * @param $refId
     * @return bool
     */
    public static function deleteByRefId( $refId )
    {
        $sql = 'DELETE FROM ' . self::getTable() . ' WHERE ref_id  = :ref_id';
        return self::execute( $sql, array( ':ref_id' => $refId ) );
    }

    /**
     * @param $nowDt
     * @return array
     */
    public static function getAllReadyAndExpiredJobs( \DateTime $nowDt )
    {
        $sql  = 'SELECT * FROM ' . self::getTable() . ' WHERE ';
        $sql .= 'job_status = :job_status AND ';
        $sql .= 'trigger_dt < :now_dt';
        $params = array(
            ':job_status' => self::JOB_STATUS_READY,
            ':now_dt' => $nowDt->format( 'Y-m-d H:i:s' )
        );
        return self::findMany( $sql, $params );
    }

    /**
     * @param DateTime $nowDt
     */
    public static function markAllForProcessing( \DateTime $nowDt )
    {
        $sql = 'UPDATE ' . self::getTable() . ' SET job_status = :job_status_inprogress ';
        $sql .= 'WHERE trigger_dt < :now_dt AND ';
        $sql .= 'job_status = :job_status_ready';

        $params = array(
            ':job_status_inprogress' => TB_Shared_Ent_TeamData_Job::JOB_STATUS_PROCESSING,
            ':job_status_ready' => TB_Shared_Ent_TeamData_Job::JOB_STATUS_READY,
            ':now_dt' => $nowDt->format( 'Y-m-d H:i:s' )
        );
        self::execute( $sql, $params );
    }

    /**
     * Delete all jobs which are status done
     */
    public static function cleanUp()
    {
        $sql = 'DELETE FROM ' . self::getTable() . ' WHERE job_status  = :job_status_done';
        return self::execute( $sql, array( ':job_status_done' => TB_Shared_Ent_TeamData_Job::JOB_STATUS_DONE ) );
    }

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

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