<?php
class Plugg_User_Main_Identity_Friend_Request_Confirm extends Sabai_Application_Controller
{
    protected function _doExecute(Sabai_Application_Context $context)
    {
        $request = $this->_parent->getRequestedFriendRequest($context);
        $identity = $this->_parent->getRequestedUserIdentity($context);
        $url = array(
            'base' => '/user',
            'path' => '/' . $identity->getId(),
            'params' => array('tab_id' => $context->request->getAsInt('tab_id'))
        );

        if ($request->isPending() || $request->isConfirmed() || !$request->isOwnedBy($identity)) {
            $context->response->setError($context->plugin->_('Invalid request'), $url);
            return;
        }

        $form = $this->_getForm($context, $request);
        if ($form->validate()) {
            $request->setConfirmed();
            if ($request->commit()) {
                $message = $context->plugin->_('Friend request confirmed successfully.');
                $context->response->setSuccess($message, $url);
                return;
            }
        }

        $context->response->setPageInfo($context->plugin->_('Confirm a friend request'));
        $context->response->setVars(array('request_form' => &$form));
    }

    function _getForm(Sabai_Application_Context $context, $request)
    {
        $to_user = $this->locator->getService('UserIdentityFetcher')->fetchUserIdentity($request->get('to'));
        $form = $request->toHTMLQuickForm();
        $form->removeElementsAll();
        $form->addElement(
            'static',
            '',
            $context->plugin->_('Request sent to'),
            sprintf(
                '<a href="%3$s" title="%1$s"><img alt="" src="%2$s" width="32" /></a>',
                $to_user->getUsername(),
                $to_user->getImage(),
                $this->url->create(array('base' => '/user', 'path' => '/' . $to_user->getId()))
            )
        );
        $form->addElement('static', '', $context->plugin->_('Message'), h($request->get('message')));
        $result = $request->isAccepted() ? $context->plugin->_('Accepted') : $context->plugin->_('Rejected');
        $form->addElement('static', '', $context->plugin->_('Result'), $result);
        $form->addSubmitButtons(
            $context->plugin->_('Confirm'),
            sprintf(
                '<a href="%s">%s</a>',
                $this->url->create(array(
                    'base' => '/user',
                    'params' => array('tab_id' => $context->request->getAsInt('tab_id'))
                )),
                $context->plugin->_('Cancel')
            )
        );
        $form->useToken();
        return $form;
    }
}