<?php

define("LIBERATIONSWEB", 20091223);

session_start();

//Librairie de fonctions
require_once(__DIR__ . '/vendor/autoload.php');
require_once("lib/libconfig.inc.php");
require_once("lib/libsession.inc.php");
require_once("lib/libfonctions.inc.php");
require_once("lib/libmysql.inc.php");
require_once("lib/libencode.inc.php");
require_once("lib/libcourriel.inc.php");
require_once("lib/libliberations.inc.php");
require_once("lib/libcentrale.inc.php");
require_once('fpdf/fpdf.php');

class PDF extends FPDF {

    var $NomEmployeur;
    var $NomEmploye;
    var $DateLiberation;
    var $NoArticle;
    var $Commentaire;
    var $duree;
    var $Lieu;
    var $Quipaye;
    var $Datepaiement;
    var $Texte21;
    var $Texte22;
    var $syndicatnom;
    var $niveau;
    var $configCentrale;

    function WordWrap(&$text, $maxwidth) {
        $text = trim($text);
        if ($text === '') {
            return 0;
        }
        $space = $this->GetStringWidth(' ');
        $lines = explode("\n", $text);
        $text = '';
        $count = 0;

        foreach ($lines as $line) {
            $words = preg_split('/ +/', $line);
            $width = 0;

            foreach ($words as $word) {
                $wordwidth = $this->GetStringWidth($word);
                if ($wordwidth > $maxwidth) {
                    // Word is too long, we cut it
                    for ($i = 0; $i < strlen($word); $i++) {
                        $wordwidth = $this->GetStringWidth(substr($word, $i, 1));
                        if ($width + $wordwidth <= $maxwidth) {
                            $width += $wordwidth;
                            $text .= substr($word, $i, 1);
                        } else {
                            $width = $wordwidth;
                            $text = rtrim($text) . "\n" . substr($word, $i, 1);
                            $count++;
                        }
                    }
                } elseif ($width + $wordwidth <= $maxwidth) {
                    $width += $wordwidth + $space;
                    $text .= $word . ' ';
                } else {
                    $width = $wordwidth + $space;
                    $text = rtrim($text) . "\n" . $word . ' ';
                    $count++;
                }
            }
            $text = rtrim($text) . "\n";
            $count++;
        }
        $text = rtrim($text);
        return $count;
    }

    // ****************************************************
    // Entête de page
    // ****************************************************
    function Header() {
        $Image41 = 'logo/' . $_SESSION["syndicat"] . "." . $_SESSION['logo'];
        $this->Image($Image41, 181, 25, 47, 22);

        $this->SetXY(26, 26);
        $this->SetTextColor(0, 0, 0);
        $this->SetFont('Times', 'BI', 20);
        $etiquette20 = mb_convert_encoding("Libérations selon paiement", 'ISO-8859-1', 'UTF-8');
        $this->Cell(93, 10, $etiquette20, 0, 0, 'L');

        $this->SetLineWidth(1);
        $this->Line(25, 50, 228, 50);

        $this->SetY(52);
    }

    // ****************************************************
    // Pied de page
    // ****************************************************
    function Footer() {
        //Numéro de page
        //Positionnement à 1,5 cm du bas
        //Police Arial italique 8
        $this->SetTextColor(0, 0, 0);
        $this->SetY(-10);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');

        $this->SetLineWidth(0);
        $this->Line(26, 205, 244, 205);

        $etiquette43 = $this->configCentrale["syndicat_nom"];
        $etiquette45 = $this->configCentrale["adresse"] . ", " . $this->configCentrale["ville"] .
                " (" . $this->configCentrale["province"] . ") " . $this->configCentrale["codepostal"] .
                " Téléphone : " . str_replace(array("(", ")"), "", $this->configCentrale["telephone"]) .
                " Télécopieur : " . str_replace(array("(", ")"), "", $this->configCentrale["telecopieur"]);

        $this->SetXY(25, 201);
        $this->SetFont('Times', 'B', 9);
        $this->Cell(219, 4, mb_convert_encoding($etiquette43, 'ISO-8859-1', 'UTF-8'), 0, 0, 'C');

        $this->SetXY(25, 205);
        $this->SetFont('Times', 'B', 9);
        $this->Cell(219, 4, mb_convert_encoding($etiquette45, 'ISO-8859-1', 'UTF-8'), 0, 0, 'C');
    }
}

// ****************************************************
// Ajout le total des lib?rations pour chaque employ?
// ****************************************************
function ajoutTotalSommaireEmploye($pdf, $nombredeligne, $calculduree) {
    $pdf->SetX(29);
    $pdf->SetFont('Times', 'B', 9);
    $pdf->Cell(1, 4, mb_convert_encoding("Nombre de libérations :", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

    $pdf->SetX(106);
    $pdf->SetFont('Times', 'B', 9);
    $pdf->Cell(1, 4, mb_convert_encoding("Durée totale :", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

    $pdf->SetX(70);
    $pdf->SetFont('Times', 'B', 9);
    $pdf->Cell(1, 4, $nombredeligne, 0, 0, 'L');

    $pdf->SetX(154);
    $pdf->SetFont('Times', 'B', 9);
    $pdf->Cell(1, 4, sprintf("%02.2f / %dhrs", $calculduree, $calculduree * 8), 0, 0, 'L'); //1 journée correspond à 8 heures

    $pdf->ln();
}

// ****************************************************
// Ajout le total des libérations pour chaque employeur
// ****************************************************
function ajoutTotalSommaireEmployeur($pdf, $nombredeligne2, $calculduree2) {
    $pdf->SetX(29);
    $pdf->SetFont('Times', 'BU', 11);
    $pdf->Cell(1, 4, mb_convert_encoding("Nombre de libérations :", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

    $pdf->SetX(121);
    $pdf->SetFont('Times', 'BU', 11);
    $pdf->Cell(1, 4, mb_convert_encoding("Durée totale :", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

    $pdf->SetX(70);
    $pdf->SetFont('Times', 'BU', 11);
    $pdf->Cell(1, 4, $nombredeligne2, 0, 0, 'L');

    $pdf->SetX(154);
    $pdf->SetFont('Times', 'BU', 11);
    $pdf->Cell(1, 4, sprintf("%02.2f / %dhrs", $calculduree2, $calculduree2 * 8), 0, 0, 'L'); //1 journée correspond à 8 heures

    $pdf->ln();
    $pdf->ln();
}

$i = 0;
unset($sqlparam);
$sqlparam["table"][] = "employes";
$sqlparam["table"][] = "employeurs";
$sqlparam["table"][] = "liberations";
$sqlparam["table"][] = "ligneliberations";
$sqlparam["table"][] = "articles";
$sqlparam["table"][] = "duree";
$sqlparam["join"][] = "employes.refemployeur=employeurs.refemployeur";
$sqlparam["join"][] = "employes.refemploye = liberations.refemploye";
$sqlparam["join"][] = "liberations.refliberation = ligneliberations.refliberation";
$sqlparam["join"][] = "ligneliberations.refarticle = articles.refarticle";
$sqlparam["join"][] = "duree.refduree=ligneliberations.duree";
$sqlparam["champs"][] = "CONCAT(employes.nomfamille,', ',employes.prenom) as nomemploye";
$sqlparam["champs"][] = "employes.numemploye";
$sqlparam["champs"][] = "employeurs.nomemployeur";
$sqlparam["champs"][] = "unix_timestamp(liberations.datedemande) as nombre";
$sqlparam["champs"][] = "If(liberations.typeoperation=2,'Annulation','Demande') AS toperation";
$sqlparam["champs"][] = "articles.noarticle";
$sqlparam["champs"][] = "unix_timestamp(ligneliberations.dateliberation) as dateliberation";
$sqlparam["champs"][] = "If(liberations.typeoperation=1,duree.dureeNombre,0-dureeNombre) AS calculduree";
$sqlparam["champs"][] = "employes.refemploye";
$sqlparam["champs"][] = "ligneliberations.commentaire";
$sqlparam["champs"][] = "ligneliberations.quipaye";
$sqlparam["champs"][] = "ligneliberations.lieu";
$sqlparam["champs"][] = "DATE_FORMAT(ligneliberations.datepaiement,\"%Y-%m-%d\") as datepaiement";
$sqlparam["ordre"][] = "employeurs.nomemployeur";
$sqlparam["ordre"][] = "CONCAT(employes.nomfamille, ', ', employes.prenom)";
$sqlparam["ordre"][] = "ligneliberations.dateliberation";

//Titre
$mode = "Rapport des libérations selon le paiement";
$rapport_source = "rapport_liberations_paiement";
require("lib/librapports.inc.php");

$result = executerRequeteSql($sqlparam);

// ****************************************************
// Vérification de la présence de détails dans la liste
// ****************************************************
if (!($result && is_array($result) && count($result) > 0)) {
    print"<center>Aucune libérations trouvée!";
    print "<br>";
    print "<input type='button' onclick='javascript:window.close();' value='Fermer'></center>";
    die();
}

// ********************
// Traitement principal
// ********************
//Instanciation de la classe dérivée
$pdf = new PDF('L', 'mm', 'Letter');
$pdf->SetMargins(25, 25);
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->configCentrale = buildConfigCentrale();

$nomemploye = "";
$nomemployeur = "";
$debut = 0;
$calculduree = 0;
$nombredeligne = 0;
$calculduree2 = 0;
$nombredeligne2 = 0;
$debutemploye = 0;
$debutemployeur = 0;

$pdf->syndicatnom = $_SESSION["syndicatnom"];
$pdf->niveau = $_SESSION['gestion_site'];

// *******************
// Lecture des données
// *******************
foreach ($result as $clef => $champs) {

    if ($nomemploye != $champs["nomemploye"]) { //0
        if ($debutemploye > 0) {
            ajoutTotalSommaireEmploye($pdf, $nombredeligne, $calculduree);
            $calculduree = 0;
            $nombredeligne = 0;
        }

        if ($nomemployeur != $champs["nomemployeur"] && $debutemployeur > 0) {
            ajoutTotalSommaireEmployeur($pdf, $nombredeligne2, $calculduree2);
            $nomemployeur = $champs["nomemployeur"];
            $calculduree2 = 0;
            $nombredeligne2 = 0;
        }

        //Ajout du nom de l'employé avec son employeur
        $NomEmploye = mb_convert_encoding($champs["nomemploye"], 'ISO-8859-1', 'UTF-8');
        $PremierDeNomEmployeur = $champs["nomemployeur"];

        $pdf->SetX(25);
        $pdf->SetFillColor(199, 199, 199);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(203, 12, " ", 0, 0, 'L', true);
        $pdf->SetFillColor(255, 255, 255);

        $pdf->SetX(25);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(48, 4, $NomEmploye, 0, 0, 'L');
        if (!isset($bHavEmployeur)) {
            $pdf->SetX(74);
            $pdf->SetFont('Times', '', 8);
            $pdf->Cell(72, 4, mb_convert_encoding($PremierDeNomEmployeur, 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');
        } elseif (isset($bHavEmployeur) && $bHavEmployeur && $debut == 0) {
            $pdf->SetXY(25, 45);
            $pdf->SetFont('Times', 'BI', 15);
            $pdf->Cell(72, 4, mb_convert_encoding($PremierDeNomEmployeur, 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');
            $pdf->SetY(52);
        }

        $pdf->ln();
        $pdf->ln();

        //Détail par libérations
        $pdf->SetX(29);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(18, 4, "Date", 0, 0, 'L');

        $pdf->SetX(52);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(17, 4, "Type", 0, 0, 'L');

        $pdf->SetX(70);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(12, 4, "Article", 0, 0, 'L');

        $pdf->SetX(86);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(67, 4, "Commentaire", 0, 0, 'L');

        $pdf->SetX(154);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(16, 4, mb_convert_encoding("Durée", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

        $pdf->SetX(165);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(14, 4, "Lieu", 0, 0, 'L');

        if ($pdf->niveau >= "Oui") {
            $pdf->SetX(190);
            $pdf->SetFont('Times', '', 8);
            $pdf->Cell(20, 4, mb_convert_encoding("Assumée par", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

            $pdf->SetX(208);
            $pdf->SetFont('Times', '', 8);
            $pdf->Cell(26, 4, "Date paiement", 0, 0, 'L');
        }

        $pdf->ln();

        $nomemploye = $champs["nomemploye"];
    }

    $nomemployeur = $champs["nomemployeur"];
    $debutemployeur++;

    $DateLiberation = date("Y-m-d", $champs["dateliberation"]);
    $TOperation = $champs["toperation"];
    $NoArticle = $champs["noarticle"];
    $Commentaire = $champs["commentaire"];
    $CDuree = $champs["calculduree"];
    $lieu = $champs["lieu"];
    $assumerpar = $champs["quipaye"];
    $datepaiement = ($champs["datepaiement"] == "0000-00-00") ? mb_convert_encoding("Non-assigné", 'ISO-8859-1', 'UTF-8') : $champs["datepaiement"];

    $pdf->SetX(29);
    $pdf->SetFont('Times', '', 8);
    $pdf->Cell(18, 4, $DateLiberation, 0, 0, 'L');

    $pdf->SetX(52);
    if ($TOperation == "Annulation") {
        $pdf->SetTextColor(255, 0, 0);
    }
    $pdf->Cell(17, 4, $TOperation, 0, 0, 'L');
    if ($TOperation == "Annulation") {
        $pdf->SetTextColor(0, 0, 0);
    }

    $pdf->SetX(70);
    $pdf->Cell(12, 4, $NoArticle, 0, 0, 'L');

    $pdf->SetX(154);
    if ($TOperation == "Annulation") {
        $pdf->SetTextColor(255, 0, 0);
    }

    $pdf->Cell(16, 4, sprintf("%02.2f/%dh", $CDuree, $CDuree * 8), 0, 0, 'L'); //1 journée correspond à 8 heures

    if ($TOperation == "Annulation") {
        $pdf->SetTextColor(0, 0, 0);
    }

    $pdf->SetX(165);
    $pdf->Cell(14, 4, mb_convert_encoding($lieu, 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

    if ($pdf->niveau >= "Oui") {
        $pdf->SetX(190);
        $pdf->Cell(20, 4, $assumerpar, 0, 0, 'L');

        $pdf->SetX(208);
        $pdf->Cell(26, 4, $datepaiement, 0, 0, 'L');
    }

    $pdf->SetX(86);
    $pdf->WordWrap($Commentaire, 67);
    $pdf->MultiCell(67, 4, mb_convert_encoding($Commentaire, 'ISO-8859-1', 'UTF-8'));

    $pdf->SetTextColor(0, 0, 0);
    //Calcul par employé
    $calculduree = $calculduree + $CDuree;
    $nombredeligne++;

    //Calcul par employeur
    $calculduree2 = $calculduree2 + $CDuree;
    $nombredeligne2++;

    //Nombre de ligne totale
    $debut++;

    //Nombre de ligne totale
    $debutemploye++;
}

ajoutTotalSommaireEmploye($pdf, $nombredeligne, $calculduree);
ajoutTotalSommaireEmployeur($pdf, $nombredeligne2, $calculduree2);

$pdf->Output();
