<?php
/**
 * Class represents records from table helpdesk_ticket
 * {autogenerated}
 * @property int $ticket_id 
 * @property string $ticket_mask 
 * @property int $user_id 
 * @property string $status enum('new','awaiting_user_response','awaiting_admin_response','closed')
 * @property string $subject 
 * @property datetime $created 
 * @property datetime $updated 
 * @see Am_Table
 */
class HelpdeskTicket extends Am_Record {

    const STATUS_NEW = 'new';
    const STATUS_AWAITING_USER_RESPONSE = 'awaiting_user_response';
    const STATUS_AWAITING_ADMIN_RESPONSE = 'awaiting_admin_response';
    const STATUS_CLOSED = 'closed';

    protected $_key = 'ticket_id';
    protected $_table = '?_helpdesk_ticket';
    private $state = null;

    public static function getStatusOptions()
    {
        return array (
            'new' => ___('New'),
            'awaiting_admin_response' => ___('Awaiting Admin Response'),
            'awaiting_user_response' => ___('Awaiting User Response'),
            'closed' => ___('Closed')
        );
    }

    public function getMessages()
    {
        return $this->getDi()->helpdeskMessageTable->findBy(
            array('ticket_id'=>$this->pk()), 
            null, null, "dattm DESC");
    }

    public function getUser()
    {
        return $this->getDi()->userTable->load($this->user_id);
    }
    
    protected function _generateMask()
    {
        if (!empty($this->ticket_mask)) return;
        $this->ticket_mask = 
            $this->getDi()->app->generateRandomString(3, 'ABCDEFGJIKLMNOPQRSTUVWXYZ') 
            . '-' . rand(100000, 999999);
    }
    /**
     * before record insertion generate new ticket mask. if the mask is generated, try
     * 20 times to generate new mask, then throw exception
     * @return type 
     */
    public function insert($reload = true)
    {
        $maxAttempts = 20;
        for ($i = 0; $i <= $maxAttempts; $i++)
        {
            try {
                $this->_generateMask();
                return parent::insert($reload);
            } catch (Am_Exception_Db_NotUnique $e) {
                if ($i >= $maxAttempts)
                    throw new Am_Exception_InternalError("Could not generate new ticket mask after [$i] attempts");
                $this->ticket_mask = null;
            }
        }   
    }

    public function  delete()
    {
        $this->deleteFromRelatedTable('?_helpdesk_message');
        parent::delete();
    }
}

class HelpdeskTicketTable extends Am_Table {
    protected $_key = 'ticket_id';
    protected $_table = '?_helpdesk_ticket';
    protected $_recordClass = 'HelpdeskTicket';
    
    public function insert(array $values, $returnInserted = false)
    {
        if (empty($values['created']))
            $values['created'] = $this->getDi()->sqlDateTime;
        return parent::insert($values, $returnInserted);
    }
    
    public function load($keyOrTicketId, $throwExceptions = true)
    {
        if (preg_match('/^\d+$/', trim($keyOrTicketId), $matches))
            return parent::load($matches[0], $throwExceptions);
        else {
            $keyOrTicketId = filterId($keyOrTicketId);
            $found = $this->findFirstByTicketMask($keyOrTicketId);
            if (!$found && $throwExceptions)
                throw new Am_Exception_InternalError("Ticket with mask [$keyOrTicketId] not found");
            return $found;
        }
    }

    public function clearOld($date)
    {
        foreach($this->findByUpdated('<' . $date) AS $ticket)
        {
            $ticket->delete();
        }

    }
}
