<?php

/**
 *
 * @author antonio
 */
class PreventiviController extends Kit_Controller {

    private $status = array('IE' => 'IN ELABORAZIONE', 'AP' => 'APROVATO', 'NA' => 'NON APPROVATO');

    public function init() {
        $this->SetSearchParams();
      
        
    }

    public function indexAction() {
        
    }

    
    public function translate($string) {
        
        
        return $this->view->translate($string);
    }
    
    public function stampaPreventivoAction() {

        $this->_helper->Layout()->disableLayout();
        $this->_helper->ViewRenderer->setNeverRender();

        $id = $this->getRequest()->getParam('id');
        $anagrafiche = new Application_Model_DbTable_Anagrafica();
        $preventivi = new Application_Model_DbTable_Doct();
        $righe = new Application_Model_DbTable_Docr();
        $indirizzi = new Application_Model_DbTable_Indirizzi();
        $telefoni = new Application_Model_DbTable_Telefoni();
        $divisioni = new Application_Model_DbTable_Divisioni();

        try {

            $preventivo = $preventivi->find($id)->current();
            if (file_exists(APPLICATION_PATH.'/configs/lang/'.$preventivo->LANG.'.csv'))
            $translate = new Zend_Translate('csv', APPLICATION_PATH.'/configs/lang/'.$preventivo->LANG.'.csv', $preventivo->LANG);
       
            Zend_Registry::set('Zend_Translate', $translate);
            $cliente = $anagrafiche->find($preventivo->ANA_TIPO, $preventivo->ANA_COD)->current();
            
            $ditta = $anagrafiche->find('D', $preventivo->DOC_DITTA)->current();

            $indirizzi_cliente = $indirizzi->fetchAll("ANA_TIPO='CL' AND ANA_COD={$cliente->ANA_COD}")->current();
            if (!isset($indirizzi_cliente->INDIRIZZO))
                die("<h4>NON POSSO ESEGUIRE LA STAMPA.</h4><br/>Nella scheda cliente non &egrave; stato inserito alcun indirizzo");
            
            $ditta_telefoni = $telefoni->fetchAll(" ANA_TIPO='D' AND ANA_COD={$preventivo->DOC_DITTA}");

            $string_telefoni = '';

            foreach ($ditta_telefoni as $k => $vl) {
                $string_telefoni.= $vl->TIPO . ' : ' . $vl->TELEFONO . ' ';
            }

            $sede = $indirizzi->fetchAll("ANA_TIPO='{$ditta->ANA_TIPO}' AND ANA_COD={$ditta->ANA_COD}")->current();

            $anagrafica = $ditta->RAG_SOC . ' ' . $sede->INDIRIZZO . ' , ' . $sede->COMUNE . ' ';

          
            $img_path = APPLICATION_PATH . '/data/models/loghi/DIV_' . $preventivo->DOC_DIVISIONE . '.jpeg';

            $print_configs = array('logo' => $img_path, 'author' => $this->view->utente['ANA_TIPO'] . '.' . $this->view->utente['ANA_COD'], 'anagrafica' => $anagrafica . $string_telefoni);

            $pdf = new PDF($print_configs);

            // inizio ciclo stampa delle lettere.
            $pdf->setFontToPlain();
            $pdf->ln();
            $pdf->AddPage('P');
            $pdf->SetFontSize(9);
            $pdf->SetX(140);
            $pdf->setFontToBold();

            $pdf->Cell(80, 4, 'Spett.le ' . utf8_decode($preventivo->RAG_SOC));
            $pdf->setFontToPlain();
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->cell(80, 4, 'P.IVA : ' . $cliente->PIVA);
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->cell(80, 4, utf8_decode($indirizzi_cliente->INDIRIZZO));
            $pdf->SetX(15);
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->cell(80, 4, $indirizzi_cliente->CAP . ' ' . $indirizzi_cliente->COMUNE . ' ' . $indirizzi_cliente->PROV);
            $pdf->ln();
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->Cell(80, 4, "TITOLO : " . utf8_decode($preventivo->TITOLO));
            $pdf->ln();
            
            $pdf->SetX(15);
            $pdf->Cell(80, 4, "NR.PREV. : " . $preventivo->DOC_NUM . ' DEL ' . $this->view->Data($preventivo->DTA_INS));
            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            $pdf->SetX(15);

            $pdf->MultiCell(180, 5, utf8_decode($this->translate("la_nostra_offerta")));
            $pdf->ln();
            // con la presente stiamo le sottoponiamo la nostra migliore offerta per le seguenti attività.
            $pdf->SetX(15);
            $pdf->SetFontSize(7);
            $pdf->SetWidths(array(30, 60, 15, 20, 30, 30));
            /*
             *    
             *             <th><?=$this->translate('nr');?></th>
            <th><?=$this->translate('cod')?></th>
            <th><?=$this->translate('descrizione');?></th>
            <th><?=$this->translate('costo')?></th>
            <th><?=$this->translate('ricarica')?></th>
            <th><?=$this->translate('prezzo_listino');?></th>
            <th><?=$this->translate('unita');?></th>
            <th><?=$this->translate('qta');?></th>
            <th><?=$this->translate('prezzo_senza_ricarica')?></th>
            <th><?=$this->translate('prezzo_totale');?></th>
            <th><?=$this->translate('budget');?></th>
            <th><?=$this->translate('subtotale');?></th>
             * 
             */
            $pdf->SetRowHeader(array($this->translate('cod'), $this->translate('descrizione'), utf8_decode($this->translate('unita')), utf8_decode( $this->translate('qta')), $this->translate('prezzo'), $this->translate('subtotale')), array('C', 'C', 'C', 'C', 'C', 'C'));
            $pdf->RowHead();

            foreach ($righe->selectRigheDaStampare($preventivo->ID) as $n => $riga) {
                $pdf->SetX(15);
                $pdf->SetAligns(array('L', 'L', 'C', 'C', 'R', 'R'));
                $pdf->Row(array(
                    utf8_decode($riga->COD_ATT),
                    utf8_decode($riga->DESCRIZIONE),
                    $riga->UNI,
                    $riga->QTA,
                    $this->view->Number($riga->PREZZO_LISTINO, 'VALUTA'),
                    $this->view->Number($riga->PREZZO_TOT)
                ));
            }
            $pdf->ln();
            $pdf->setFontToBold();

            $pdf->SetX(140);
            $pdf->Cell(30, 5, $this->translate('totale_listino'), 1, 0, 'L');
            $pdf->Cell(30, 5, $this->view->Number($preventivo->DOC_IMP), 1, 0, 'R');
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->Cell(30, 5, $this->translate('sconto'), 1, 0, 'L');
            $pdf->Cell(30, 5, $this->view->Number($preventivo->SCONTO, 'SCONTO'), 1, 0, 'R');
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->Cell(30, 5, $this->translate('totale_netto'), 1, 0, 'L');
            $pdf->Cell(30, 5, $this->view->Number($preventivo->TOTALE_NETTO), 1, 0, 'R');
            $pdf->ln();
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->setFontToPlain();
            $pdf->MultiCell(180, 5, utf8_decode($this->translate('valido').' ' . $this->view->Data($preventivo->DTA_VALIDITA) . '.'));
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->setFontToPlain();
            $pdf->MultiCell(180, 5, utf8_decode($this->translate('mod_pag') .' '. $preventivo->DESCPAG));
            $pdf->SetY($pdf->GetY() + 30);
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->Cell(50, 4, utf8_decode("{$sede->COMUNE},  " . date('d-n-Y', time())));
            $pdf->SetX(155);
            $pdf->Cell(50, 4, $this->translate('firma'));

            $pdf->Output($preventivo->DOC_NUM . '.pdf', 'D');
        } catch (Exception $exc) {
            echo $exc->getMessage();
	    
        }
    }

    public function stampaPreventivoSpAction() {
// stampa del preventivo senza prezzi.
        $this->_helper->Layout()->disableLayout();
        $this->_helper->ViewRenderer->setNeverRender();

        $id = $this->getRequest()->getParam('id');
        $anagrafiche = new Application_Model_DbTable_Anagrafica();
        $preventivi = new Application_Model_DbTable_Doct();
        $righe = new Application_Model_DbTable_Docr();
        $indirizzi = new Application_Model_DbTable_Indirizzi();
        $telefoni = new Application_Model_DbTable_Telefoni();
        $divisioni = new Application_Model_DbTable_Divisioni();

        try {

            $preventivo = $preventivi->find($id)->current();
             if (file_exists(APPLICATION_PATH.'/configs/lang/'.$preventivo->LANG.'.csv'))
                $translate = new Zend_Translate('csv', APPLICATION_PATH.'/configs/lang/'.$preventivo->LANG.'.csv', $preventivo->LANG);
       
            Zend_Registry::set('Zend_Translate', $translate);
            
            $cliente = $anagrafiche->find('CL', $preventivo->ANA_COD)->current();

            $ditta = $anagrafiche->find('D', $preventivo->DOC_DITTA)->current();

            $indirizzi_cliente = $indirizzi->fetchAll("ANA_TIPO='CL' AND ANA_COD={$cliente->ANA_COD}")->current();

            $ditta_telefoni = $telefoni->fetchAll(" ANA_TIPO='D' AND ANA_COD={$preventivo->DOC_DITTA}");

            $string_telefoni = '';

            foreach ($ditta_telefoni as $k => $vl) {
                $string_telefoni.= $vl->TIPO . ' : ' . $vl->TELEFONO . ' ';
            }

            $sede = $indirizzi->fetchAll("ANA_TIPO='{$ditta->ANA_TIPO}' AND ANA_COD={$ditta->ANA_COD}")->current();

            $anagrafica = $ditta->RAG_SOC . ' ' . $sede->INDIRIZZO . ' , ' . $sede->COMUNE . ' ';

           
            $img_path = APPLICATION_PATH . '/data/models/loghi/DIV_' . $preventivo->DOC_DIVISIONE . '.jpeg';

            $print_configs = array('logo' => $img_path, 'author' => $this->view->utente['ANA_TIPO'] . '.' . $this->view->utente['ANA_COD'], 'anagrafica' => $anagrafica . $string_telefoni);

            $pdf = new PDF($print_configs);

            // inizio ciclo stampa delle lettere.
            $pdf->setFontToPlain();
            $pdf->ln();
            $pdf->AddPage('P');
            $pdf->SetFontSize(9);
            $pdf->SetX(140);
            $pdf->setFontToBold();

            $pdf->Cell(80, 4, 'Spett.le ' . utf8_decode($preventivo->RAG_SOC));
            $pdf->setFontToPlain();
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->cell(80, 4, 'P.IVA : ' . $cliente->PIVA);
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->cell(80, 4, utf8_decode($indirizzi_cliente->INDIRIZZO));
            $pdf->SetX(15);
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->cell(80, 4, $indirizzi_cliente->CAP . ' ' . $indirizzi_cliente->COMUNE . ' ' . $indirizzi_cliente->PROV);
            $pdf->ln();
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->Cell(80, 4, "TITOLO : " . utf8_decode($preventivo->TITOLO));
            $pdf->ln();
            
            $pdf->SetX(15);
            $pdf->Cell(80, 4, "NR.PREV. : " . $preventivo->DOC_NUM . ' DEL ' . $this->view->Data($preventivo->DTA_INS));
            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            $pdf->SetX(15);

            $pdf->MultiCell(180, 5,$this->translate('la_nostra_offerta'));
            $pdf->ln();
            // con la presente stiamo le sottoponiamo la nostra migliore offerta per le seguenti attività.
            $pdf->SetX(15);
            $pdf->SetFontSize(7);
            $pdf->SetWidths(array(30, 150));
            $pdf->SetRowHeader(array($this->translate('cod'), $this->translate('descrizione')), array('C', 'C'));
            $pdf->RowHead();

            foreach ($righe->selectRigheDaStampare($preventivo->ID) as $n => $riga) {
                $pdf->SetX(15);
                $pdf->SetAligns(array('L', 'L', 'C', 'C', 'R', 'R'));
                $pdf->Row(array(
                    utf8_decode($riga->COD_ATT),
                    utf8_decode($riga->DESCRIZIONE)
                ));
            }
            $pdf->ln();
            $pdf->setFontToBold();

            $pdf->SetX(135);
            $pdf->Cell(30, 5, $this->translate('totale_netto'), 1, 0, 'L');
            $pdf->Cell(30, 5, $this->view->Number($preventivo->DOC_IMP), 1, 0, 'R');
            $pdf->ln();
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->setFontToPlain();
            $pdf->MultiCell(180, 5, utf8_decode($this->translate('valido') . '  '.$this->view->Data($preventivo->DTA_VALIDITA) . '.'));
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->setFontToPlain();
            $pdf->MultiCell(180, 5, utf8_decode($this->translate('mod_pag') .' '. $preventivo->DESCPAG));
            $pdf->SetY($pdf->GetY() + 30);
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->Cell(50, 4, utf8_decode("{$sede->COMUNE}, " . date('d-n-Y', time())));
            $pdf->SetX(155);
            $pdf->Cell(50, 4, $this->translate("firma"));


            $pdf->Output($preventivo->DOC_NUM . '.pdf', 'D');
        } catch (Exception $exc) {
            echo $exc->getMessage();
        }
    }

    public function stampaPreventivoNAction() {
// stampa preventivo con totale e sconto e senza prezzi
        $this->_helper->Layout()->disableLayout();
        $this->_helper->ViewRenderer->setNeverRender();

        $id = $this->getRequest()->getParam('id');
        $anagrafiche = new Application_Model_DbTable_Anagrafica();
        $preventivi = new Application_Model_DbTable_Doct();
        $righe = new Application_Model_DbTable_Docr();
        $indirizzi = new Application_Model_DbTable_Indirizzi();
        $telefoni = new Application_Model_DbTable_Telefoni();
        $divisioni = new Application_Model_DbTable_Divisioni();

        try {

            $preventivo = $preventivi->find($id)->current();
            $cliente = $anagrafiche->find('CL', $preventivo->ANA_COD)->current();
            if (file_exists(APPLICATION_PATH.'/configs/lang/'.$preventivo->LANG.'.csv'))
            $translate = new Zend_Translate('csv', APPLICATION_PATH.'/configs/lang/'.$preventivo->LANG.'.csv', $preventivo->LANG);
             Zend_Registry::set('Zend_Translate', $translate);
            
            $ditta = $anagrafiche->find('D', $preventivo->DOC_DITTA)->current();

            $indirizzi_cliente = $indirizzi->fetchAll("ANA_TIPO='CL' AND ANA_COD={$cliente->ANA_COD}")->current();
            
            $ditta_telefoni = $telefoni->fetchAll(" ANA_TIPO='D' AND ANA_COD={$preventivo->DOC_DITTA}");

            $string_telefoni = '';

            foreach ($ditta_telefoni as $k => $vl) {
                $string_telefoni.= $vl->TIPO . ' : ' . $vl->TELEFONO . ' ';
            }

            $sede = $indirizzi->fetchAll("ANA_TIPO='{$ditta->ANA_TIPO}' AND ANA_COD={$ditta->ANA_COD}")->current();

            $anagrafica = $ditta->RAG_SOC . ' ' . $sede->INDIRIZZO . ' , ' . $sede->COMUNE . ' ';

            $img_path = APPLICATION_PATH . '/data/models/loghi/DIV_' . $preventivo->DOC_DIVISIONE . '.jpeg';

            $print_configs = array('logo' => $img_path, 'author' => $this->view->utente['ANA_TIPO'] . '.' . $this->view->utente['ANA_COD'], 'anagrafica' => $anagrafica . $string_telefoni);

            $pdf = new PDF($print_configs);

            // inizio ciclo stampa delle lettere.
            $pdf->setFontToPlain();
            $pdf->ln();
            $pdf->AddPage('P');
            $pdf->SetFontSize(9);
            $pdf->SetX(140);
            $pdf->setFontToBold();

            $pdf->Cell(80, 4, 'Spett.le ' . utf8_decode($preventivo->RAG_SOC));
            $pdf->setFontToPlain();
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->cell(80, 4, 'P.IVA : ' . $cliente->PIVA);
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->cell(80, 4, utf8_decode($indirizzi_cliente->INDIRIZZO));
            $pdf->SetX(15);
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->cell(80, 4, $indirizzi_cliente->CAP . ' ' . $indirizzi_cliente->COMUNE . ' ' . $indirizzi_cliente->PROV);
            $pdf->ln();
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->Cell(80, 4, "TITOLO : " . utf8_decode($preventivo->TITOLO));
            $pdf->ln();
            
            $pdf->SetX(15);
            $pdf->Cell(80, 4, "NR.PREV. : " . $preventivo->DOC_NUM . ' DEL ' . $this->view->Data($preventivo->DTA_INS));
            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            $pdf->SetX(15);

            $pdf->MultiCell(180, 5, $this->translate('la_nostra_offerta'));
            $pdf->ln();
            // con la presente stiamo le sottoponiamo la nostra migliore offerta per le seguenti attività.
            $pdf->SetX(15);
            $pdf->SetFontSize(7);
            $pdf->SetWidths(array(30, 155));
            $pdf->SetRowHeader(array($this->translate('cod'), $this->translate('descrizione')), array('C', 'C'));
            $pdf->RowHead();

            foreach ($righe->selectRigheDaStampare($preventivo->ID) as $n => $riga) {
                $pdf->SetX(15);
                $pdf->SetAligns(array('L', 'L'));
                $pdf->Row(array(
                    utf8_decode($riga->COD_ATT),
                    utf8_decode($riga->DESCRIZIONE)
                ));
            }
            $pdf->ln();
            $pdf->setFontToBold();

            $pdf->SetX(140);
            $pdf->Cell(30, 5, $this->translate('totale_listino'), 1, 0, 'L');
            $pdf->Cell(30, 5, $this->view->Number($preventivo->DOC_IMP), 1, 0, 'R');
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->Cell(30, 5, $this->translate('sconto'), 1, 0, 'L');
            $pdf->Cell(30, 5, $this->view->Number($preventivo->SCONTO, 'SCONTO'), 1, 0, 'R');
            $pdf->ln();
            $pdf->SetX(140);
            $pdf->Cell(30, 5, $this->translate('totale_netto'), 1, 0, 'L');
            $pdf->Cell(30, 5, $this->view->Number($preventivo->TOTALE_NETTO), 1, 0, 'R');
            $pdf->ln();
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->setFontToPlain();
            $pdf->MultiCell(180, 5, utf8_decode($this->translate('valido').' ' . $this->view->Data($preventivo->DTA_VALIDITA) . '.'));
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->setFontToPlain();
            $pdf->MultiCell(180, 5, utf8_decode($this->translate('mod_pag'). $preventivo->DESCPAG));
            $pdf->SetY($pdf->GetY() + 30);
            $pdf->ln();
            $pdf->SetX(15);
            $pdf->Cell(50, 4, utf8_decode("{$sede->COMUNE},  " . date('d-n-Y', time())));
            $pdf->SetX(155);
            $pdf->Cell(50, 4, $this->translate("firma"));


            $pdf->Output($preventivo->DOC_NUM . '.pdf', 'D');
        } catch (Exception $exc) {
            echo $exc->getMessage();
        }
    }

    public function listaPreventiviAction() {
        
        $page = $this->getRequest()->getParam('page');

        $anagrafica = new Application_Model_DbTable_Anagrafica();
        $preventivi = new Application_Model_DbTable_Doct();

        $where = ($this->search != '') ? "DOC_TIPO='PR' AND ( TITOLO LIKE '%{$this->search}%'  OR RAG_SOC LIKE '%{$this->search}%' )" : "DOC_TIPO='PR'";

        $adapter = $preventivi->getPaginator(array('ID', 'ANA_COD', 'RAG_SOC', 'STATO', 'TITOLO', 'DOC_NUM','DOC_DITTA','DOC_DIVISIONE','TIPOLOGIA', 'YEAR(DTA_INS) AS ANNO', 'SCONTO', 'DOC_IMP', 'TOTALE_NETTO', 'BUDGET'), $where, 'DTA_INS DESC');

        $paginatore = new Zend_Paginator($adapter);
        $paginatore->setCurrentPageNumber($page);
        $paginatore->setItemCountPerPage($paginatore->getTotalItemCount());

        $this->view->paginatore = $paginatore;
        $this->view->anagrafica = $anagrafica;
        
        
        
    }

    public function nuovoPreventivoAction() {
        $preventivi = new Application_Model_DbTable_Doct();

        $form = new Application_Form_PreventivoTestata(array('orentation'=>'inline'));
        $form->getElement('annulla')->setAttrib('OnClick', "document.location.href='{$this->view->url(array('action' => 'lista-preventivi'))}'");
        $anagrafiche = new Application_Model_DbTable_Anagrafica();
        
         if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {

                $scheda_cliente = $anagrafiche->find('CL', $form->getElement('ANA_CODC')->getValue())->current();
                $data = array(
                    'TITOLO' => $form->getElement('TITOLO')->getValue(),
                     'DOC_DITTA'=> new Zend_Db_Expr( " ( SELECT ANA_COD FROM divisioni WHERE ID={$form->getElement('DOC_DIVISIONE')->getValue()} )"),
                    'DOC_DIVISIONE'=>$form->getElement('DOC_DIVISIONE')->getValue(),
                    'ANA_TIPO'=>'CL',
                    'ANA_COD' => $form->getElement('ANA_CODC')->getValue(),
                    'RAG_SOC' => $scheda_cliente->RAG_SOC,
                    'TIPOLOGIA'=>$form->getElement('TIPOLOGIA')->getValue(),
                    'IDPAG' => $form->getElement('IDPAG')->getValue(),
                    'DESCPAG' => new Zend_Db_Expr("(SELECT DESCRIZIONE FROM modpag WHERE IDPAG={$form->getElement('IDPAG')->getValue()} )"),
                    'DTA_VALIDITA' => $this->view->Data($form->getElement('DTA_VALIDITA')->getValue()),
                    'NOTE' => $form->getElement('NOTE')->getValue(),
                    'DOC_TIPO' => 'PR',
                    'UID_INS' => $this->view->utente['username'],
                    'DTA_INS' => new Zend_Db_Expr(" NOW() "),
                    'DTA_INIZIO_TEO' => $this->view->Data($form->getElement('DTA_INIZIO_TEO')->getValue()),
                    'DTA_FINE_TEO' => $this->view->Data($form->getElement('DTA_FINE_TEO')->getValue())
                );

                $id = $preventivi->insert($data);

                $this->_redirect($this->view->url(array('action' => 'scheda-preventivo', 'id' => $id)));
            }
        }

        $this->view->form = $form;
    }

    public function formTestataPreventivo(Application_Form_PreventivoTestata $form) {

       /* $doct = new Application_Model_DbTable_Doct();

        $stato_preventivo = new Zend_Form_Element_Select('STATO');
        $stato_preventivo->setMultiOptions($doct->stati_preventivo);
        $stato_preventivo->setLabel('Stato del preventivo');

        $stato_preventivo->setOrder(0);

        $form->addElement($stato_preventivo);


        $budget = $form->createElement('text', 'BUDGET');
        $budget->setLabel('Budget Field : ');
        //       $budget->setOrder(8);
        $budget->setAttrib('class', 'text text-success');
        $budget->setAttrib('readonly', 'true');
        //    $form->addElement($budget);
        //
            $totale = $form->createElement('text', 'DOC_IMP');
        $totale->setLabel('Totale Imponibile : ');
        //     $totale->setOrder(9);
        $totale->setAttrib('readonly', 'true');
        $totale->setAttrib('class', 'number');

        //   $form->addElement($totale);

        $sconto = $form->createElement('text', 'SCONTO');
        $sconto->setLabel('Sconto : ');
        //    $sconto->setOrder(10);
        $sconto->setAttrib('readonly', 'true');
        $sconto->setAttrib('class', ' sale');

        //  $form->addElement($sconto);

        $totale_netto = $form->createElement('text', 'TOTALE_NETTO');
        //    $totale_netto->setLabel('Totale Netto : ');
        $totale_netto->setAttrib('readonly', 'true');
        //   $totale_netto->setOrder(11);
        $totale_netto->setAttrib('class', 'number');

        //     $form->addElement($totale_netto);*/
    }

    public function anteprimaPreventivoAction() {
             $id = $this->getRequest()->getParam('id');
                $preventivi = new Application_Model_DbTable_Doct();
                   $preventivo = $preventivi->find($id)->current();
             $this->renderDocument($preventivo);
                   $nav =  Zend_Registry::get('Zend_Navigation');
        $nav->findOneByLabel('Lista Preventivi')
           ->addPage(array(
                            'label'=>'Preventivo NR.'.$preventivo->DOC_NUM,
                            'controller'=>'preventivi',
                            'action'=>'anteprima-preventivo',
                            'params'=>array('id'=>$preventivo->ID)
                      ));
        
         
         $this->view->navigation($nav);
    }
    
    public function schedaPreventivoAction() {
        $id = $this->getRequest()->getParam('id');
        
        $preventivi = new Application_Model_DbTable_Doct();
        //$tipologie = new Application_Model_DbTable_TipologieDoct();
        $anagrafiche = new Application_Model_DbTable_Anagrafica();
        $preventivo = $preventivi->find($id)->current();

        
        $righe_prev = $preventivo->findDependentRowset('Application_Model_DbTable_Docr');
        $this->view->preventivo = $preventivo;

        $form = new Application_Form_PreventivoTestata(array('orentation'=>'inline'));
        $this->formTestataPreventivo($form);

        $form->getElement('annulla')->setAttrib('OnClick', "document.location.href='{$this->view->url(array('action' => 'lista-preventivi'))}'");

        $form_data = $preventivo->toArray();
        $form_data['DTA_VALIDITA'] = $this->view->Data($form_data['DTA_VALIDITA'], 'MYSQL');
        $form_data['DTA_INIZIO_TEO'] = $this->view->Data($form_data['DTA_INIZIO_TEO'], 'MYSQL');
        $form_data['DTA_FINE_TEO'] = $this->view->Data($form_data['DTA_FINE_TEO'], 'MYSQL');
        $form_data['ANA_CODC']=$preventivo->ANA_COD;
        $form->populate($form_data);
        
        $url_righe = $this->view->url(array('action' => 'righe-preventivo', 'id' => $id));
        $url_stampa = $this->view->url(array('action' => 'stampa-preventivo', 'id' => $id));
        $url_stampa_sp = $this->view->url(array('action' => 'stampa-preventivo-sp', 'id' => $id));
        $url_stampa_n = $this->view->url(array('action' => 'stampa-preventivo-n', 'id' => $id));
        
        
        $url_duplica = $this->view->url(array('action' => 'duplica-preventivo', 'id' => $id));

        $form->getElement('annulla')->setLabel('Torna alla lista');
        $form->getElement('continua')->setLabel('Conferma modifiche');

        $buttons = array();

        if ($preventivo->STATO == 'AP') {
            $progetto = $preventivi->fetchAll("PID={$preventivo->ID}")->current();

            $url_progetto = $this->view->url(array('controller' => 'progetti', 'action' => 'scheda-progetto', 'id' => $progetto->ID));

            $btn_prj = $form->createElement('button', 'prj')
                    ->setAttrib('OnClick', "document.location.href='{$url_progetto}'")
                    ->setAttrib('class', "btn btn-success btn_200")
                    ->setLabel('Progetto relativo : ' . $progetto->DOC_NUM)
                    ->setOrder(5);
            array_push($buttons, $btn_prj);
            $form->removeElement('continua');
        }

        $btn_righe_preventivo = $form->createElement('button', 'righe')
                ->setLabel('righe preventivo (' . $righe_prev->count() . ")")
                ->setAttrib('OnClick', "document.location.href='{$url_righe}'")
                ->setAttrib('class', "btn btn-danger btn_200")
                ->setOrder(1);
        array_push($buttons, $btn_righe_preventivo);
  
        $this->view->btn1 = $url_stampa;
        $this->view->btn2 = $url_stampa_n;
        $this->view->btn3 = $url_stampa_sp;
        
        $btn_duplica = $form->createElement('button', 'duplica')
                ->setLabel('Duplica preventivo')
                ->setAttrib('OnClick', "document.location.href='{$url_duplica}'")
                ->setAttrib('class', "btn btn-warning btn_200")
                ->setOrder(6);
        array_push($buttons, $btn_duplica);


        $form->addElements($buttons);
        
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {

                try {
                    $scheda_cliente = $anagrafiche->find('CL', $form->getElement('ANA_CODC')->getValue())->current();
                    $data = array(
                        'TITOLO' => $form->getElement('TITOLO')->getValue(),
                        'LANG'=>$form->getElement('LANG')->getValue(),
                        'ANA_TIPO'=>'CL',
                        'DOC_DITTA'=> new Zend_Db_Expr( " ( SELECT ANA_COD FROM divisioni WHERE ID={$form->getElement('DOC_DIVISIONE')->getValue()} )"),
                        'DOC_DIVISIONE'=>$form->getElement('DOC_DIVISIONE')->getValue(),
                        'ANA_COD' => $form->getElement('ANA_CODC')->getValue(),
                        'RAG_SOC' => $scheda_cliente->RAG_SOC,
                        'IDPAG' => $form->getElement('IDPAG')->getValue(),
                        'DESCPAG' => new Zend_Db_Expr("(SELECT DESCRIZIONE FROM modpag WHERE IDPAG={$form->getElement('IDPAG')->getValue()} )"),
                        'DTA_VALIDITA' => $this->view->Data($form->getElement('DTA_VALIDITA')->getValue()),
                        'NOTE' => $form->getElement('NOTE')->getValue(),
                        'STATO' => $form->getElement('STATO')->getValue(),
                        'TIPOLOGIA'=> $form->getElement('TIPOLOGIA')->getValue(),
                        'UID_MOD' => $this->view->utente['username'],
                        'DTA_MOD' => new Zend_Db_Expr(" NOW() "),
                        'DTA_INIZIO_TEO' => $this->view->Data($form->getElement('DTA_INIZIO_TEO')->getValue()),
                        'DTA_FINE_TEO' => $this->view->Data($form->getElement('DTA_FINE_TEO')->getValue())
                    );

                    $preventivi->update($data, "ID=$id");
/*
*/
                    if ($form->getElement('STATO')->getValue() == 'AP') {

                        $id_progetto = $preventivi->confermaPreventivo($id);
                        foreach ($_POST['TIPOLOGIE'] as $key => $id_tipologia) {
                            $tipologie->insert(array('IDDOCT' => $id_progetto, 'ID_TIPOLOGIA' => $id_tipologia));
                        }
                        //ADESSO BISOGNA ASSEGNARE GLI INCARICHI AI COLLABORATORI
                        $url = $this->view->url(array('controller' => 'progetti', 'action' => 'scheda-progetto', 'id' => $id_progetto));
                        $this->_redirect($url);
                    }


                    $this->view->message = "Record modificato correttamente";
                    $this->view->class = "success";
                } catch (Exception $exc) {
                    $this->view->class = "warning";
                    $this->view->message = $exc->getMessage();
                }
            }
        }

        $this->view->form = $form;
        
        $nav =  Zend_Registry::get('Zend_Navigation');
        $nav->findOneByLabel('Lista Preventivi')
           ->addPage(array(
                            'label'=>'Scheda Preventivo NR.'.$preventivo->DOC_NUM,
                            'controller'=>'preventivi',
                            'action'=>'scheda-preventivo',
                            'params'=>array('id'=>$preventivo->ID)
                      ));
        
         
         $this->view->navigation($nav);
    }

    public function assegnaIncarichiAction() {
        $id = $this->getRequest()->getParam('id');

        $anagrafiche = new Application_Model_DbTable_Anagrafica();
        $collabs = $anagrafiche->fetchAll("ANA_TIPO='CO'", 'RAG_SOC');
        $collaboratori = array();
        foreach ($collabs as $n => $collaboratore) {
            $collaboratori[$collaboratore->ANA_COD] = $collaboratore->RAG_SOC;
        }


        $preventivi = new Application_Model_DbTable_Doct();
        $preventivo = $preventivi->find($id)->current();

        $righe = $preventivo->findDependentRowset('Application_Model_DbTable_Docr');

        $this->view->preventivo = $preventivo;
        $this->view->righe = $righe;
        $this->view->collaboratori = $collaboratori;
    }

    public function righePreventivoAction() {
        
        $this->view->headScript()->appendFile('/dynatree/src/jquery.dynatree.js');
        $id = $this->getRequest()->getParam('id');
        $preventivi = new Application_Model_DbTable_Doct();

        $select = $preventivi->select()->order('NR');

        $preventivo = $preventivi->find($id)->current();
          if (file_exists(APPLICATION_PATH.'/configs/lang/'.$preventivo->LANG.'.csv'))
            $translate = new Zend_Translate('csv', APPLICATION_PATH.'/configs/lang/'.$preventivo->LANG.'.csv', $preventivo->LANG);
       
       Zend_Registry::set('Zend_Translate', $translate);
       
        
        $righe = $preventivo->findDependentRowset('Application_Model_DbTable_Docr', NULL, $select);

        $this->view->preventivo = $preventivo;
        $this->view->righe = $righe;
        
        $url_stampa = $this->view->url(array('action' => 'stampa-preventivo', 'id' => $id));
        $url_stampa_sp = $this->view->url(array('action' => 'stampa-preventivo-sp', 'id' => $id));
        $url_stampa_n = $this->view->url(array('action' => 'stampa-preventivo-n', 'id' => $id));
        
        $this->view->btn1 = $url_stampa;
        $this->view->btn2 = $url_stampa_sp;
        $this->view->btn3 = $url_stampa_n;
        
        /*
        if ($preventivo->STATO == 'AP') {
            $this->renderScript('preventivi/righe-preventivo_confermato.phtml');
        }
        */
    }

    public function nuovaRigaPreventivoAction() {
               
        $this->_helper->ViewRenderer->setNeverRender();
        $id = $this->getRequest()->getParam('id');
        $righe = new Application_Model_DbTable_Docr();
        $nrighe = $this->getRequest()->getParam('nrighe');
        
        if ($nrighe>=1) {
            for ($i = 0; $i<=(int) $nrighe-1; $i++) {
                  $righe->insert(array('ID_DOCT' => $id, 'NR' => $righe->getRigaNum($id), 'QTA' => 0, 'RICARICA'=>23, 'TEMPO_DOMANDA' => 19, 'COSTO_ORARIO_RISORSA' => 8));
            }
            $this->_redirect($this->view->url(array('action' => 'righe-preventivo', 'id' => $id), null, false));
        }
    }
    public function duplicaPreventivoAction() {

        $this->_helper->Layout()->disableLayout();
        $this->_helper->ViewRenderer->setNeverRender();

        $id_prev_old = $this->getRequest()->getParam('id');
        $preventivi = new Application_Model_DbTable_Doct();
        $anagrafiche = new Application_Model_DbTable_Anagrafica();
        $righe_table = new Application_Model_DbTable_Docr();
        $preventivo_info = $preventivi->find($id_prev_old)->current();

        $scheda_cliente = $anagrafiche->find('CL', $preventivo_info->ANA_COD);

        /* inserisce un nuovo preventivo */

        $data = array(
            'DOC_TIPO' => 'PR',
            'PID' => $id_prev_old,
            'UID_INS' => $this->view->utente['username'],
            'UID_MOD' => $this->view->utente['username'],
            'DOC_DITTA' => $preventivo_info->DOC_DITTA,
            'DOC_DIVISIONE' => $preventivo_info->DOC_DIVISIONE,
            'ANA_TIPO' => $preventivo_info->ANA_TIPO,
            'ANA_COD' => $preventivo_info->ANA_COD,
            'RAG_SOC' => $preventivo_info->RAG_SOC,
            'DTA_DOC' => $preventivo_info->DTA_DOC,
            'DTA_INS' => new Zend_Db_Expr("NOW()"),
            'DTA_VALIDITA' => new Zend_Db_Expr("NOW()"),
            'TITOLO' => $preventivo_info->TITOLO . ' DUPLICATO',
            'DESCRIZIONE' => $preventivo_info->DESCRIZIONE,
            'STATO' => 'IE',
            'DOC_IMP' => $preventivo_info->DOC_IMP,
            'SCONTO' => $preventivo_info->SCONTO,
            'TOTALE_NETTO' => $preventivo_info->TOTALE_NETTO,
            'IVAPERC' => $preventivo_info->IVAPERC,
            'DOC_IVA' => $preventivo_info->DOC_IVA,
            'DOC_TOT' => $preventivo_info->DOC_TOT,
            'BUDGET' => $preventivo_info->BUDGET,
            'GENPAG' => $preventivo_info->GENPAG,
            'IDPAG' => $preventivo_info->IDPAG,
            'DESCPAG' => $preventivo_info->DESCPAG,
            'IMP_PROV' => $preventivo_info->IMP_PROV,
            'PERC_PROV' => $preventivo_info->PERC_PROV,
            'NOTE' => $preventivo_info->NOTE,
            'NUM_RILEVAZIONI' => $preventivo_info->NUM_RILEVAZIONI,
            'DTA_INCASSO' => $preventivo_info->DTA_INCASSO,
            'INCASSATO' => $preventivo_info->INCASSATO,
            'MONTE_ORE_TEO' => $preventivo_info->MONTE_ORE_TEO,
            'MONTE_ORE_EFF' => $preventivo_info->MONTE_ORE_EFF,
            'DTA_INIZIO_TEO' => $preventivo_info->DTA_INIZIO_TEO,
            'DTA_INIZIO_EFF' => $preventivo_info->DTA_INIZIO_EFF,
            'DTA_FINE_TEO' => $preventivo_info->DTA_FINE_TEO,
            'DTA_FINE_EFF' => $preventivo_info->DTA_FINE_EFF,
        );


        try {
            $id = $preventivi->insert($data);
            $righe = $righe_table->fetchAll('ID_DOCT = ' . $id_prev_old, 'NR');

            foreach ($righe as $n => $riga) {
                $data_riga = array(
                    'TEMPO_RECLUTAMENTO' => $riga->TEMPO_RECLUTAMENTO,
                    'TEMPO_DOMANDA' => $riga->TEMPO_DOMANDA,
                    'TEMPO_INTERVISTA' => $riga->TEMPO_INTERVISTA,
                    'NUMERO_DOMANDE' => $riga->NUMERO_DOMANDE,
                    'COSTO_ORARIO_RISORSA' => $riga->COSTO_ORARIO_RISORSA,
                    'PID' => $riga->PID,
                    'NR' => $riga->NR,
                    'ID_DOCT' => $id,
                    'ID_ATT' => $riga->ID_ATT,
                    'COD_ATT' => $riga->COD_ATT,
                    'DESCRIZIONE' => $riga->DESCRIZIONE,
                    'QTA' => $riga->QTA,
                    'UNI' => $riga->UNI,
                    'BUDGET_FIELD' => $riga->BUDGET_FIELD,
                    'RICARICA' => $riga->RICARICA,
                    'PREZZO_COSTO' => $riga->PREZZO_COSTO,
                    'PREZZO_LISTINO' => $riga->PREZZO_LISTINO,
                    'PREZZO_TOT' => $riga->PREZZO_TOT,
                    'IVA_RIGA' => $riga->IVA_RIGA,
                    'SUBTOTALE' => $riga->SUBTOTALE,
                    'DTA_INS' => $riga->DTA_INS,
                    'DTA_LIST' => $riga->DTA_LIST,
                    'DTA_MOD' => $riga->DTA_MOD,
                    'ESENTE_IVA' => $riga->ESENTE_IVA,
                    'IVA_CODICE' => $riga->IVA_CODICE,
                    'IVA_DESC' => $riga->IVA_DESC,
                    'IVA_PERC' => $riga->IVA_PERC,
                );
                $righe_table->insert($data_riga);
                //inserimento delle tipologie di progetto.
                $preventivi->getAdapter()->query("INSERT INTO tipologie_doct ( ID_TIPOLOGIA, IDDOCT) SELECT ID_TIPOLOGIA, '$id' from tipologie_doct WHERE IDDOCT=$id_prev_old");
                
                
                
                
            }
        } catch (Exception $e) {
            echo $e->getMessage();
            echo "<br/>";
            echo $e->getTraceAsString();
        }

        $this->_redirect($this->view->url(array('action' => 'scheda-preventivo', 'id' => $id)));
    }

}

?>

