<hr>
<?php

/**
//This file is part of NOALYSS and is under GPL 
//see licence.txt
*/
/**
 * @brief show the common parts of operation details 
 * 
 * Variables : $div = popup or box (det[0-9]
 *@var $obj = Acc_Operation 
 *@var $str_anc = HTML for analytic
 */
bcscale(2);
\Noalyss\Dbg::echo_file(__FILE__);
$select_box=new \Select_Box("sb_".$jr_id, _("Autre action"));
$select_box->set_position("normal");
$cn=Dossier::connect();
// Contains all the linked actions
$a_followup = Follow_Up::get_all_operation($jr_id);
//
// Contains all the linked operations
$oRap=new Acc_Reconciliation($cn);
$oRap->jr_id=$jr_id;
$aRap=$oRap->get();

// Detail of operation
 $detail = new Acc_Misc($cn, $obj->jr_id);
 $detail->get();
 
 // find out exercice
 $periode_id=new Periode($cn,$detail->det->jr_tech_per);
 $exercice=$periode_id->get_exercice();

// @var $nb_document (int) number of doc 
$nb_document=($detail->det->jr_pj_name != "")?1:0;
// @var $str_nb_doc (string) HTML span number of doc 
$str_nb_doc=($nb_document==0)?span(""):span($nb_document,'class="nb-round"');

// @var $nb_aRap (int) number of reconciliation 
$nb_aRap=(is_array($aRap))?count($aRap):0;
// @var $str_nb_rap (string) HTML span for number of reconciliation 
$str_nb_rap=($nb_aRap==0)?span(""):span($nb_aRap,'class="nb-round"');

//@var $nb_sup_doc (int) number of supplementary documents
$nb_sup_doc=$cn->get_value("select count(*) from jrn_sup_document where jr_id=$1",[$jr_id]);

// @var $str_nb_sup_doc (string) HTML span for the number of  supplementary documents
$x=sprintf('id="%s_%s"',"doc_supp",$div);
$str_nb_sup_doc=($nb_sup_doc==0)?span("",$x):span($nb_sup_doc,'class="nb-round" '.$x);

// @var $nb_fu (int) number of event in follow-up
$nb_fu=count($a_followup);
// @var $str_nb_fu (string) HTML span for the number of followup
$str_nb_fu=($nb_fu==0)?span(""):span($nb_fu,'class="nb-round"');

// Array of tab
// 
$a_tab['writing_div']=array('id'=>'writing_div'.$div,'label'=>_('Ecriture Comptable'),'display'=>'none');
$a_tab['info_operation_div']=array('id'=>'info_operation_div'.$div,'label'=>_('Information'),'display'=>'none');
$a_tab['linked_operation_div']=array('id'=>'linked_operation_div'.$div,'label'=>_('Opérations liées').$str_nb_rap,'display'=>'none');
$a_tab['document_operation_div']=array('id'=>'document_operation_div'.$div,'label'=>_('Document').$str_nb_doc,'display'=>'block');
$a_tab['linked_action_div']=array('id'=>'linked_action_div'.$div,'label'=>_('Actions Gestion').$str_nb_fu,'display'=>'none');
$a_tab['analytic_div']=array('id'=>'analytic_div'.$div,'label'=>_('Comptabilité Analytique'),'display'=>'none');
$a_tab['supplemental_doc_div']=array('id'=>'supplemental_doc_div'.$div,'label'=>_('Documents supplémentaires').$str_nb_sup_doc,'display'=>'none');
//var $g_parameter \Noalyss_Parameter_Folder
global $g_parameter;


 
// show tabs
if ( $div != "popup") :
 $a_tab['document_operation_div']['display']='block';
 $tabs=array_column($a_tab,"id");

?>
<input type="hidden" id="<?=$div?>tab" value="<?=join(",",$tabs)?>">
<ul  class="tabs">
    <?php foreach ($a_tab as $idx=>$a_value): ?>
    <?php 
        $class=($a_value['display']=='block') ?"tabs_selected":"tabs"
    ?>
    <li class="<?php echo $class?>">
        <?php $div_tab_id=$a_value['id'];?>
        <?php if ( $div_tab_id == "supplemental_doc_div".$div):?>
            <a href="javascript:void(0)" onclick="unselect_other_tab(this.parentNode.parentNode);this.parentNode.className='tabs_selected' ;Supplement_Document.refresh_list('<?=\Dossier::id()?>','<?=$div?>','<?=$obj->jr_id?>');show_tabs($F('<?=$div?>tab').split(','),'<?php echo $div_tab_id; ?>');"><?php echo _($a_value['label'])?></a>
        <?php else: ?>
            <a href="javascript:void(0)" onclick="unselect_other_tab(this.parentNode.parentNode);this.parentNode.className='tabs_selected' ;show_tabs($F('<?=$div?>tab').split(','),'<?php echo $div_tab_id; ?>');"><?php echo _($a_value['label'])?></a>
        <?php endif; ?>
    </li>
    <?php    endforeach; ?>
</ul>
<div style="clear:both"></div>
<?php
else :
    foreach ($a_tab as $idx=>$a_value):
    $a_tab[$idx]['display']='block';
    endforeach; 
endif;
?>


<?php
    $cmd=new IText('BON_COMMANDE',$obj->info->command);
    $other=new IText('OTHER',$obj->info->other);
?>
        <div id="writing_div<?php echo $div;?>" class="myfieldset" style="display:<?php echo $a_tab['writing_div']['display']?>">
          <?php 
          // display title only in popup
          if ($div == 'popup') :
          ?> 
                <h1 class="legend"><?php echo $a_tab['writing_div']['label']?></h1>
          <?php endif; ?>

<div class="content">
            <?php
           
            ?>
            <table class="result">
                <tr>
                    <?php
                    echo th(_('Poste Comptable'));
                    echo th(_('Quick Code'));
                    echo th(_('Libellé'));
                    echo th(_('Débit'), ' style="text-align:right"');
                    echo th(_('Crédit'), ' style="text-align:right"');
                    echo '</tr>';
                    for ($e = 0; $e < count($detail->det->array); $e++)
                    {
                        $row = '';
                        $q = $detail->det->array;
                        $view_history = HtmlInput::history_account($q[$e]['j_poste'], $q[$e]['j_poste'], "", $exercice);
                                
                        $row.=td($view_history);
                        if ($q[$e]['j_qcode'] != '')
                        {
                            $fiche = new Fiche($cn);
                            $fiche->get_by_qcode($q[$e]['j_qcode']);
                            $view_history = HtmlInput::history_card($fiche->id,  $q[$e]['j_qcode'],"",$exercice);
                        } else
                            $view_history = '';
                        $row.=td($view_history);
                        
                        if ($q[$e]['j_text']=="")
                        {
                            if ($q[$e]['j_qcode'] != '')
                            {
                            // nom de la fiche
                                $ff = new Fiche($cn);
                                $ff->get_by_qcode($q[$e]['j_qcode']);
                                $row.=td($ff->get_attribute(h(ATTR_DEF_NAME)));
                            } else
                            {
                                // libellé du compte
                                $name = $cn->get_value('select pcm_lib from tmp_pcmn where pcm_val=$1', array($q[$e]['j_poste']));
                                $row.=td(h($name));
                            }
                        }
                        else 
                            $row.=td(h($q[$e]['j_text']));
                        
                        $montant = td(nbm($q[$e]['j_montant']), 'class="num"');
                        $row.=($q[$e]['j_debit'] == 't') ? $montant : td('');
                        $row.=($q[$e]['j_debit'] == 'f') ? $montant : td('');
                        $class=($e%2==0)?' class="even"':'class="odd"';

                        echo tr($row,$class);
                    }
                    ?>
            </table>
        </div>
</div>
<div id="info_operation_div<?php echo $div;?>" class="myfieldset" style="display:<?php echo $a_tab['info_operation_div']['display']?>">
    <?php 
          // display title only in popup
          if ($div == 'popup') :
          ?> 
                <h1 class="legend"><?php echo $a_tab['info_operation_div']['label']?></h1>
          <?php endif; ?>
    <table>
        <tr>
            <td><?php echo _(" Bon de commande")?>   :</td><td> <?php echo Icon_Action::infobulle(31)." ".$cmd->input();  ?></td>
        </tr>
        <tr>
            <td> <?php echo _("Autre information")?> : </td><td><?php echo Icon_Action::infobulle(30)." ".$other->input();?></td>
        </tr>
        <tr>
            <td>
                <?=_("Type opération")?>
            </td>
            <td>
                <?php
                    // Opération type
                    
                    echo Acc_Operation::select_operation_type($detail->det->jr_optype)->input();
                ?>
            </td>
        </tr>
    </table>
</div>
<div id="linked_operation_div<?php echo $div;?>" style="display:<?php echo $a_tab['linked_operation_div']['display']?>" class="myfieldset">
 <?php 
          // display title only in popup
          if ($div == 'popup') :
          ?> er
                <h1 class="legend"><?php echo $a_tab['linked_operation_div']['label']?></h1>
          <?php endif; ?>
<?php 

if ($aRap  != null ) {
  $amount_tva_include=(isset($total_tvac))?$total_tvac:$detail->det->jr_montant;
  $tableid="tb".$div;
  $total_rec=0;
  $operation=new Acc_Operation($cn);
  $operation->set_id($jr_id);
  echo '<table id="'.$tableid.'">';
  for ($e=0;$e<count($aRap);$e++)  {
    $opRap=new Acc_Operation($cn);
    $opRap->jr_id=$aRap[$e];
    $internal=$opRap->get_internal();
    $array_jr=$cn->get_array('select jr_date,jr_pj_number,jr_montant,jr_comment , jr_internal ,jr_optype
                                from jrn where jr_id=$1',
        array($aRap[$e]));
    $amount=$array_jr[0]['jr_montant'];
    switch (substr($array_jr[0]['jr_internal'],0,1)) {
        case 'A':
            $amount = $cn->get_value("select sum(qp_price+qp_vat+qp_nd_tva+qp_nd_tva_recup-qp_vat_sided) from quant_purchase qp 
                                            where qp_internal=$1",
                array($internal));
            // add additional tax if any
            $add=$operation->get_sum_other_tax();
            $amount=noalyss_bcadd($amount,$add,2);
            break;
        case 'V':
            $amount=$cn->get_value("select sum(qs_price+qs_vat-qs_vat_sided) from quant_sold qs  
                                        where qs_internal=$1",
                array($internal));
            // add additional tax if any
            $add=$operation->get_sum_other_tax();
            $amount=bcadd($amount??0,$add??0,2);
            break;
    }
    $total_rec=bcadd($total_rec,$amount??0);
    $str="modifyOperation(".$aRap[$e].",".$gDossier.")";
    
    // If write access , allow to drop Reconciles operations
    if ( $access=='W') {
            $js="return confirm_box(null,'"._("vous confirmez?")."',";
            $js.=sprintf('function () { dropLink(\'%s\',\'%s\',\'%s\',\'%s\');deleteRowRec(\'%s\',$(\'row%d\'));})',
					  $gDossier,
					  $div,
					  $jr_id,
					   $aRap[$e],
					   $tableid,
                                          $e
					  );
            $remove=Icon_Action::trash(uniqid(), $js);
    }
    else
      $remove='';
    
    $comment=strip_tags($array_jr[0]['jr_comment']??"");
    $pj_nb=h($array_jr[0]['jr_pj_number']);
    echo tr (td(format_date($array_jr[0]['jr_date'])).
            td('<a class="line" href="javascript:void(0)" onclick="'.$str.'" >'.$internal.'</A>').
            td($pj_nb).
            td($comment).
            td(_('montant').'='.nbm($amount)).
            td(_('delta').'='.nbm(bcsub(abs($amount_tva_include),abs($total_rec)))).
            td($remove),' id = "row'.$e.'"');
  }
  echo '</table>';
}
?>
<?php 
if ( $access=='W') {
     $wConcerned=new IConcerned("rapt".$div);
     $wConcerned->amount_id=$obj->det->jr_montant;
     $wConcerned->div="search_reconcile";
     $wConcerned->set_hideOperation( $obj->jr_id);
    echo $wConcerned->input();

}
?>
</div>
<div id="linked_action_div<?php echo $div;?>" style="display:<?php echo $a_tab['linked_action_div']['display']?>" class="myfieldset">
         <?php 
  // display title only in popup
  if ($div == 'popup') :
  ?> 
        <h1 class="legend"><?php echo $a_tab['linked_action_div']['label']?></h1>
  <?php endif; ?>
<?php 
/**
 * show possible linked actions
 */
echo '<ul style="list-style-type:square;">';
for ($i = 0; $i < count($a_followup); $i++)
{
    $remove='';
    if ( $access=='W') $remove=HtmlInput::button_action_remove_operation($a_followup[$i]['ago_id']);
        if ( $div == 'popup')
        {
                echo '<li id="op'.$a_followup[$i]['ago_id'].'">'.HtmlInput::detail_action($a_followup[$i]['ag_id'], h($a_followup[$i]['ag_ref']." ".$a_followup[$i]['ag_title']),0).$remove.'</li>';
        }
        else
        {
                echo '<li id="op'.$a_followup[$i]['ago_id'].'">'.HtmlInput::detail_action($a_followup[$i]['ag_id'], h($a_followup[$i]['ag_ref']." ".$a_followup[$i]['ag_title']),1).$remove.'</li>';
        }
}
echo '</ul>';
$related=new IRelated_Action('related');
$related->id='related'.$div;
 if ( $access=='W') echo $related->input();
echo '</div>';
?>

<?php 
//------------------------------------------------
// Receipt
//------------------------------------------------
require_once NOALYSS_TEMPLATE.'/ledger_detail_file.php';
?>
<?php
//------------------------------------------------
// Receipt supplemental_doc_div
//------------------------------------------------
require_once NOALYSS_TEMPLATE."/ledger_detail_sup_files.php";
?>


<div id="analytic_div<?php echo $div;?>" style="overflow:auto;display:<?php echo $a_tab['analytic_div']['display']?>">
   <?php
    if ($div == 'popup') :
    ?> 
        <h1 class="legend"><?php echo $a_tab['analytic_div']['label']?></h1>
  <?php endif; ?>
    <?php if ( $owner->MY_ANALYTIC != "nu") : 
        if ( strpos($str_anc,'<td>') == true ):
        ?>
     
                <table class="result">
                            <?php echo $str_anc;?>
                </table>
        <?php else: ?>
        <span class="notice">
        <?php echo _('Aucune donnée'); ?>
            </span>
        <?php endif;?>
<?php else:?>
    <span class="notice">
    <?php echo _('Non utilisée'); ?>
    </span>
<?php endif;?>
</div>
<?php
      echo '<p style="text-align:center">';

if ( $div != 'popup' ) {
  $a=new IButton('Fermer',_('Fermer'));
  $a->label=_("Fermer");
  $a->javascript="removeDiv('".$div."')";
  echo $a->input();
} else {
    echo HtmlInput::hidden('p_jrn',$oLedger->id);
}

?>

<?php 

/**
 * if you can write
 */
  if ( $access=='W') {
  echo HtmlInput::submit('save',_('Sauver'),'onClick="return verify_ca(\'popup\');"');
  $owner=new Noalyss_Parameter_Folder($cn);
  if ($owner->MY_ANALYTIC != 'nu' /*&& $div=='popup' */){
      
      $select_box->add_javascript(_("Vérification CA"), sprintf("verify_ca('%s')",$div));
  }

  $per=new Periode($cn,$obj->det->jr_tech_per);
  if ( $per->is_closed() == 0 && $owner->MY_STRICT=='N' && $g_user->check_action(RMOPER)==1)
  {
    $javascript="return confirm_box(null,content[50],function () {removeOperation('".$obj->det->jr_id."',".dossier::id().",'".$div."')})";
    $select_box->add_javascript(_("Supprimer"), $javascript);
  }
 //----------------------------------------------------
 // Extourne
 //----------------------------------------------------
    $select_box->add_javascript(_("Extourne"), sprintf("g('ext%s').style.display='block'",$div));

 //-------------------------------------------------------------------
 // Duplicate
 //-------------------------------------------------------------------
 $select_box->add_javascript(_("Dupliquer"),sprintf("duplicate_operation('%s','%s')",Dossier::id(),$obj->jr_id));

 //-------------------------------------------------------------------
 // Export PDF
 //-------------------------------------------------------------------
 $select_box->add_url(_("Export PDF"),   "export.php?".
         http_build_query(array("act"=>"PDF:operation_detail","gDossier"=>Dossier::id(),"operation_id"=>$obj->jr_id))); 
 
 
echo $select_box->input();
echo '</p>';
echo '</form>';

  echo '<div id="ext'.$div.'" class="inner_box" style="position:absolute;top:40px;display:none">';
  $date=new IDate('ext_date');
  $extourne_label=new IText("ext_label");
  $extourne_label->size=40;
  $r="<form id=\"form_".$div."\" onsubmit=\"return false;\">";
  $r.=HtmlInput::hidden('jr_id',$obj->jr_id)
      . HtmlInput::hidden('div',$div).dossier::hidden().HtmlInput::hidden('act','reverseop');
  $r.=HtmlInput::title_box(_('Extourner'), 'ext'.$div, 'hide');
  $r.="<p>";
  $r.= _("Extourner une opération vous permet de l'annuler par son écriture inverse");
  $r.="</p>";

  $r.="<p>";
  $r.=_("entrez une date")." :".$date->input();
  $r.="</p>";

  $r.="<p>";
  $r.=_("Libellé")." :".$extourne_label->input();
  $r.="</p>";

  
  $r.='<p  style="text-align:center">';
  $r.=HtmlInput::submit('x','accepter',
          'onclick="confirm_box($(\'form_'.$div.'\'),content[50],function () {$(\'form_'.$div.'\').divname=\''.$div.'\';reverseOperation($(\'form_'.$div.'\'))}); return false"');
  $r.=HtmlInput::button_hide( "ext".$div);
    $r.="</p>";
  $r.='</form>';
  echo $r;
  echo '</div>';



}else {
    echo '</p>';
}

