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

        $form = $this->_getForm($context, $friend);
        if ($form->validate()) {
            // Remove pairs
            $friend->markRemoved();
            $model = $context->plugin->getModel();
            $friends = $model->Friend
                ->criteria()
                ->with_is($identity->getId())
                ->fetchByUser($friend->get('with'));
            foreach ($friends as $friend_pair) {
                $friend_pair->markRemoved();
            }

            if ($model->commit()) {
                $message = $context->plugin->_('Friend removed successfully.');
                $context->response->setSuccess($message, $url);
                return;
            }
        }

        $context->response
            ->setPageInfo($context->plugin->_('Remove a friend'))
            ->setVars(array('friend_form' => $form));
    }

    function _getForm(Sabai_Application_Context $context, $friend)
    {
        $with_user = $this->locator->getService('UserIdentityFetcher')->fetchUserIdentity($friend->get('with'));
        $form = $friend->toHTMLQuickForm();
        $form->removeElementsAll();
        $form->addElement('static', '', $context->plugin->_('Friend'), sprintf('<a href="%3$s" title="%1$s"><img alt="" src="%2$s" width="32" /></a> %1$s', h($with_user->getUsername()), $with_user->getImage(), $this->url->create(array('base' => '/user', 'path' => '/' . $with_user->getId()))));
        $form->addSubmitButtons($context->plugin->_('Remove friend'), 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;
    }
}