<?php

/**
 * kataoInvoice actions.
 *
 * @package www.katao.fr
 * @subpackage kataoInvoice
 * @author Your name here
 * @version SVN: $Id: actions.class.php 8507 2008-04-17 17:32:20Z fabien $
 */
class kataoInvoiceActions extends wpActions {
    public function preExecute() {
        parent::preExecute();
        sfLoader::loadHelpers(array('Asset', 'Tag', 'Url'));
    }

    public function executeIndex() {
        $criteria = new Criteria();
        $criteria->addJoin(KataoInvoicePeer::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 'no':
                $criteria->$sort_method(KataoInvoicePeer::ID);
                break;
            case 'status':
                $criteria->$sort_method(KataoInvoicePeer::STATUS);
                break;
            case 'member':
                $criteria->$sort_method(KataoInvoicePeer::MEMBER_LAST_NAME);
                $criteria->$sort_method(KataoInvoicePeer::MEMBER_FIRST_NAME);
                break;
            default:
                $criteria->$sort_method(KataoInvoicePeer::CREATED_AT);
        }

        if ('' != $this->filter_status = $this->getUser()->getAttribute('katao_invoice_filter_status')) {
            $criteria->add(KataoInvoicePeer::STATUS, $this->filter_status);
        }
        if ('' != $this->filter_member = $this->getUser()->getAttribute('katao_invoice_filter_member')) {
            $criteria->add(KataoInvoicePeer::KATAO_MEMBER_ID, $this->filter_member);
        }
        if ('' != $this->filter_node = $this->getUser()->getAttribute('katao_invoice_filter_node')) {
            $criteria->add(KataoInvoicePeer::KATAO_NODE_ID, $this->filter_node);
        }
        if ('' != $this->filter_period = $this->getUser()->getAttribute('katao_invoice_filter_period', KataoPeriodPeer::getActivePeriod()->getId())) {
            $criteria->add(KataoInvoicePeer::KATAO_PERIOD_ID, $this->filter_period);
        }

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

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

    public function executeFilter($request) {
        $this->getUser()->setAttribute('katao_invoice_filter_status', $request->getParameter('filter_status'));
        $this->getUser()->setAttribute('katao_invoice_filter_member', $request->getParameter('filter_member'));
        $this->getUser()->setAttribute('katao_invoice_filter_node', $request->getParameter('filter_node'));
        $this->getUser()->setAttribute('katao_invoice_filter_period', $request->getParameter('filter_period'));
        return $this->redirect('kataoInvoice/index');
    }

    public function executeFilterReset($request) {
        $this->getUser()->setAttribute('katao_invoice_filter_status', '');
        $this->getUser()->setAttribute('katao_invoice_filter_member', '');
        $this->getUser()->setAttribute('katao_invoice_filter_node', '');
        $this->getUser()->setAttribute('katao_invoice_filter_period', KataoPeriodPeer::getActivePeriod()->getId());
        return $this->redirect('kataoInvoice/index');
    }

    public function executeShow($request) {
        $this->katao_invoice = KataoInvoicePeer::retrieveByPk($request->getParameter('id'));
        $this->redirectWithErrorUnless($this->katao_invoice, 'Facture #' . $request->getParameter('id') . ' inconnue.');
    }

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

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

    public function executeEdit($request) {
        $this->form = new KataoInvoiceForm(KataoInvoicePeer::retrieveByPk($request->getParameter('id')));
    }

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

        $this->form = new KataoInvoiceForm(KataoInvoicePeer::retrieveByPk($request->getParameter('id')));

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

            wpFlashMessages::addConfirmation('Facture "' . $katao_invoice->getNumber() . '" sauvée avec succès.');
            $this->redirect('kataoInvoice/index');
        }

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

    public function executeDelete($request) {
        $this->redirectWithErrorUnless($katao_invoice = KataoInvoicePeer::retrieveByPk($request->getParameter('id')), 'Facture #' . $request->getParameter('id') . ' inconnue.');

        $katao_invoice->delete();

        wpFlashMessages::addConfirmation('Facture "' . $katao_invoice->getNumber() . '" supprimée avec succès.');
        $this->redirect('kataoInvoice/index');
    }

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

            wpPersistenceManager::cleanSelection('katao_invoice');
            wpFlashMessages::addConfirmation('Les factures sélectionnées ont été supprimées avec succès.');
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins une facture.');
        }

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

    public function executeExportPDF($request) {
        $this->redirectWithErrorUnless($katao_invoice = KataoInvoicePeer::retrieveByPk($request->getParameter('id')), 'Facture #' . $request->getParameter('id') . ' inconnue.');

        $content = $katao_invoice->generatePDF();

        $response = $this->getResponse();
        $response->setContentType('application/pdf');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="' . $katao_invoice->getNumber() . '.pdf"');
        $response->setHttpHeader('Content-Length', strlen($content));
        $response->setHttpHeader('Pragma', 'public');
        $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
        $response->setHttpHeader('Expires', '0');
        $response->setContent($content);
        return sfView::NONE;
    }

    public function executeSend($request) {
        $this->redirectWithErrorUnless($katao_invoice = KataoInvoicePeer::retrieveByPk($request->getParameter('id')), 'Facture #' . $request->getParameter('id') . ' inconnue.');

        $this->sendInvoice($katao_invoice);

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

    public function executeSendMultiple($request) {
        if (!wpPersistenceManager::isEmpty('katao_invoice')) {
            foreach (KataoInvoicePeer::retrieveByPKs(array_keys(wpPersistenceManager::getSelectedItems('katao_invoice'))) as $katao_invoice) {
                $this->sendInvoice($katao_invoice);
            }

            wpPersistenceManager::cleanSelection('katao_invoice');
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins une facture.');
        }

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

    protected function sendInvoice(KataoInvoice $katao_invoice) {
        try {
            if ('' != $katao_invoice->getMemberEmail()) {
                $content = $katao_invoice->generatePDF();

                $mailer = new wpMail();

                $message = new Swift_Message('Facture Katao');
                $message->attach(new Swift_Message_Part(sprintf('%s,

Suite à la dernière distribution de la periode %s, tu trouveras ci-joint ta facture.

Tu peux consulter ton compte et tes opérations à cette adresse :
%smon-profil
%s', $katao_invoice->getMemberFirstName(), $katao_invoice->getKataoPeriod()->getName(), sfConfig::get('app_katao_frontend_url'), Utils::getKataoEmailFooter())));
                $message->attach(new Swift_Message_Attachment($content, sprintf('%s.pdf', $katao_invoice->getNumber()), 'application/pdf'));

                $mailer->send($message, new Swift_Address($katao_invoice->getMemberEmail(), sprintf('%s %s', $katao_invoice->getMemberFirstName(), $katao_invoice->getMemberLastName())), sfConfig::get('app_mail_from'));
                $mailer->disconnect();

                wpFlashMessages::addConfirmation('Facture "' . $katao_invoice->getNumber() . '" envoyée avec succès.');
            } else {
                wpFlashMessages::addInformation('Facture "' . $katao_invoice->getNumber() . '" non envoyée car cet adhérent n\'a pas d\'email. Merci de bien vouloir l\'exporter et la lui envoyer ou faxer.');
            }

            if (KataoInvoice::STATUS_VALIDATED == $katao_invoice->getStatus()) {
                $katao_invoice->setStatus(KataoInvoice::STATUS_SENT);
                $katao_invoice->save();
            }
        }
        catch (Exception $e) {
            $mailer->disconnect();
            wpFlashMessages::addError('Impossible d\'envoyer la facture ' . $katao_invoice->getNumber() . '.');
        }
    }

    public function executeExportPDFAll($request) {
        $criteria = new Criteria();
        if ($this->getUser()->isJustDelegate()) {
            $criteria->addJoin(KataoInvoicePeer::KATAO_MEMBER_ID, KataoMemberPeer::ID);
            $criteria->add(KataoMemberPeer::KATAO_NODE_ID, $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId());
        }
        $criteria->addAscendingOrderByColumn(KataoInvoicePeer::ID);
        return $this->exportInvoicesToPDF(KataoInvoicePeer::doSelect($criteria));
    }

    public function executeExportPDFSelected($request) {
        if (!wpPersistenceManager::isEmpty('katao_invoice')) {
            $criteria = new Criteria();
            $criteria->add(KataoInvoicePeer::ID, array_keys(wpPersistenceManager::getSelectedItems('katao_invoice')), Criteria::IN);
            $criteria->addAscendingOrderByColumn(KataoInvoicePeer::ID);
            return $this->exportInvoicesToPDF(KataoInvoicePeer::doSelect($criteria));
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins une facture.');
            $this->redirect('kataoInvoice/index');
        }
    }

    protected function exportInvoicesToPDF($katao_invoices) {
        $file = tempnam('tmp', 'zip');
        $archive = new ZipArchive();
        $archive->open($file, ZipArchive::OVERWRITE);

        foreach ($katao_invoices as/*(KataoInvoice)*/ $katao_invoice) {
            $archive->addFromString($katao_invoice->getNumber() . '.pdf', $katao_invoice->generatePDF());
        }

        $archive->close();

        $response = $this->getResponse();
        $response->setContentType('application/zip');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="KATAO_Factures_Adhérents_' . date('Y-m-d') . '.zip"');
        $response->setHttpHeader('Content-Length', filesize($file));
        $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($file));
        return sfView::NONE;
    }

    public function executeDeliver($request) {
        $this->redirectWithErrorUnless($this->katao_invoice = KataoInvoicePeer::retrieveByPk($request->getParameter('id')), 'Facture #' . $request->getParameter('id') . ' inconnue.');

        if ($request->isMethod('POST')) {
            foreach ($request->getParameter('quantity') as $katao_invoice_product_id => $quantity) {
                KataoInvoiceProductPeer::deliverQuantity($katao_invoice_product_id, $quantity);
            }
            $this->katao_invoice->setStatus(KataoInvoice::STATUS_DELIVERED);
            $this->katao_invoice->save();

            $katao_product_id = $request->getParameter('new_product');
            if ($katao_product_id) {
                $katao_member = $this->katao_invoice->getKataoMember();
                $katao_user = $katao_member->getFirstKataoUser();
                $katao_cart = $katao_user->getCart($this->katao_invoice->getKataoPeriodId(), $this->katao_invoice->getKataoNodeId(), true);
                $katao_product = KataoProductPeer::retrieveByPK($katao_product_id);
                $katao_order_product_id = KataoOrderProductPeer::getIdByProductAndPeriodAndNode($katao_product_id, $this->katao_invoice->getKataoPeriodId(), $this->katao_invoice->getKataoNodeId());

                $katao_cart_product = new KataoCartProduct();
                $katao_cart_product->setKataoCart($katao_cart);
                $katao_cart_product->setKataoProduct($katao_product);
                $katao_cart_product->setProductReference($katao_product->getReference());
                $katao_cart_product->setProductName($katao_product->getName());
                $katao_cart_product->setProductPriceEuro($katao_product->getUnitPriceEuro());
                $katao_cart_product->setProductMargin($katao_product->getMargin());
                $katao_cart_product->setProductTvaRate($katao_product->getTvaRate());
                $katao_cart_product->setQuantity(0);
                $katao_cart_product->setQuantityAdjusted(0);
                $katao_cart_product->setHasBeenAdjusted(true);
                $katao_cart_product->setQuantityDelivered(1);
                $katao_cart_product->setKataoOrderProductId($katao_order_product_id);
                $katao_cart_product->save();

                $katao_invoice_product = new KataoInvoiceProduct();
                $katao_invoice_product->setKataoInvoice($this->katao_invoice);
                $katao_invoice_product->setKataoProduct($katao_product);
                $katao_invoice_product->setKataoCartProduct($katao_cart_product);
                $katao_invoice_product->setKataoOrderProductId($katao_order_product_id);
                $katao_invoice_product->setProductReference($katao_product->getReference());
                $katao_invoice_product->setProductName($katao_product->getName());
                $katao_invoice_product->setProductPriceEuro($katao_product->getUnitPriceEuro());
                $katao_invoice_product->setProductMargin($katao_product->getMargin());
                $katao_invoice_product->setProductTvaRate($katao_product->getTvaRate());
                $katao_invoice_product->setQuantity(0);
                $katao_invoice_product->setQuantityDelivered(0);
                $katao_invoice_product->setSolAmount(0);
                $katao_invoice_product->save();

                wpFlashMessages::addConfirmation('Produit "' . $katao_product->getName() . '" ajouté à la facture avec succès.');
                $this->redirect('@katao_invoice_deliver?id=' . $this->katao_invoice->getId());
            } else {
                wpFlashMessages::addConfirmation('Facture "' . $this->katao_invoice->getNumber() . '" délivrée avec succès.');
                $this->redirect('kataoInvoice/index');
            }
        }
    }

    public function executeValidate($request) {
        $this->redirectWithErrorUnless($this->katao_period = KataoPeriodPeer::retrieveByPK((int)$this->getUser()->getAttribute('katao_invoice_filter_period', KataoPeriodPeer::getActivePeriod()->getId())), 'Merci de filtrer les factures sur une période avant de les valider.', 'kataoInvoice/index');

        if ($request->isMethod('POST')) {
            $katao_node = KataoNodePeer::retrieveByPK($request->getParameter('node_id'));
            $this->redirectWithErrorUnless($katao_node, 'Merci de choisir un noeud', '@katao_invoice_validate');

            $criteria_update = new Criteria();
            $criteria_update->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_VALIDATED);
            $criteria_where = new Criteria();
            $criteria_where->add(KataoInvoicePeer::KATAO_PERIOD_ID, $this->katao_period->getId());
            $criteria_where->add(KataoInvoicePeer::KATAO_NODE_ID, $katao_node->getId());
            $criteria_where->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_DELIVERED);
            BasePeer::doUpdate($criteria_where, $criteria_update, Propel::getConnection());

            wpFlashMessages::addConfirmation('Les factures du noeud "' . $katao_node->getCity() . '" pour la période "' . $this->katao_period->getName() . '" ont été validées avec succès.');
            $this->redirect('kataoInvoice/index');
        }
    }

    public function executeUpdateProductDetails($request) {
        $katao_period = KataoPeriodPeer::retrieveByPK((int)$this->getUser()->getAttribute('katao_invoice_filter_period', KataoPeriodPeer::getActivePeriod()->getId()));
        $katao_node = KataoNodePeer::retrieveByPK($request->getParameter('node_id'));

        $return = '<i>Aucune facture à valider.</i>';
        $suppliers = array();
        if (!is_null($katao_period) && !is_null($katao_node)) {
            $criteria = new Criteria();
            $criteria->add(KataoInvoicePeer::KATAO_PERIOD_ID, $katao_period->getId());
            $criteria->add(KataoInvoicePeer::KATAO_NODE_ID, $katao_node->getId());
            $criteria->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_DELIVERED, Criteria::NOT_EQUAL);
            if (0 < KataoInvoicePeer::doCount($criteria)) {
                $return = '<i>Toutes les factures de ce noeud ne sont pas délivrées.</i>';
            } else {
                $criteria = new Criteria();
                $criteria->addJoin(KataoInvoiceProductPeer::KATAO_INVOICE_ID, KataoInvoicePeer::ID);
                $criteria->add(KataoInvoicePeer::KATAO_PERIOD_ID, $katao_period->getId());
                $criteria->add(KataoInvoicePeer::KATAO_NODE_ID, $katao_node->getId());
                $criteria->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_DELIVERED);
                foreach (KataoInvoiceProductPeer::doSelectJoinAllExceptKataoOrderProduct($criteria) as/*(KataoInvoiceProduct)*/ $katao_invoice_product) {
                    $return = '<i>Tous les produits ont été distribués en totalité.</i>';

                    $katao_invoice = $katao_invoice_product->getKataoInvoice();
                    $katao_product = $katao_invoice_product->getKataoProduct();

                    $supplier_name = $katao_product->getKataoSupplier()->getName();
                    $product_name = $katao_invoice_product->getProductName();

                    $current = $katao_product->getTotalDeliveredQuantity(false, $katao_period->getId(), $katao_node->getId());
                    $total = $katao_product->getTotalReceivedQuantity($katao_period->getId(), $katao_node->getId());
                    if ($current != $total) {
                        $suppliers[$supplier_name][$product_name]['current'] = $current;
                        $suppliers[$supplier_name][$product_name]['total'] = $total;
                        $suppliers[$supplier_name][$product_name]['members'][$katao_invoice->getId()] = $katao_invoice->getMemberName();
                    }
                }
            }
        }

        if (0 < count($suppliers)) {
            $return = '<table class="admin-sub-list">';
            foreach ($suppliers as $supplier_name => $products) {
                $return .= sprintf('<tr><td colspan="4" style="border:none!important;"><div class="content-add02">
	<div class="heading02"><h2>%s</h2></div>
</div></td></tr>', $supplier_name);
                $return .= sprintf('<tr><th>Produit</th><th style="text-align:center!important">%s</th><th style="text-align:center!important"">%s</th><th>Adhérents</th></tr>', image_tag('actions/receive.png', array('alt' => 'Quantité réceptionnée', 'title' => 'Quantité réceptionnée')), image_tag('actions/deliver.png', array('alt' => 'Quantité délivrée', 'title' => 'Quantité délivrée')));
                foreach ($products as $product_name => $product_data) {
                    $diff_str = $product_data['current'] - $product_data['total'];
                    if (0 < $diff_str) {
                        $diff_str = '+' . $diff_str;
                    }
                    $return .= sprintf('<tr valign="top"><td nowrap="nowrap">%s</td><td style="text-align:center!important">%s</td><td style="text-align:center!important">%d (%s)</td>', $product_name, $product_data['total'], $product_data['current'], $diff_str);

                    $members = array();
                    foreach ($product_data['members'] as $invoice_id => $member_name) {
                        $members[] = sprintf('<li>%s</li>', link_to($member_name, '@katao_invoice_deliver?id=' . $invoice_id));
                    }
                    if (0 < count($members)) {
                        $return .= sprintf('<td><ul>%s</ul></td>', implode('', $members));
                    }

                    $return .= '</tr>';
                }
            }
            $return .= '</table>';
        }

        return $this->renderText($return);
    }
}