<?php

    require_once("{$sitepath}autentificare.php");
    require_once("{$sitepath}pagecomponents.php");

    check_connected();
    
    if (!isset($run_from_service))
    {
        $msg_id_aplicatie = getuserdata('msg_id_aplicatie', 0);
        $msg_id_fisier = getuserdata('msg_id_fisier', 0);
        $msg_text = getuserdata('msg_text', '');
        
        $pagina_tabel = getuserdata('pagina_tabel', 1);
        $nrmed = getuserdata('nrmed', 10);
        $sortare = getuserdata('sortare', 1);
        $filtru = getuserdata('filtru', '');
    }
    
    function ScrieInformatiiMedicament($sCodCAS, $sDenumire, $sDCI, $sProducator, $nImpachetare, $sCompensari, $nNrCompensari)
    {
        global $nr_rec;
        $nr_rec ++;
        $sMedicamentAntet = "\n        <tr".(($nr_rec % 2 == 0)?"":" class='even'").">";
        $sMedicamentAntet .= "\n            <td rowspan='$nNrCompensari'>$sCodCAS</td>";
        $sMedicamentAntet .= "\n            <td rowspan='$nNrCompensari'>$sDenumire</td>";
        $sMedicamentAntet .= "\n            <td rowspan='$nNrCompensari'>$sDCI</td>";
        $sMedicamentAntet .= "\n            <td rowspan='$nNrCompensari'>$sProducator</td>";
        $sMedicamentAntet .= "\n            <td rowspan='$nNrCompensari' class='center'>".((int)$nImpachetare)."</td>";
        if ($sCodCAS) echo $sMedicamentAntet.$sCompensari;        
    }
    
    $qNrMedicamente = $connMain->query("
              SELECT COUNT(*) AS NrMed FROM cas_medicamente m
                  JOIN cas_producatori p ON p.IdProducator = m.IdProducator
              WHERE '$data_lista' BETWEEN DataInceput AND IFNULL(DataSfarsit, '9999-12-31')
                  AND ( UPPER(m.Cod) LIKE UPPER('%$filtru%')
                     OR UPPER(m.Denumire) LIKE UPPER('%$filtru%')
                     OR UPPER(p.Nume) LIKE UPPER('%$filtru%')
                     OR UPPER(m.DCI) LIKE UPPER('%$filtru%') )
                  AND m.Cod IN (
                      SELECT Cod FROM cas_compensari
                      WHERE '$data_lista' BETWEEN DataInceput AND IFNULL(DataSfarsit, '9999-12-31')
                      )");
    $nNrMedicamente = 0;
    if ($rNrMedicamente = $qNrMedicamente->fetch_assoc())
        $nNrMedicamente = $rNrMedicamente['NrMed'];
    $nNrPagini = ceil($nNrMedicamente / $nrmed);
    if ($pagina_tabel > $nNrPagini) $pagina_tabel = $nNrPagini;
    if ($pagina_tabel < 1) $pagina_tabel = 1;
    
    $qMedicamente = $connMain->query("
        SELECT
            c2.IdCasCompensare AS ID,
            m4.Cod AS CodCAS,
            m4.Denumire AS Medicament,
            m4.DCI,
            p4.Nume AS Producator,
            m4.CantitatePePachet,
            c2.Sublista,
            c2.CodBoala,
            c2.CodPNS,
            c2.PretMaximUT,
            c2.ValoareCompensare,
            c2.PretMaxim,
            c2.ValoareCompensare,
            c2.PretMaxim - c2.ValoareCompensare AS ValoareDePlata
        FROM (
            SELECT
                m2.IdCasMedicament,
                m2.PretAmanuntUT
            FROM (
                SELECT
                    m1.IdCasMedicament,
                    MIN(c1.PretMaximUT) AS PretAmanuntUT
                FROM cas_medicamente m1
                    JOIN cas_lista l1 ON l1.IdMedicament = m1.IdCasMedicament
                        AND l1.Data = '$data_lista'
                    JOIN cas_compensari c1 ON c1.IdCasCompensare = l1.IdCompensare
                    JOIN cas_producatori p1 ON p1.IdProducator = m1.IdProducator
                WHERE DATE('$data_lista') BETWEEN m1.DataInceput AND IFNULL(m1.DataSfarsit, DATE('9999-12-31'))
                    AND ( UPPER(m1.Cod) LIKE UPPER('%$filtru%')
                       OR UPPER(m1.Denumire) LIKE UPPER('%$filtru%')
                       OR UPPER(p1.Nume) LIKE UPPER('%$filtru%')
                       OR UPPER(m1.DCI) LIKE UPPER('%$filtru%') )
                GROUP BY m1.IdCasMedicament, m1.Denumire
                ORDER BY ".(($sortare == 1)?"PretMaximUT":"Denumire")."
                ) m2
            LIMIT ".(($pagina_tabel - 1) * $nrmed).", ".($nrmed)."
            ) m3
            JOIN cas_medicamente m4 ON m4.IdCasMedicament = m3.IdCasMedicament
            JOIN cas_producatori p4 ON p4.IdProducator = m4.IdProducator
            JOIN cas_lista l2 ON l2.IdMedicament = m4.IdCasMedicament
                AND l2.Data = '$data_lista'
            JOIN cas_compensari c2 ON c2.IdCasCompensare = l2.IdCompensare
        ORDER BY ".(($sortare == 1)?"m3.PretAmanuntUT":"m4.Denumire").", c2.Sublista, c2.CodBoala, c2.CodPNS    
        ");
    echo $connMain->error;
    $nr_rec = 0;
    if ($qMedicamente->num_rows > 0)
    {
        echo "\n<table class='medicamente'>";
        echo "\n    <thead>";
        echo "\n        <tr>";
        echo "\n            <th>Cod CAS</th>";
        echo "\n            <th>Medicament</th>";
        echo "\n            <th>DCI</th>";
        echo "\n            <th>Producător</th>";
        echo "\n            <th>Împachetare</th>";
        echo "\n            <th>Lista</th>";
        echo "\n            <th>Cod boală</th>";
        echo "\n            <th>PNS</th>";
        echo "\n            <th>Preţ amănunt UT</th>";
        echo "\n            <th>Preţ compensat UT</th>";
        echo "\n            <th>Preţ amanunt</th>";
        echo "\n            <th>Preţ compensat</th>";
        echo "\n            <th>Diferenţă de plată</th>";
        echo "\n            <th>Cantitate</th>";
        echo "\n            <th>Acţiune</th>";
        echo "\n        </tr>";
        echo "\n    </thead>";
        echo "\n    <tbody>";
        $sMedicament = "";
        $sDCI = "";
        $sCodCAS = "";
        $sDenumire = "";
        $sProducator = "";
        $nImpachetare = 0;
        $nNrCompensari = 0;
        while ($rMedicamente = $qMedicamente->fetch_assoc())
        {
            $bMedicamentNou = false;
            if ($sCodCAS != $rMedicamente['CodCAS'])
            {
                if ($sCodCAS) ScrieInformatiiMedicament($rMedicamente['CodCAS'], $sDenumire, $sDCI, $sProducator, $nImpachetare, $sMedicament, $nNrCompensari);
                $sMedicament = "";
                $sCodCAS = $rMedicamente['CodCAS'];
                $sDenumire = $rMedicamente['Medicament'];
                $sDCI = $rMedicamente['DCI'];
                $sProducator = $rMedicamente['Producator'];
                $nImpachetare = $rMedicamente['CantitatePePachet'];
                $bMedicamentNou = true;
                $nNrCompensari = 0;
            }
            $nNrCompensari++;
            if (!$bMedicamentNou) $sMedicament .= "\n        <tr".(($nr_rec % 2 == 1)?"":" class='even'").">";
            $sMedicament .= "\n            <td class='center'>{$rMedicamente['Sublista']}</td>";
            $sMedicament .= "\n            <td class='center'>{$rMedicamente['CodBoala']}</td>";
            $sMedicament .= "\n            <td class='center'>{$rMedicamente['CodPNS']}</td>";
            $sMedicament .= "\n            <td class='number'>".number_format($rMedicamente['PretMaximUT'], 6, ',', '.')."</td>";
            $sMedicament .= "\n            <td class='number'>".number_format($rMedicamente['ValoareCompensare'], 6, ',', '.')."</td>";
            $sMedicament .= "\n            <td class='number'>".number_format($rMedicamente['PretMaxim'], 2, ',', '.')."</td>";
            $fValoareCompensare = $rMedicamente['ValoareCompensare'];
            $fPretCompensat = round($fValoareCompensare * $nImpachetare, 2);
            $fRestDePlata = $rMedicamente['PretMaxim'] - $fPretCompensat;
            $sMedicament .= "\n            <td class='number'>".number_format($fPretCompensat, 2, ',', '.')."</td>";
            $sMedicament .= "\n            <td class='number'>".number_format($fRestDePlata, 2, ',', '.')."</td>";
            $sMedicament .= "\n            <td class='butoane'>";
            $sMedicament .= "<input type='text' name='cant{$rMedicamente['ID']}' id='cant{$rMedicamente['ID']}'>";
            $sMedicament .= "\n            </td>";
            $sMedicament .= "\n            <td class='butoane'>";
            $sMedicament .= "<a href='#peloc' onclick='adaugaMedicament({$rMedicamente['ID']})' class='btn_adauga'>Adaugă pe reţetă</a></td>";
            $sMedicament .= "\n        </tr>";            
        }
        if ($sCodCAS) ScrieInformatiiMedicament($sCodCAS, $sDenumire, $sDCI, $sProducator, $nImpachetare, $sMedicament, $nNrCompensari);
        echo "\n        <tr>";
        echo "\n            <th colspan='15' class='nav'>";
        echo "\n                Pagina ";
        for ($i = 1; $i <= 5; $i++)
        {
            if ($i <= $nNrPagini)
            {
                if ($i == $pagina_tabel) 
                    echo "<b>$i</b>&nbsp;";
                else
                    echo "<a href='#peloc' onclick='pagina = $i; requestMedicamente();'>$i</a>&nbsp;";
            }
        }
        if ($pagina_tabel > 8) echo " ..... ";
        for ($i = $pagina_tabel - 2; $i <= $pagina_tabel + 2; $i ++)
        {
            if (($i > 5) && ($i < $nNrPagini - 4))
            {
                if ($i == $pagina_tabel) 
                    echo "<b>$i</b>&nbsp;";
                else
                    echo "<a href='#peloc' onclick='pagina = $i; requestMedicamente();'>$i</a>&nbsp;";                
            }
        }
        if ($nNrPagini - 5 > $pagina_tabel + 2) echo " ..... ";
        for ($i = $nNrPagini - 4; $i <= $nNrPagini; $i ++)
        {
            if ($i > 5)
            {
                if ($i == $pagina_tabel)
                    echo "<b>$i</b>&nbsp;";
                else
                    echo "<a href='#peloc' onclick='pagina = $i; requestMedicamente();'>$i</a>&nbsp;";                
            }
        }
        echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Salt la ";
        echo "<input type='text' style='width: 2em; display: inline' name='pag' id='pag' onkeyup='pagina = this.value; cautaMedicament();'>";
        echo "\n            </th>";
        echo "\n        </tr>";
        echo "\n    </tbody>";
        echo "\n</table>";
    }
    
?>