<?php

/**
 * mailing actions.
 *
 * @package www.katao.fr
 * @subpackage mailing
 * @author Your name here
 * @version SVN: $Id: actions.class.php 9301 2008-05-27 01:08:46Z dwhittle $
 */
class mailingActions extends sfActions {
    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex($request)
    {
        $this->group_list = KataoMemberGroupPeer::getAllGroupsObject();
        $this->form = new KataoMemberMailingForm();
    }

    public function executeSave($request)
    {
        $this->form = new KataoMemberMailingForm();

        $groupIds = $request->getParameter('katao_member_mailing');
        if ($request->isMethod('post')) {
            if (count($groupIds) == 0) {
            	wpFlashMessages::addError('Vous devez sélectionner au moins un groupe');
            	$this->redirect('@katao_member_mailing');
            }

            $criteria = new Criteria();
            $criteria->addJoin(KataoMemberPeer::ID, KataoAssocMemberGroupPeer::MEMBER_ID);
            $criteria->add(KataoAssocMemberGroupPeer::GROUP_ID, $groupIds, Criteria::IN);
            $criteria->setDistinct();

            // Remplissage du tableau Excel
            $excel = new sfPhpExcel();
            $excel->setActiveSheetIndex(0);
        	$sheet = $excel->getActiveSheet();
			$position = 1;
        	$sheet->setCellValue('A'.$position, 'Prénom');
        	$sheet->setCellValue('B'.$position, 'Nom');
        	if ($user) {
        		$sheet->setCellValue('C'.$position, 'Email');
        	}
        	$position++;

            foreach(KataoMemberPeer::doSelect($criteria) as  $member) {
                $sheet->setCellValue('A'.$position, $member->getFirstName());
                $sheet->setCellValue('B'.$position, $member->getLastName());
            	$user = KataoUserPeer::retrieveByKataoMemberId($member->getId());
            	if ($user) {
                    $sheet->setCellValue('C'.$position, $user->getEmail());
                }
            	$position++;
            }
            // Téléchargement du fichier
            $tmp_filename = tempnam(sys_get_temp_dir(), 'mailing');

            $objWriter = new PHPExcel_Writer_Excel5($excel);
            $objWriter->save($tmp_filename);

            $response = $this->getResponse();
            $response->setContentType('application/vnd.ms-excel');
            $response->setHttpHeader('Content-disposition', 'attachment; filename="liste.xls"');
            $response->setHttpHeader('Pragma', 'public');
            $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
            $response->setHttpHeader('Expires', '0');
            $response->setContent(file_get_contents($tmp_filename));
            unlink($tmp_filename);

            return sfView::NONE;
        }
    }
}