<?php
/* Copyright (C) 2021       MB Informatique         <info@mb-informatique.fr> */

function approve_holiday($id, $db, $langs)
{
    global $conf, $dolibarr_main_url_root;
    $langs->load("holiday");
    $object = new Holiday($db);
    $object->fetch($id);
    $user = new User($db);
    $user->fetch($object->fk_validator);

// If status is waiting approval and approver is also user
    if ($object->statut == Holiday::STATUS_VALIDATED) {
        $object->oldcopy = dol_clone($object);

        $object->date_valid = dol_now();
        $object->fk_user_valid = $user->id;
        $object->statut = Holiday::STATUS_APPROVED;

        $db->begin();

        $verif = $object->approve($user);
        if ($verif <= 0) {
            setEventMessages($object->error, $object->errors, 'errors');
            $error++;
        }

        // Si pas d'erreur SQL on redirige vers la fiche de la demande
        if (!$error) {
            // Calculcate number of days consummed
            $nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday);
            $soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type);
            $newSolde = ($soldeActuel - $nbopenedday);

            // On ajoute la modification dans le LOG
            $result = $object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $object->fk_type);
            if ($result < 0) {
                $error++;
                setEventMessages(null, $object->errors, 'errors');
            }

            //Update balance
            $result = $object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type);
            if ($result < 0) {
                $error++;
                setEventMessages(null, $object->errors, 'errors');
            }
        }

        if (!$error) {
            // To
            $destinataire = new User($db);
            $destinataire->fetch($object->fk_user);
            $emailTo = $destinataire->email;

            if (!$emailTo) {
                dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
            } else {
                // From
                $expediteur = new User($db);
                $expediteur->fetch($object->fk_validator);
                //$emailFrom = $expediteur->email;		Email of user can be an email into another company. Sending will fails, we must use the generic email.
                $emailFrom = $conf->global->MAIN_MAIL_EMAIL_FROM;

                // Subject
                $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
                if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;

                $subject = $societeName . " - " . $langs->transnoentitiesnoconv("HolidaysValidated");

                // Content
                $message = $langs->transnoentitiesnoconv("Hello") . " " . $destinataire->firstname . ",\n";
                $message .= "\n";

                $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day')) . "\n";

                $message .= "- " . $langs->transnoentitiesnoconv("ValidatedBy") . " : " . dolGetFirstLastname($expediteur->firstname, $expediteur->lastname) . "\n";

                $message .= "- " . $langs->transnoentitiesnoconv("Link") . " : " . $dolibarr_main_url_root . "/holiday/card.php?id=" . $object->id . "\n\n";
                $message .= "\n";

                $trackid = 'leav' . $object->id;

                $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);

                // Envoi du mail
                $result = $mail->sendfile();

                if (!$result) {
                    setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
                    $action = '';
                }
            }
        }

        if (!$error) {
            $db->commit();
        } else {
            $db->rollback();
        }
    }
}

function approve_expensereport($id, $db, $langs, $hidedetails, $hidedesc, $hideref)
{
    global $conf, $urlwithroot;
    $langs->load("expensereport");
    $object = new ExpenseReport($db);
    $object->fetch($id);
    $user = new User($db);
    $user->fetch($object->fk_user_validator);

    $result = $object->setApproved($user);

    if ($result > 0)
    {
        // Define output language
        if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
        {
            $outputlangs = $langs;
            $newlang = '';
            if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
            if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
            if (!empty($newlang)) {
                $outputlangs = new Translate("", $conf);
                $outputlangs->setDefaultLang($newlang);
            }
            $model = $object->model_pdf;
            $ret = $object->fetch($id); // Reload to get new records

            $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
        }
    }

    if ($result > 0)
    {
        // Send mail

        // TO
        $destinataire = new User($db);
        $destinataire->fetch($object->fk_user_author);
        $emailTo = $destinataire->email;

        // CC
        $emailCC = $conf->global->NDF_CC_EMAILS;
        if (empty($emailTo)) $emailTo = $emailCC;

        // FROM
        $expediteur = new User($db);
        $expediteur->fetch($object->fk_user_approve > 0 ? $object->fk_user_approve : $object->fk_user_validator);
        $emailFrom = $expediteur->email;

        if ($emailFrom && $emailTo)
        {
            $filename = array(); $filedir = array(); $mimetype = array();

            // SUBJECT
            $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
            if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;

            $subject = $societeName." - ".$langs->transnoentities("ExpenseReportApproved");

            // CONTENT
            $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
            $link = '<a href="'.$link.'">'.$link.'</a>';
            $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);

            // Rebuilt pdf
            /*
            $object->setDocModel($user,"");
            $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);

            if($resultPDF
            {
                // ATTACHMENT
                $filename=array(); $filedir=array(); $mimetype=array();
                array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
                array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
                array_push($mimetype,"application/pdf");
            }
            */

            $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);

            if ($mailfile)
            {
                // SEND
                $result = $mailfile->sendfile();
                if ($result)
                {
                    $ok = "ok";
                } else {
                    $langs->load("other");
                    if ($mailfile->error)
                    {
                        $mesg = '';
                        $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
                        $mesg .= '<br>'.$mailfile->error;
                        setEventMessages($mesg, null, 'errors');
                    } else {
                        setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
                    }
                }
            } else {
                setEventMessages($mailfile->error, $mailfile->errors, 'errors');
                $action = '';
            }
        } else {
            setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
            $action = '';
        }
    } else {
        setEventMessages($langs->trans("FailedtoSetToApprove"), null, 'warnings');
        $action = '';
    }
}