<?php

class OffersController extends Controller
{
    /**
     * Construct this object by extending the basic Controller class
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     */
    public function index()
    {
        $this->View->render('offers',array(
            'type' => 1
        ));
    }

    public function requests()
    {
        $this->View->render('offers',array(
            'type' => 2
        ));
    }

    public function view($offer_id)
    {
        if (!is_numeric($offer_id)) {
            $offer_id = OfferModel::getOfferIdBySlug($offer_id);
        }
        $offer = OfferModel::getOffer($offer_id);
        if (isset($offer->title) && $offer->title != '') {
            View::set($offer->profile_id);
            $this->View->render('offer', array(
                'offer' => $offer,
                'profile' => UserProfileModel::getUserProfile($offer->profile_id))
            );
        } else {
            $this->View->render('404');
        }
    }

    public function add($profile_id = null)
    {
        Auth::checkAuthentication();
        if ($profile_id === null)
        {
            $profiles = UserProfileModel::getUserProfilesByUserId(Session::get('user_id'));
            $profile_id = $profiles[0]->id;
        }
        UserProfileModel::checkCompletion($profile_id);
        $this->View->renderAdmin('editOffer', array(
            'offer' => OfferModel::getEmptyOffer($profile_id),
            'profile' => UserProfileModel::getUserProfile($profile_id))
        );
    }

    public function edit($offer_id = null)
    {
        Auth::checkAuthentication();
        OfferModel::checkOwnership($offer_id);
        $offer = OfferModel::getOffer($offer_id);
        $this->View->renderAdmin('editOffer', array(
            'offer' => $offer,
            'profile' => UserProfileModel::getUserProfile($offer->profile_id))
        );
    }

    public function save_action($offer_id = null)
    {
        Auth::checkAuthentication();
        OfferModel::checkOwnership($offer_id);
        OfferModel::saveOffer($offer_id);
        Redirect::to('offers/view/'.$offer_id);
    }
}
