<?php

/**
 * kataoMemberDeposit actions.
 *
 * @package www.katao.fr
 * @subpackage kataoMemberDeposit
 * @author Your name here
 * @version SVN: $Id: actions.class.php 8507 2008-04-17 17:32:20Z fabien $
 */
class kataoMemberDepositActions extends wpActions {
    public function executeIndex() {
        $criteria = new Criteria();
        $criteria->addJoin(KataoMemberDepositPeer::KATAO_MEMBER_ID, KataoMemberPeer::ID);

        if ($this->getUser()->isJustDelegate()) {
            $criteria->add(KataoMemberPeer::KATAO_NODE_ID, $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId());
        }

        $sort_method = $this->getCriteriaSortMethod();
        switch ($this->sort = $this->getRequestParameter('sort', 'date')) {
            case 'member':
                $criteria->$sort_method(KataoMemberPeer::LAST_NAME);
                $criteria->$sort_method(KataoMemberPeer::FIRST_NAME);
                break;
            case 'amount':
                $criteria->$sort_method(KataoMemberDepositPeer::AMOUNT);
                break;
            case 'status':
                $criteria->$sort_method(KataoMemberDepositPeer::STATUS);
                break;
            case 'payment-mode':
                $criteria->$sort_method(KataoMemberDepositPeer::PAYMENT_MODE);
                break;
            default:
                $criteria->$sort_method(KataoMemberDepositPeer::VALUED_AT);
        }

        if ('' != $this->filter_member = $this->getUser()->getAttribute('katao_member_deposit_filter_member')) {
            $criteria->add(KataoMemberDepositPeer::KATAO_MEMBER_ID, $this->filter_member);
        }
        if ('' != $this->filter_currency = $this->getUser()->getAttribute('katao_member_deposit_filter_currency')) {
            $criteria->add(KataoMemberDepositPeer::CURRENCY, $this->filter_currency);
        }
        if ('' != $this->filter_payment_mode = $this->getUser()->getAttribute('katao_member_deposit_filter_payment_mode')) {
            $criteria->add(KataoMemberDepositPeer::PAYMENT_MODE, $this->filter_payment_mode);
        }
        if ('' != $this->filter_status = $this->getUser()->getAttribute('katao_member_deposit_filter_status')) {
            $criteria->add(KataoMemberDepositPeer::STATUS, $this->filter_status);
        }

        $pager = new sfPropelPager('KataoMemberDeposit', sfConfig::get('app_pager'));
        $pager->setPeerMethod('doSelectJoinKataoMember');
        $pager->setCriteria($criteria);
        $pager->setPage($this->getRequestParameter('page', 1));
        $pager->init();
        $this->pager = $pager;

        $this->katao_member_depositList = $pager->getResults();
    }

    public function executeFilter($request) {
        $this->getUser()->setAttribute('katao_member_deposit_filter_member', $request->getParameter('filter_member'));
        $this->getUser()->setAttribute('katao_member_deposit_filter_currency', $request->getParameter('filter_currency'));
        $this->getUser()->setAttribute('katao_member_deposit_filter_payment_mode', $request->getParameter('filter_payment_mode'));
        $this->getUser()->setAttribute('katao_member_deposit_filter_status', $request->getParameter('filter_status'));
        return $this->redirect('kataoMemberDeposit/index');
    }

    public function executeFilterReset($request) {
        $this->getUser()->setAttribute('katao_member_deposit_filter_member', '');
        $this->getUser()->setAttribute('katao_member_deposit_filter_currency', '');
        $this->getUser()->setAttribute('katao_member_deposit_filter_payment_mode', '');
        $this->getUser()->setAttribute('katao_member_deposit_filter_status', '');
        return $this->redirect('kataoMemberDeposit/index');
    }

    public function executeShow($request) {
        $this->katao_member_deposit = KataoMemberDepositPeer::retrieveByPk($request->getParameter('id'));
        $this->redirectWithErrorUnless($this->katao_member_deposit, 'Dépôt #' . $request->getParameter('id') . ' inconnu.');
    }

    public function executeCreate() {
        $this->form = new KataoMemberDepositForm();

        $this->setTemplate('edit');
    }

    public function executeEdit($request) {
        $katao_member_deposit = KataoMemberDepositPeer::retrieveByPk($request->getParameter('id'));

        if (!is_null($katao_member_deposit)) {
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $current_user_node_id = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
            $this->redirectWithErrorIf($is_just_delegate && $current_user_node_id != $katao_member_deposit->getKataoMember()->getKataoNodeId());
        }

        $this->form = new KataoMemberDepositForm($katao_member_deposit);
    }

    public function executeUpdate($request) {
        $this->redirectWithErrorUnless($request->isMethod('post'));

        $katao_member_deposit = KataoMemberDepositPeer::retrieveByPk($request->getParameter('id'));

        if (!is_null($katao_member_deposit)) {
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $current_user_node_id = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
            $this->redirectWithErrorIf($is_just_delegate && $current_user_node_id != $katao_member_deposit->getKataoMember()->getKataoNodeId());
        }

        $this->form = new KataoMemberDepositForm($katao_member_deposit);

        $this->form->bind($request->getParameter('katao_member_deposit'));
        if ($this->form->isValid()) {
            $katao_member_deposit = $this->form->save();

            wpFlashMessages::addConfirmation('Dépôt "' . $katao_member_deposit->getMemberName() . '" sauvé avec succès.');
            $this->redirect('kataoMemberDeposit/index');
        }

        $this->setTemplate('edit');
    }

    public function executeDelete($request) {
        $this->redirectWithErrorUnless($katao_member_deposit = KataoMemberDepositPeer::retrieveByPk($request->getParameter('id')), 'Dépôt #' . $request->getParameter('id') . ' inconnu.');

        $is_just_delegate = $this->getUser()->isJustDelegate();
        $current_user_node_id = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
        $this->redirectWithErrorIf($is_just_delegate && $current_user_node_id != $katao_member_deposit->getKataoMember()->getKataoNodeId());

        $katao_member_deposit->delete();

        wpFlashMessages::addConfirmation('Dépôt "' . $katao_member_deposit->getMemberName() . '" supprimé avec succès.');
        $this->redirect('kataoMemberDeposit/index');
    }

    public function executeDeleteMultiple($request) {
        if (!wpPersistenceManager::isEmpty('katao_member_deposit')) {
            $criteria = new Criteria();
            $criteria->add(KataoMemberDepositPeer::ID, array_keys(wpPersistenceManager::getSelectedItems('katao_member_deposit')), Criteria::IN);
            KataoMemberDepositPeer::doDelete($criteria);

            wpPersistenceManager::cleanSelection('katao_member_deposit');
            wpFlashMessages::addConfirmation('Les dépôts sélectionnés ont été supprimés avec succès.');
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins un dépôt.');
        }

        $this->redirect('kataoMemberDeposit/index');
    }

    public function executeDispatchSols($request) {
    }

    public function executeDispatchSolsUpdate($request) {
        $katao_member_ids = array();
        if ('member' == $request->getParameter('type') && '' != $request->getParameter('member')) {
            $katao_member_ids[] = $request->getParameter('member');
        } elseif (('node' == $request->getParameter('type') && '' != $request->getParameter('node')) || ('all' == $request->getParameter('type'))) {
            $criteria = new Criteria();
            $criteria->addSelectColumn(KataoMemberPeer::ID);
            $criteria->addJoin(KataoMemberPeer::ID, KataoUserPeer::KATAO_MEMBER_ID);
            if ('all' != $request->getParameter('type')) {
                $criteria->add(KataoMemberPeer::KATAO_NODE_ID, $request->getParameter('node'));
            }
            $criteria->add(KataoMemberPeer::IS_MEMBER, true);
            $criteria->add(KataoUserPeer::STATUS, KataoUser::STATUS_ACTIVE);

            $rs = KataoMemberPeer::doSelectRS($criteria);
            while ($rs->next()) {
                $katao_member_ids[] = $rs->getInt(1);
            }
        }

        if (0 < $katao_member_ids_count = count($katao_member_ids)) {
            if (0 < $amount = floor((int)$request->getParameter('amount') / $katao_member_ids_count)) {
                foreach ($katao_member_ids as $katao_member_id) {
                    $katao_member_deposit = new KataoMemberDeposit();
                    $katao_member_deposit->setKataoMemberId($katao_member_id);
                    $katao_member_deposit->setAmount($amount);
                    $katao_member_deposit->setCurrency(KataoMemberDeposit::CURRENCY_SOL);
                    $katao_member_deposit->setPaymentMode(KataoMemberDeposit::PAYMENT_MODE_OTHER);
                    $katao_member_deposit->setStatus(KataoMemberDeposit::STATUS_VALIDATED);
                    $katao_member_deposit->save();
                }
                wpFlashMessages::addConfirmation(sprintf('%d %s ont été répartis sur les %d adhérents.', $amount, wpConfig::getAdditionalCurrencyName(), $katao_member_ids_count));
            } else {
                wpFlashMessages::addWarning(sprintf('Impossible de répartir %d %s sur %s adhérents.', $request->getParameter('amount'), wpConfig::getAdditionalCurrencyName(), $katao_member_ids_count));
            }
        } else {
            wpFlashMessages::addWarning('Impossible de répartir les ' . wpConfig::getAdditionalCurrencyName() . ' sur aucun adhérent.');
        }

        return $this->redirect('kataoMemberDeposit/index');
    }

    public function validateDispatchSolsUpdate() {
        $return = true;

        if ('' == $this->getRequestParameter('amount')) {
            $this->getRequest()->setError('amount', 'Merci de saisir un montant');
            $return = false;
        }
        if ('' == $type = $this->getRequestParameter('type')) {
            $this->getRequest()->setError('type', 'Merci de choisir un type de bénéficiaire(s)');
            $return = false;
        }
        if ('member' == $type && '' == $this->getRequestParameter('member')) {
            $this->getRequest()->setError('member', 'Merci de sélectionner un adhérent');
            $return = false;
        }
        if ('node' == $type && '' == $this->getRequestParameter('node')) {
            $this->getRequest()->setError('node', 'Merci de sélectionner un noeud');
            $return = false;
        }

        return $return;
    }

    public function handleErrorDispatchSolsUpdate() {
        return $this->forward('kataoMemberDeposit', 'dispatchSols');
    }

    public function executePrintChecks($request) {
        if (wpPersistenceManager::isEmpty('katao_member_deposit')) {
            wpFlashMessages::addWarning('Merci de sélectionner au moins un dépôt.');
            return $this->redirect('kataoMemberDeposit/index');
        }

        $katao_member_deposits = array();

        $criteria = new Criteria();
        $criteria->add(KataoMemberDepositPeer::ID, array_keys(wpPersistenceManager::getSelectedItems('katao_member_deposit')), Criteria::IN);
        foreach (KataoMemberDepositPeer::doSelect($criteria) as/*(KataoMemberDeposit)*/ $katao_member_deposit) {
            if (KataoMemberDeposit::PAYMENT_MODE_CHECK == $katao_member_deposit->getPaymentMode()) {
                $katao_member_deposits[] = $katao_member_deposit;
            }
        }

        if (0 == count($katao_member_deposits)) {
            wpFlashMessages::addWarning('Merci de sélectionner au moins un dépôt sous forme de chèque.');
            return $this->redirect('kataoMemberDeposit/index');
        }

        if ($request->isMethod('post')) {
            $number = $request->getParameter('number');

            $sf_php_excel = new sfPhpExcel();

            $file_name = tempnam(sfConfig::get('sf_upload_dir'), 'excel_');

            $sf_php_excel->setActiveSheetIndex(0);

            $style_header = array(
                'font' => array(
                    'bold' => true,
                    'color' => array('argb' => PHPExcel_Style_Color::COLOR_WHITE),
                    ),
                'alignment' => array(
                    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
                    ),
                'borders' => array(
                    'top' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                        ),
                    'right' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                        ),
                    'bottom' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                        ),
                    'left' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                        ),
                    ),
                'fill' => array(
                    'type' => PHPExcel_Style_Fill::FILL_SOLID,
                    'startcolor' => array(
                        'argb' => 'FFA0A0A0',
                        ),
                    ),
                );
            $style_border = array(
                'borders' => array(
                    'top' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                        ),
                    'right' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                        ),
                    'bottom' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                        ),
                    'left' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                        ),
                    ),
                );

            $sf_php_excel->getActiveSheet()->mergeCells('A1:B1');
            $sf_php_excel->getActiveSheet()->setCellValue('A1', wpConfig::getName());

            $address = explode("\n", str_replace("\r", '', wpConfig::getAddress()));
            $sf_php_excel->getActiveSheet()->mergeCells('A2:B2');
            $sf_php_excel->getActiveSheet()->setCellValue('A2', !empty($address[0])?$address[0]:'');
            $sf_php_excel->getActiveSheet()->mergeCells('A3:B3');
            $sf_php_excel->getActiveSheet()->setCellValue('A3', !empty($address[1])?$address[1]:'');

            $sf_php_excel->getActiveSheet()->mergeCells('A4:B4');
            $sf_php_excel->getActiveSheet()->setCellValue('A4', sprintf('Tél : %s - %s', wpConfig::getPhone(), wpConfig::getEmail()));

            $sf_php_excel->getActiveSheet()->setCellValue('C3', 'Date');
            $sf_php_excel->getActiveSheet()->getStyle('C3')->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->setCellValue('D3', PHPExcel_Shared_Date::PHPToExcel(time()));
            $sf_php_excel->getActiveSheet()->getStyle('D3')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY);
            $sf_php_excel->getActiveSheet()->getStyle('D3')->applyFromArray($style_border);
            $sf_php_excel->getActiveSheet()->setCellValue('C4', 'Remise N°');
            $sf_php_excel->getActiveSheet()->getStyle('C4')->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->setCellValue('D4', $number);
            $sf_php_excel->getActiveSheet()->getStyle('D4')->applyFromArray($style_border);
            $sf_php_excel->getActiveSheet()->setCellValue('C5', 'Signature');
            $sf_php_excel->getActiveSheet()->getStyle('C5')->applyFromArray($style_header);

            $sf_php_excel->getActiveSheet()->setCellValue('A10', 'N° CHEQUE');
            $sf_php_excel->getActiveSheet()->getStyle('A10')->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->setCellValue('B10', 'PERSONNE/SOCIETE QUI VOUS A REMIS LE CHEQUE');
            $sf_php_excel->getActiveSheet()->getStyle('B10')->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->setCellValue('C10', 'BANQUE');
            $sf_php_excel->getActiveSheet()->getStyle('C10')->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->setCellValue('D10', 'MONTANT');
            $sf_php_excel->getActiveSheet()->getStyle('D10')->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->getStyle('D10')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);

            $index = 11;
            foreach ($katao_member_deposits as/*(KataoMemberDeposit)*/ $katao_member_deposit) {
                // mise à jour du numéro de remise de chèque
                $katao_member_deposit->setCheckDeposit($number);
                $katao_member_deposit->save();

                $sf_php_excel->getActiveSheet()->setCellValue('A' . $index, $katao_member_deposit->getCheckNumber());
                $sf_php_excel->getActiveSheet()->getStyle('A' . $index)->applyFromArray($style_border);
                $sf_php_excel->getActiveSheet()->getStyle('A' . $index)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                $sf_php_excel->getActiveSheet()->setCellValue('B' . $index, $katao_member_deposit->getKataoMember()->getFullName());
                $sf_php_excel->getActiveSheet()->getStyle('B' . $index)->applyFromArray($style_border);
                $sf_php_excel->getActiveSheet()->setCellValue('C' . $index, $katao_member_deposit->getCheckBank());
                $sf_php_excel->getActiveSheet()->getStyle('C' . $index)->applyFromArray($style_border);
                $sf_php_excel->getActiveSheet()->setCellValue('D' . $index, $katao_member_deposit->getAmount());
                $sf_php_excel->getActiveSheet()->getStyle('D' . $index)->applyFromArray($style_border);
                $sf_php_excel->getActiveSheet()->getStyle('D' . $index)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00);
                $sf_php_excel->getActiveSheet()->getStyle('D' . $index)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
                $index++;
            }

            $index++;
            $sf_php_excel->getActiveSheet()->setCellValue('A' . $index, 'BANQUE');
            $sf_php_excel->getActiveSheet()->getStyle('A' . $index)->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->setCellValue('B' . $index, 'RIB');
            $sf_php_excel->getActiveSheet()->getStyle('B' . $index)->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->setCellValue('C' . $index, 'NBR CHEQUES');
            $sf_php_excel->getActiveSheet()->getStyle('C' . $index)->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->getStyle('C' . $index)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
            $sf_php_excel->getActiveSheet()->setCellValue('D' . $index, 'TOTAL');
            $sf_php_excel->getActiveSheet()->getStyle('D' . $index)->applyFromArray($style_header);
            $sf_php_excel->getActiveSheet()->getStyle('D' . $index)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);

            $index++;
            $sf_php_excel->getActiveSheet()->setCellValue('A' . $index, wpConfig::getBankName());
            $sf_php_excel->getActiveSheet()->getStyle('A' . $index)->applyFromArray($style_border);
            $sf_php_excel->getActiveSheet()->setCellValue('B' . $index, wpConfig::getBankAccount());
            $sf_php_excel->getActiveSheet()->getStyle('B' . $index)->applyFromArray($style_border);
            $sf_php_excel->getActiveSheet()->setCellValue('C' . $index, count($katao_member_deposits));
            $sf_php_excel->getActiveSheet()->getStyle('C' . $index)->applyFromArray($style_border);
            $sf_php_excel->getActiveSheet()->setCellValue('D' . $index, '=SUM(D11:D' . (10 + count($katao_member_deposits)) . ')');
            $sf_php_excel->getActiveSheet()->getCell('D' . $index)->getCalculatedValue();
            $sf_php_excel->getActiveSheet()->getStyle('D' . $index)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
            $sf_php_excel->getActiveSheet()->getStyle('D' . $index)->applyFromArray($style_border);

            $sf_php_excel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
            $sf_php_excel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
            $sf_php_excel->getActiveSheet()->getColumnDimension('B')->setWidth(41);
            $sf_php_excel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
            $sf_php_excel->getActiveSheet()->getColumnDimension('D')->setWidth(10);

            $sf_php_excel->setActiveSheetIndex(0);

            $php_excel_writer = new PHPExcel_Writer_Excel5($sf_php_excel);
            $php_excel_writer->save($file_name);

            $file_content = file_get_contents($file_name);

            $response = $this->getResponse();
            $response->setContentType('application/vnd.ms-excel');
            $response->setHttpHeader('Content-disposition', 'attachment; filename="remise-chèques-' . $number . '.xls"');
            // $response->setHttpHeader('Content-Length', strlen($file_content));
            $response->setHttpHeader('Pragma', 'public');
            $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
            $response->setHttpHeader('Expires', '0');
            $response->setContent($file_content);
            return sfView::NONE;
        }
    }

    public function executeTransferSol($request) {
        $this->form = new KataoMemberDepositTransferSolForm();
    }

    public function executeTransferSolUpdate($request) {
        $this->redirectWithErrorUnless($request->isMethod('post'));

        $this->form = new KataoMemberDepositTransferSolForm();

        $parameters = $request->getParameter('katao_member_deposit');
        $this->form->bind($parameters);
        if ($this->form->isValid()) {
            $valued_at = time();
            if (!empty($parameters['valued_at']) && preg_match('|(\d{2})\/(\d{2})\/(\d{4})|si', $parameters['valued_at'], $matches)) {
                $valued_at = mktime(12, 0, 0, (int)$matches[2], (int)$matches[1], (int)$matches[3]);
            }

            $katao_member_deposit = new KataoMemberDeposit();
            $katao_member_deposit->setKataoMemberId($parameters['katao_member_1_id']);
            $katao_member_deposit->setAmount(- $parameters['amount']);
            $katao_member_deposit->setCurrency(KataoMemberDeposit::CURRENCY_SOL);
            $katao_member_deposit->setPaymentMode(KataoMemberDeposit::PAYMENT_MODE_TRANSFER_SOL);
            $katao_member_deposit->setStatus(KataoMemberDeposit::STATUS_VALIDATED);
            $katao_member_deposit->setValuedAt($valued_at);
            $katao_member_deposit->save();

            $katao_member_deposit = new KataoMemberDeposit();
            $katao_member_deposit->setKataoMemberId($parameters['katao_member_2_id']);
            $katao_member_deposit->setAmount($parameters['amount']);
            $katao_member_deposit->setCurrency(KataoMemberDeposit::CURRENCY_SOL);
            $katao_member_deposit->setPaymentMode(KataoMemberDeposit::PAYMENT_MODE_TRANSFER_SOL);
            $katao_member_deposit->setStatus(KataoMemberDeposit::STATUS_VALIDATED);
            $katao_member_deposit->setValuedAt($valued_at);
            $katao_member_deposit->save();

            wpFlashMessages::addConfirmation('Transfert de ' . wpConfig::getAdditionalCurrencyName() . ' effectué avec succès.');
            $this->redirect('kataoMemberDeposit/index');
        }

        $this->setTemplate('transferSol');
    }
}