<?php
/**
 * Plugin Name: WDP Facture Groupe
 */
require plugin_dir_path(__FILE__) . 'vendor/autoload.php';


//if ( !class_exists( 'WDP_Facture_Groupe_CLI' ) && class_exists( 'WP_CLI' ) ) {



class WDP_Facture_Groupe_CLI extends WP_CLI_Command
{

    protected $mpdf;

    public function __construct()
    {
        $this->mpdf = new \Mpdf\Mpdf([
            'margin_left' => 20,
            'margin_right' => 15,
            'margin_top' => 80,
            'margin_bottom' => 25,
            'margin_header' => 10,
            'margin_footer' => 10


//                'mode' => 'fr-FR',
//                'format' => 'A4',
//                'default_font_size' => "",
//                'default_font' => "",
//                'margin_left' => 10,
//                'margin_right' => 10,
//                'margin_top' => 10,
//                'margin_bottom' => 10,
//                'margin_footer' => 15,
//                'setAutoBottomMargin' => 'stretch',
//                'setAutoTopMargin' => 'stretch', 'orientation'=>'P'
        ]);
//            $this->mpdf->SetDocTemplate('template.pdf', true);  //HERE YOU CAN ATTACH THE PDF TEMPLATE HERE


    }

    public function regeneratePDF()
    {
        $this->mpdf = new \Mpdf\Mpdf([
            'margin_left' => 20,
            'margin_right' => 15,
            'margin_top' => 80,
            'margin_bottom' => 25,
            'margin_header' => 10,
            'margin_footer' => 10

//                'mode' => 'fr-FR',
//                'format' => 'A4',
//                'default_font_size' => "",
//                'default_font' => "",
//                'margin_left' => 10,
//                'margin_right' => 10,
//                'margin_top' => 10,
//                'margin_bottom' => 10,
//                'margin_footer' => 15,
//                'setAutoBottomMargin' => 'stretch',
//                'setAutoTopMargin' => 'stretch', 'orientation'=>'P'
        ]);
//            $this->mpdf->SetDocTemplate('template.pdf', true);  //HERE YOU CAN ATTACH THE PDF TEMPLATE HERE

    }

    public function execute_commands($args, $assoc_args)
    {

        WP_CLI::line('Hello');
    }


    private function getStaff()
    {
        global $wpdb;
        $queryStaff = 'SELECT id, name, email, is_active, locations FROM `lmm_bkntc_staff`';
//
        $resultStaff = $wpdb->get_results($queryStaff);

        return $resultStaff;
    }

    private function getAdresseWithIdLocation($idLocation)
    {
        global $wpdb;
        $queryLocation = 'SELECT address FROM `lmm_bkntc_locations` WHERE id=' . (int)$idLocation . ' LIMIT 1';

        $resultLocation = $wpdb->get_row($queryLocation);

        if (!empty($resultLocation)) {
            return $resultLocation->address;
        }
        return '';
    }

    public function write()
    {
        global $wpdb;
        $month_ini = new DateTime("first day of previous month 00:00:00");
        $month_end = new DateTime("last day of previous month 23:59:59");

        $debutList = $month_ini->format('d-m-Y');
        $finList = $month_end->format('d-m-Y');


        $staffArray = $this->getStaff();

        foreach ($staffArray as $rowStaff) {

//                var_dump($rowStaff->locations); exit;
            $arrayIdLocations = explode(',', $rowStaff->locations);
            if (empty($arrayIdLocations) || count($arrayIdLocations) != 1) {
                $adresse = '';
            } else {
                $idLocation = $arrayIdLocations[0];

//                    var_dump($arrayIdLocations);
//                    var_dump($idLocation);
//                    exit;
                $adresse = $this->getAdresseWithIdLocation($idLocation);
            }

            $avocatAdresseTop = $rowStaff->name . '<br />' . $adresse . '<br />';

            $query = 'SELECT c.id as id_customer, c.first_name as firstname_cutomer, c.last_name as lastname_cutomer, st.`name` as name_staff, st.`email` as email_staff, FROM_UNIXTIME(a.created_at) as dateStr, a.`paid_amount` as prixTTC FROM `lmm_bkntc_appointments` as a LEFT JOIN `lmm_bkntc_services` as s ON a.`service_id` = s.`id` LEFT JOIN `lmm_bkntc_staff` as st ON a.`staff_id` = st.`id` LEFT JOIN `lmm_bkntc_customers` as c ON a.`customer_id` = c.`id` WHERE a.`staff_id`=' . $rowStaff->id . ' AND a.`payment_status`="paid" AND FROM_UNIXTIME(a.`created_at`, "%Y-%m-%d %H:%i:%s") BETWEEN "' . $month_ini->format('Y-m-d H:i:s') . '" AND "' . $month_end->format('Y-m-d H:i:s') . '"';
            $resultAppointments = $wpdb->get_results($query);

            $query = 'SELECT c.id as id_customer, c.first_name as firstname_cutomer, c.last_name as lastname_cutomer, st.`name` as name_staff, st.`email` as email_staff, FROM_UNIXTIME(a.created_at) as dateStr, a.`paid_amount` as prixTTC FROM `lmm_bkntc_appointments` as a LEFT JOIN `lmm_bkntc_services` as s ON a.`service_id` = s.`id` LEFT JOIN `lmm_bkntc_staff` as st ON a.`staff_id` = st.`id` LEFT JOIN `lmm_bkntc_customers` as c ON a.`customer_id` = c.`id` WHERE a.`staff_id`=' . $rowStaff->id . ' AND a.`payment_status`="paid" AND FROM_UNIXTIME(a.`created_at`, "%Y-%m-%d %H:%i:%s") BETWEEN "' . $month_ini->format('Y-m-d H:i:s') . '" AND "' . $month_end->format('Y-m-d H:i:s') . '"';
            $resultAppointments = $wpdb->get_results($query);

//                $query = 'SELECT c.meta_key, meta_value WHERE user_id=';
            // Infos de facturation
//                billing_first_name
//                billing_last_name
//                billing_company
//                billing_address_1
//                billing_address_2
//                billing_city
//                billing_postcode
//                billing_country

//                $queryLieu =
//                    LEFT JOIN `lmm_bkntc_locations` as lo ON lo.id=st.locations

//var_dump($resultAppointments); exit;

            $data = [];
            $totalHT = 0;
            $totalHTAvocat = 0;
            $totalTVA = 0;
            $totalTVAAvocat = 0;
            $totalTTC = 0;
            $totalTTCAvocat = 0;
            $ligneStyle = 0;
//                $string .= $resultAppointments->name . ' ' . $resultAppointments->email . ' : ' . PHP_EOL;
            foreach ($resultAppointments as $rowAppointment) {

                $emailAvocat = $rowAppointment->email_staff;
                $description = $rowAppointment->dateStr . ' ' . ' ' . $rowAppointment->firstname_cutomer . ' ' . $rowAppointment->lastname_cutomer . ' (N° client : ' . $rowAppointment->id_customer . ') : ' . PHP_EOL;
//                    $string .= $description;
//                    $data[]=[$rowAppointment->dateStr, $description];

                // ! Le prix total TTC est routé en 70% pour l'avocat
                $prixTTCAvocat = round($rowAppointment->prixTTC * 0.7, 2);
                $totalTTCAvocat += $prixTTCAvocat;

                $totalTTC += $rowAppointment->prixTTC;

                $prixHT = round($rowAppointment->prixTTC / 1.2, 2);
                $prixHTAvocat = round($prixTTCAvocat / 1.2, 2);

                $totalHTAvocat += $prixHTAvocat;
                $totalHT += $prixHT;

                $TVA = $rowAppointment->prixTTC - $prixHT;
                $TVAAvocat = $prixTTCAvocat - $prixHTAvocat;
                $totalTVAAvocat += $TVAAvocat;

                $totalTVA += $TVA;
                $classLigne = ($ligneStyle++ % 2 == 0) ? 'pair' : 'impair';
//                    $htmlTable .= '<tr><td>' . $rowAppointment->dateStr . '</td><td>' . $description . '</td><td>' . $rowAppointment->prix . '</td></tr>';
                $htmlTable .= '<tr><td class="border ' . $classLigne . '">' . $description . '</td><td class="border ' . $classLigne . '">' . $prixHTAvocat . '</td><td class="border ' . $classLigne . '">' . $TVAAvocat . '</td><td class="border ' . $classLigne . '">' . $prixTTCAvocat . '</td></tr>';
//                    $string .= $rowAppointment['dateStr'] . ' : ' . $rowAppointment['service_id'] . ' ' . $rowStaff['paid_amount'] . ' : ' . PHP_EOL;
            }

            $this->regeneratePDF();
            $this->mpdf->AddPage();

            $this->mpdf->SetProtection(array('print'));

            $numeroFacture = file_get_contents('FA_ID.txt');
            if (empty($numeroFacture)) {
                $numeroFacture = 0;
            }
            $numeroFacture++;
            file_put_contents('FA_ID.txt', $numeroFacture);
            $this->mpdf->SetTitle("Facture -" . $numeroFacture);

            $numeroFactureDisplay = 'FSMML' . date('Y') . $numeroFacture;
            $this->mpdf->SetAuthor("MML");
//                $this->mpdf->SetWatermarkText("Paid");
//                $this->mpdf->showWatermarkText = true;
//                $this->mpdf->watermark_font = 'DejaVuSansCondensed';
//                $this->mpdf->watermarkTextAlpha = 0.1;
            $this->mpdf->SetWatermarkImage(
                'bg-mml.png',
                0.05,
                'P',
                'P'
            );
//                $this->mpdf->SetWatermarkImage(new \Mpdf\WatermarkImage('bg-mml.png'));
            $this->mpdf->showWatermarkImage = true;

            $this->mpdf->SetDisplayMode('fullpage');

            $this->mpdf->SetHTMLFooter('<div width="100%"><img width="100%" src="footer-img-mml.png"></div>');
            if (!is_file('FA_ID.txt')) {
                file_put_contents('FA_ID.txt', 0);
            }


//                style="background-image: url(\'bg-mml.png\'); background-position: top left;
//             background-repeat: no-repeat;
//             background-image-resize: 4;
//             background-image-resolution: from-image;"


            $html = '
<html>
<head>
<style>
body {font-family: sans-serif;
	font-size: 10pt;
}
p {	margin: 0pt; }
table.items {
	border: 0.1mm solid #000000;
}
td { vertical-align: top; }
.items td {
	border-left: 0.1mm solid #000000;
	border-right: 0.1mm solid #000000;
}
table thead td { background-color: #EEEEEE;
	text-align: center;
	border: 0.1mm solid #000000;
	font-variant: small-caps;
}
.items td.blanktotal {
	background-color: #EEEEEE;
	border: 0.1mm solid #000000;
	background-color: #FFFFFF;
	border: 0mm none #000000;
	border-top: 0.1mm solid #000000;
	border-right: 0.1mm solid #000000;
}
.items td.totals {
	text-align: right;
	border: 0.1mm solid #000000;
}
.items td.cost {
	text-align: center;
}

.items td.pair {
	background-color:#d33f49;
}

.items td.impair {
	background-color:#ffffff;
}
.items td.border {
border:1px solid #000000;
}
</style>
</head>
<body>

<!--mpdf
<htmlpageheader name="myheader">
<table width="100%">
<tr>
<td width="50%" style="color:#000000; "><span style="font-weight: bold; font-size: 14pt;"><img width="150px" src="logo-mml.png"></span><br />25 RUE DE PONTHIEU, .<br />75008 PARIS<br /><span style="font-family:dejavusanscondensed;">&#9742;</span> 0183644680</td>
<td width="50%" style="text-align: right;">Facture N°.<br /><span style="font-weight: bold; font-size: 12pt;">' . $numeroFactureDisplay . '</span></td>
</tr></table><br>
<table width="100%" style="font-family: serif;" cellpadding="10"><tr>
<td width="45%" style="border: none; "></td>
<td width="10%">&nbsp;</td>
<td width="45%" style="border: 0.1mm solid #888888;">' . $avocatAdresseTop . '</td>
</tr></table>
</htmlpageheader>

<htmlpagefooter name="myfooter">
<div style="font-size: 9pt; text-align: center; padding-top: 3mm; "><img src="footer-img-mml.png">
</div>
<div style="border-top: 1px solid #000000; font-size: 9pt; text-align: center; padding-top: 3mm; ">
Page {PAGENO} / {nb}
</div>
</htmlpagefooter>

<sethtmlpageheader name="myheader" value="on" show-this-page="1" />
<sethtmlpagefooter name="myfooter" value="on" />
mpdf-->






<br><div style="text-align: right">Paris, le ' . date('d-m-Y') . '</div><br>';
            $html .= '<div style="text-align: left">Par courriel : ' . $emailAvocat . '</div><br>';
            $objetMail = 'Votre facture n°' . $numeroFactureDisplay . ' – utilisation des services du ' . $month_ini->format('d/m/Y') . ' au ' . $month_end->format('d/m/Y') . ' inclus';
            $html .= '<div style="text-align: left">Objet : ' . $objetMail . '</div><br />';
            $html .= '<table class="items" style="font-size: 9pt; border-collapse: collapse; " cellpadding="8">
<tr><td class="border impair">Montant Total HT</td><td class="border impair">' . $totalHTAvocat . '</td></tr>
<tr><td class="border pair">Total TVA</td><td class="border pair">' . $totalTVAAvocat . '</td></tr>
<tr><td class="border impair">Montant Total TTC</td><td class="border impair">' . $totalTTCAvocat . '</td></tr>
</table><br>';


            $html .= '<table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; " cellpadding="8">
<thead>
<tr>
<td width="60%">Consultation(s) Visio</td>
<td width="15%">Prix HT</td>
<td width="10%">TVA</td>
<td width="15%">Prix TTC</td>
</tr>
</thead>
<tbody>';

            $html .= $htmlTable;

//<!-- ITEMS HERE -->
//<tr>
//<td align="center">MF1234567</td>
//<td align="center">10</td>
//<td>Large pack Hoover bags</td>
//<td class="cost">&pound;2.56</td>
//<td class="cost">&pound;25.60</td>
//</tr>
//<tr>
//<td align="center">MX37801982</td>
//<td align="center">1</td>
//<td>Womans waterproof jacket<br />Options - Red and charcoal.</td>
//<td class="cost">&pound;102.11</td>
//<td class="cost">&pound;102.11</td>
//</tr>
//<tr>
//<td align="center">MR7009298</td>
//<td align="center">25</td>
//<td>Steel nails; oval head; 30mm x 3mm. Packs of 1000.</td>
//<td class="cost">&pound;12.26</td>
//<td class="cost">&pound;325.60</td>
//</tr>
//<tr>
//<td align="center">MF1234567</td>
//<td align="center">10</td>
//<td>Large pack Hoover bags</td>
//<td class="cost">&pound;2.56</td>
//<td class="cost">&pound;25.60</td>
//</tr>
//<tr>
//<td align="center">MX37801982</td>
//<td align="center">1</td>
//<td>Womans waterproof jacket<br />Options - Red and charcoal.</td>
//<td class="cost">&pound;102.11</td>
//<td class="cost">&pound;102.11</td>
//</tr>
//<tr>
//<td align="center">MR7009298</td>
//<td align="center">25</td>
//<td>Steel nails; oval head; 30mm x 3mm. Packs of 1000.</td>
//<td class="cost">&pound;12.26</td>
//<td class="cost">&pound;325.60</td>
//</tr>
//<tr>
//<td align="center">MF1234567</td>
//<td align="center">10</td>
//<td>Large pack Hoover bags</td>
//<td class="cost">&pound;2.56</td>
//<td class="cost">&pound;25.60</td>
//</tr>
//<tr>
//<td align="center">MX37801982</td>
//<td align="center">1</td>
//<td>Womans waterproof jacket<br />Options - Red and charcoal.</td>
//<td class="cost">&pound;102.11</td>
//<td class="cost">&pound;102.11</td>
//</tr>
//<tr>
//<td align="center">MR7009298</td>
//<td align="center">25</td>
//<td>Steel nails; oval head; 30mm x 3mm. Packs of 1000.</td>
//<td class="cost">&pound;12.26</td>
//<td class="cost">&pound;325.60</td>
//</tr>
//<tr>
//<td align="center">MF1234567</td>
//<td align="center">10</td>
//<td>Large pack Hoover bags</td>
//<td class="cost">&pound;2.56</td>
//<td class="cost">&pound;25.60</td>
//</tr>
//<tr>
//<td align="center">MX37801982</td>
//<td align="center">1</td>
//<td>Womans waterproof jacket<br />Options - Red and charcoal.</td>
//<td class="cost">&pound;102.11</td>
//<td class="cost">&pound;102.11</td>
//</tr>
//<tr>
//<td align="center">MR7009298</td>
//<td align="center">25</td>
//<td>Steel nails; oval head; 30mm x 3mm. Packs of 1000.</td>
//<td class="cost">&pound;12.26</td>
//<td class="cost">&pound;325.60</td>
//</tr>
//<tr>
//<td align="center">MF1234567</td>
//<td align="center">10</td>
//<td>Large pack Hoover bags</td>
//<td class="cost">&pound;2.56</td>
//<td class="cost">&pound;25.60</td>
//</tr>
//<tr>
//<td align="center">MX37801982</td>
//<td align="center">1</td>
//<td>Womans waterproof jacket<br />Options - Red and charcoal.</td>
//<td class="cost">&pound;102.11</td>
//<td class="cost">&pound;102.11</td>
//</tr>
//<tr>
//<td align="center">MF1234567</td>
//<td align="center">10</td>
//<td>Large pack Hoover bags</td>
//<td class="cost">&pound;2.56</td>
//<td class="cost">&pound;25.60</td>
//</tr>
//<tr>
//<td align="center">MX37801982</td>
//<td align="center">1</td>
//<td>Womans waterproof jacket<br />Options - Red and charcoal.</td>
//<td class="cost">&pound;102.11</td>
//<td class="cost">&pound;102.11</td>
//</tr>
//<tr>
//<td align="center">MR7009298</td>
//<td align="center">25</td>
//<td>Steel nails; oval head; 30mm x 3mm. Packs of 1000.</td>
//<td class="cost">&pound;12.26</td>
//<td class="cost">&pound;325.60</td>
//</tr>
//<tr>
//<td align="center">MR7009298</td>
//<td align="center">25</td>
//<td>Steel nails; oval head; 30mm x 3mm. Packs of 1000.</td>
//<td class="cost">&pound;12.26</td>
//<td class="cost">&pound;325.60</td>
//</tr>
//<tr>
//<td align="center">MF1234567</td>
//<td align="center">10</td>
//<td>Large pack Hoover bags</td>
//<td class="cost">&pound;2.56</td>
//<td class="cost">&pound;25.60</td>
//</tr>
//<tr>
//<td align="center">MX37801982</td>
//<td align="center">1</td>
//<td>Womans waterproof jacket<br />Options - Red and charcoal.</td>
//<td class="cost">&pound;102.11</td>
//<td class="cost">&pound;102.11</td>
//</tr>
//<tr>
//<td align="center">MR7009298</td>
//<td align="center">25</td>
//<td>Steel nails; oval head; 30mm x 3mm. Packs of 1000.</td>
//<td class="cost">&pound;12.26</td>
//<td class="cost">&pound;325.60</td>
//</tr>
//<!-- END ITEMS HERE -->
//<tr>
//<td class="blanktotal" colspan="3" rowspan="6"></td>
//<td class="totals">Subtotal:</td>
//<td class="totals cost">&pound;1825.60</td>
//</tr>
//<tr>
//<td class="totals">Tax:</td>
//<td class="totals cost">&pound;18.25</td>
//</tr>
//<tr>
//<td class="totals">Shipping:</td>
//<td class="totals cost">&pound;42.56</td>
//</tr>
//<tr>
//<td class="totals"><b>TOTAL:</b></td>
//<td class="totals cost"><b>&pound;1882.56</b></td>
//</tr>
//<tr>
//<td class="totals">Deposit:</td>
//<td class="totals cost">&pound;100.00</td>
//</tr>
//<tr>
//<td class="totals"><b>Balance due:</b></td>
//<td class="totals cost"><b>&pound;1782.56</b></td>
//</tr>
            $html .= '</tbody>
</table>

<br>
<div style="text-align: center; font-style: italic;">Mode de règlement : Prélèvement automatique par l\’organisme de paiement MOLLIE
Conformément aux dispositions des articles L.441-6, D.441-5 et L.441-3 du Code de Commerce, le non-respect des conditions de paiement entraînera des intérêts de retard ainsi que l\’application de plein droit d’une indemnité forfaitaire de 40 € pour frais de recouvrement.

TVA Acquittée sur encaissement récupérable lors du paiement.
</div>


</body>
</html>
';


            $this->mpdf->WriteHTML($html);

            $this->mpdf->Output('FACTURE_' . $numeroFactureDisplay . '_' . $rowStaff->name . '_du_' . $debutList . '_au_' . $finList . '.pdf');
//                wp_mail(
//                    'webdevphp7@gmail.com',
//                    $objetMail,
//                    'test message',
//                    ''
//                );
            mail('webdevphp7@gmail.com', $objetMail, 'test');
//                use PHPMailer\PHPMailer\PHPMailer;
//                use PHPMailer\PHPMailer\SMTP;
//                use PHPMailer\PHPMailer\Exception;
//
////Load Composer's autoloader
//                require 'vendor/autoload.php';
//
////Create an instance; passing `true` enables exceptions
//                $mail = new PHPMailer(true);
//
//                try {
//                    //Server settings
//                    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
//                    $mail->isSMTP();                                            //Send using SMTP
//                    $mail->Host       = 'smtp.example.com';                     //Set the SMTP server to send through
//                    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
//                    $mail->Username   = 'user@example.com';                     //SMTP username
//                    $mail->Password   = 'secret';                               //SMTP password
//                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
//                    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//
//                    //Recipients
//                    $mail->setFrom('from@example.com', 'Mailer');
//                    $mail->addAddress('joe@example.net', 'Joe User');     //Add a recipient
//                    $mail->addAddress('ellen@example.com');               //Name is optional
//                    $mail->addReplyTo('info@example.com', 'Information');
//                    $mail->addCC('cc@example.com');
//                    $mail->addBCC('bcc@example.com');
//
//                    //Attachments
//                    $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
//                    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name
//
//                    //Content
//                    $mail->isHTML(true);                                  //Set email format to HTML
//                    $mail->Subject = 'Here is the subject';
//                    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
//                    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
//
//                    $mail->send();
//                    echo 'Message has been sent';
//                } catch (Exception $e) {
//                    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
//                }
        }
    }

}

$instance = new WDP_Facture_Groupe_CLI();

WP_CLI::add_command('wdpfacturegroupe', $instance);
//    }



