<?php

class api10Actions extends sfActions {
    protected $outputFormat = null;
    protected $outputSerializer = null;

    public function executeIndex($request)
    {
        try {
            $this->checkOutputFormat($request->getParameter('output'));
            $this->checkApiKey($request->getParameter('apikey'));
            //region check Method
            $method = $request->getParameter('method');
            if (empty($method)) {
                throw new Exception('Missing method parameter');
            }
            if (!method_exists($this, $method)) {
                throw new Exception(sprintf('Unable to find requested method: %s', $method));
            }
            $availableMethods = array();
            $availableMethods[] = 'getAmount';
            $availableMethods[] = 'addPaypalDepot';
            $availableMethods[] = 'getGmapData';
            $availableMethods[] = 'getSupplierDetails';
            $availableMethods[] = 'getSupplierCategories';
            if (!in_array($method, $availableMethods)) {
                throw new Exception(sprintf('Unknown method: %s', $method));
            }
            //endregion

            $this->renderResult($this->$method($request), 200);
        }
        catch(Exception $e) {
            $this->renderResult($e->getMessage(), 500);
        }
        return sfView::NONE;
    }

    protected function logCall($message)
    {
        $this->logMessage($message, 'debug');
    }

    protected function checkOutputFormat($outputFormat)
    {
        if (null == $outputFormat) {
            $outputFormat = 'php';
        }
        $outputFormat = strtolower($outputFormat);

        $supportedFormat = array('php' => 'serialize');
        if (!isset($supportedFormat[$outputFormat])) {
            throw new Exception(sprintf('Unsupported output type: %s. Supported format: %s', $output, implode(', ', $supportedFormat)));
        }
        $this->outputSerializer = $supportedFormat[$outputFormat];
        return true;
    }

    protected function renderResult($result, $statusCode)
    {
        $this->getResponse()->setStatusCode($statusCode);

        sfConfig::set('sf_web_debug', false);
        if (null == $this->outputSerializer) {
            // $this->result = $result;
            $this->renderText($result);
            return true;
        }
        if (is_string($this->outputSerializer) || is_array($this->outputSerializer)) {
            // $this->result = call_user_func($this->outputSerializer, $result);
            $this->renderText(call_user_func($this->outputSerializer, $result));
            return true;
        }
        throw new Exception(sprintf('Unknown output serializer: %s', serialize($this->outputSerializer)));
    }

    protected function arrayToString($array)
    {
        $result = array();
        foreach($array as $key => $value) {
            $result[] = sprintf('%s => %s', $key, is_array($value)?$this->arrayToString($value):$value);
        }
        return 'array(' . implode(', ', $result) . ')';
    }

    public function checkApiKey($apikey)
    {
        if (empty($apikey)) {
            throw new Exception('apikey parameter is missing');
        }
        if ($apikey != sfConfig::get('app_api_key')) {
            throw new Exception(sprintf('Invalid API key: %s', $apikey));
        }
        return true;
    }

    protected function getAmount($request)
    {
        $this->logCall('getAmount()');

        //region arguments
        $user_id = $request->getParameter('user_id', false);
        //endregion

        $return = false;
        $criteria = new Criteria();
        $criteria->add(KataoUserPeer::ID, $user_id);
        $katao_user = KataoUserPeer::doSelectOne($criteria);

        if ($katao_user) {
            $katao_member = $katao_user->getKataoMember();
            $current_amount_euro = $katao_member->getCurrentAmountEuro();
            $current_amount_sol = $katao_member->getCurrentAmountSol();

            $return = sprintf('<p>Votre solde est de :<br />%s et %s</p>', Utils::formatCurrencyEuro($current_amount_euro), Utils::formatCurrencySol($current_amount_sol));
        }

        return $return;
    }

    protected function getAddPaypalDepot($request)
    {
        $this->logCall('getAddPaypalDepot()');

        //region arguments
        $member_id = $request->getParameter('member_id', false);
        $amount = $request->getParameter('amount', false);
        $message = $request->getParameter('message', false);
        //endregion

        $depot = KataoMemberDepositPeer::addPaypalDepot($member_id, $amount, $message);

        return true;
    }

    protected function getGmapData($request)
    {
        $this->logCall('getGmapData()');

        $display_soliste = $request->getParameter('display_soliste', false);
        $do_select_members = $request->getParameter('do_select_members', true);
        $selected_categories = $request->getParameter('selected_categories', array());
        $search_words = $request->getParameter('search_words', '');

        if ($display_soliste && $do_select_members) {
            $data['member'] = array();

            $criteria = new Criteria();
            $criteria->add(KataoUserPeer::GMAP_LAT, '', Criteria::NOT_EQUAL);
            $criteria->add(KataoUserPeer::GMAP_LNG, '', Criteria::NOT_EQUAL);
            $criteria->addJoin(KataoUserPeer::KATAO_MEMBER_ID, KataoMemberPeer::ID);

            if ($search_words != '') {
                $cton1 = $c->getNewCriterion(KataoMemberPeer::FIRST_NAME, sprintf('%%%s%%', $search_words), Criteria::LIKE);
                $cton2 = $c->getNewCriterion(KataoMemberPeer::LAST_NAME, sprintf('%%%s%%', $search_words), Criteria::LIKE);
                $cton1->addOr($cton2);
                $criteria->add($cton1);
            }

            $members = KataoUserPeer::doSelectJoinKataoMember($criteria);
            foreach($members as/*(KataoUser)*/ $objectInstance) {
                $data['member']['member'][] = $objectInstance->toArray();
            }
        }

        $data['prestataire'] = array();
        $ids = array();

        $suppliers = array();
        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoSupplierPeer::ID);
        $criteria->addSelectColumn(KataoSupplierPeer::NAME);
        $criteria->addSelectColumn(KataoSupplierPeer::URL_IDENTIFIER);
        $criteria->addSelectColumn(KataoSupplierPeer::ORDER_MIN_AMOUNT);
        $criteria->addSelectColumn(KataoUserPeer::STATUS);
        $criteria->add(KataoSupplierPeer::IS_GLOBAL, true);
        $criteria->addJoin(KataoSupplierPeer::ID, KataoUserPeer::KATAO_SUPPLIER_ID);
        $criteria->addJoin(KataoSupplierProductCategoryPeer::KATAO_SUPPLIER_ID, KataoSupplierPeer::ID);
        $criteria->addAscendingOrderByColumn(KataoSupplierPeer::NAME);

        if (!empty($selected_categories)) {
            $criteria->add(KataoSupplierProductCategoryPeer::KATAO_PRODUCT_CATEGORY_ID, $selected_categories, Criteria::IN);
        }

        if ($search_words != '') {
            $criteria->add(KataoSupplierPeer::NAME, sprintf('%%%s%%', $search_words), Criteria::LIKE);
        }

        $rs = KataoSupplierPeer::doSelectRS($criteria);
        while ($rs->next()) {
            $suppliers[$rs->getString(2)] = array('id' => $rs->getInt(1), 'url' => $rs->getString(3), 'order_min_amount' => $rs->getFloat(4), 'status' => $rs->getInt(5));
        }

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoSupplierPeer::ID);
        $criteria->addSelectColumn(KataoSupplierPeer::NAME);
        $criteria->addSelectColumn(KataoSupplierPeer::URL_IDENTIFIER);
        $criteria->addSelectColumn(KataoSupplierPeer::ORDER_MIN_AMOUNT);
        $criteria->addSelectColumn(KataoUserPeer::STATUS);
        $criteria->addJoin(KataoSupplierPeer::ID, KataoSupplierNodePeer::KATAO_SUPPLIER_ID);
        $criteria->addJoin(KataoSupplierPeer::ID, KataoUserPeer::KATAO_SUPPLIER_ID);
        $criteria->addJoin(KataoSupplierProductCategoryPeer::KATAO_SUPPLIER_ID, KataoSupplierPeer::ID);
        $criteria->add(KataoSupplierPeer::IS_GLOBAL, false);
        $criteria->addAscendingOrderByColumn(KataoSupplierPeer::NAME);

        if ($search_words != '') {
            $criteria->add(KataoSupplierPeer::NAME, sprintf('%%%s%%', $search_words), Criteria::LIKE);
        }

        if (!empty($selected_categories)) {
            $criteria->add(KataoSupplierProductCategoryPeer::KATAO_PRODUCT_CATEGORY_ID, $selected_categories, Criteria::IN);
        }

        $rs = KataoSupplierPeer::doSelectRS($criteria);
        while ($rs->next()) {
            $suppliers[$rs->getString(2)] = array('id' => $rs->getInt(1), 'url' => $rs->getString(3), 'order_min_amount' => $rs->getFloat(4), 'status' => $rs->getInt(5));
        }

        ksort($suppliers);

        $return = array();
        foreach ($suppliers as $supplier_name => $supplier_data) {
            $supplier_data['name'] = $supplier_name;
            $return[$supplier_data['id']] = $supplier_data;
        }

        $ids = $return;
        foreach (KataoSupplierPeer::retrieveByPKs(array_keys($ids)) as $objectInstance) {
            $tab = $objectInstance->toArray();

            $tab['FullAdress'] = $objectInstance->getFullAdress();

            unset($tab['Presentation']);

            $supplier = $objectInstance->getFirstKataoUser();
            if (KataoUser::STATUS_ACTIVE == $supplier->getStatus()) {
            		$categories = $objectInstance->getKataoSupplierProductCategorys();
            		$temp = array();
								foreach ($categories as /*(KataoSupplierProductCategory)*/$cat){
            			$temp[$cat->getKataoProductCategoryId()] = $cat->getKataoProductCategory()->getName();
            		}
                $tab['sol_cat'] = $temp;

								$category =/*(KataoSupplierProductCategory)*/ array_shift($objectInstance->getKataoSupplierProductCategorys()) ;
                $data['prestataire'][$category->getKataoProductCategoryId()][] = $tab;
            }
        }

        ksort($data['prestataire']);

        return $data;
    }

    protected function getSupplierDetails($request)
    {
        $this->logCall('getSupplierDetails()');

        //region arguments
        $id = $request->getParameter('id', false);
        //endregion

        $katao_supplier = KataoSupplierPeer::retrieveByUrlIdentifier($id);
        if ($katao_supplier == null) {
            return false;
        }

        if (!$katao_supplier->isVisible()) {
            return false;
        }

        return $katao_supplier->toArray();
    }

    protected function getSupplierCategories()
    {
        $this->logCall('getSupplierCategories()');

        $criteria = new Criteria();
        $criteria->add(KataoProductCategoryPeer::ID, 16, Criteria::NOT_EQUAL);
        $categories = KataoProductCategoryPeer::doSelect($criteria);;

        $data = array();
        foreach($categories as/*(KataoProductCategory)*/ $objectInstance) {
            $data[$objectInstance->getId()] = $objectInstance->getName();
        }
       return $data;
    }
}