<?php

class BlitzController extends Controller {

    public function __construct() {
        $this->beforeFilter('csrf');
    }

    public function makeTextBlock($text, $fontfile, $fontsize, $width) {
        $words = explode(' ', $text);
        $lines = array($words[0]);
        $currentLine = 0;
        for ($i = 1; $i < count($words); $i++) {
            $lineSize = imagettfbbox($fontsize, 0, $fontfile, $lines[$currentLine] . ' ' . $words[$i]);
            if ($lineSize[2] - $lineSize[0] < $width) {
                $lines[$currentLine] .= ' ' . $words[$i];
            } else {
                $currentLine++;
                $lines[$currentLine] = $words[$i];
            }
        }
        return $lines;
    }

    public function generate() {

        $edition = Contest::getEdition();

        $band = Band::findOrFail(Input::get('band_id'));

        $bandId = $band->id;
        $bandName = $band->name;
        $template = Input::get('template');
        $zipFolderId = date('Y') . '_' . $edition . '_' . $bandId . '_material_divulgacao_' . $template;
        $zipFilePAth = public_path() . '/uploads/blitzes/' . $zipFolderId . ".zip";

        switch ($template) {
            case 'Template_1':

                $bandName = mb_strtoupper($bandName, 'UTF-8');
                //$font = public_path() . "/assets/fonts/Bluescreens-Round-Bold.ttf";
                $font = public_path() . "/assets/fonts/edp_preon_medium-webfont.ttf";

                // A4 PRINT

                $image1 = imagecreatefrompng(public_path() . "/assets/img/blitz/{$edition}/cartaz_1/CartazA4-BG.png");
                $image_width = imagesx($image1);

                imagealphablending($image1, true);

                $white = imagecolorallocate($image1, 0, 0, 0);

                $fSizeInitial = 60;

                //makeTextBlock($text, $fontfile, $fontsize, $width)
                $finalText = $this->makeTextBlock($bandName, $font, $fSizeInitial, ($image_width * 2) / 2);
                //imagettfbbox ( float $size , float $angle , string $fontfile , string $text )
                for ($i = 0; $i < count($finalText); $i++) {
                    $bbox = imagettfbbox($fSizeInitial, 0, $font, $finalText[$i]);
                    $x = ceil(($image_width - $bbox[2]) / 2);

                    //the first y determines the position of the text in the image
                    //the next determines line spacing

                    if ($i == 0) {
//                        $dist = 600;
                        $dist = 2750;
                        $y = $dist;
                    } else {
                        $y = $y + 90;
                    }


                    // imagefttext("Image", "Font Size", "Rotate Text", "Left Position",
                    // "Top Position", "Font Color", "Font Name", "Text To Print");

                    imagefttext($image1, $fSizeInitial, 0, $x, $y, $white, $font, $finalText[$i]);
                }

                //COVER IMAGE

                $image2 = imagecreatefrompng(public_path() . "/assets/img/blitz/{$edition}/cartaz_1/FB_Cover.png");
                $image_width = imagesx($image2);

                imagealphablending($image2, true);

                $white = imagecolorallocate($image2, 0, 0, 0);

                // makeTextBlock($text, $fontfile, $fontsize, $width)
                $finalText = $this->makeTextBlock($bandName, $font, 25, 330);

                for ($i = 0; $i < count($finalText); $i++) {

                    // imagettfbbox ( float $size , float $angle , string $fontfile , string $text )
                    $bbox = imagettfbbox(25, 0, $font, $finalText[$i]);

                    // the first y determines the position of the text in the image
                    // the next determines line spacing

                    if ($i == 0) {
                        $dist = 160;
                        $y = $dist;
                    } else {
                        $y = $y + 45;
                    }


                    // imagefttext("Image", "Font Size", "Rotate Text", "Left Position",
                    // "Top Position", "Font Color", "Font Name", "Text To Print");

                    imagefttext($image2, 25, 0, 100, $y, $white, $font, $finalText[$i]);
                }

                // POST IMAGE

                $image3 = imagecreatefrompng(public_path() . "/assets/img/blitz/{$edition}/cartaz_1/FB_Post.png");
                $image_width = imagesx($image3);

                imagealphablending($image3, true);

                $white = imagecolorallocate($image3, 0, 0, 0);

                $finalText = $this->makeTextBlock($bandName, $font, 50, ($image_width * 2) / 3);

                for ($i = 0; $i < count($finalText); $i++) {
                    $bbox = imagettfbbox(50, 0, $font, $finalText[$i]);
                    $x = ceil(($image_width - $bbox[2]) / 2);

                    if ($i == 0) {
                        $dist = 1650;
                        $y = $dist;
                    } else {
                        $y = $y + 75;
                    }

                    imagefttext($image3, 50, 0, $x, $y, $white, $font, $finalText[$i]);
                }

                break;

            case 'Template_2':

                $fSizeInitial = 60;

                $bandName = mb_strtoupper($bandName, 'UTF-8');
                $font = public_path() . "/assets/fonts/edp_preon_medium-webfont.ttf";

                //A4 PRINT

                $image1 = imagecreatefrompng(public_path() . "/assets/img/blitz/{$edition}/cartaz_2/02CartazA4.png");
                $image_width = imagesx($image1);

                imagealphablending($image1, true);

                $white = imagecolorallocate($image1, 255, 255, 255);

                //makeTextBlock($text, $fontfile, $fontsize, $width)
                $finalText = $this->makeTextBlock($bandName, $font, $fSizeInitial, ($image_width * 2) / 2);
                //imagettfbbox ( float $size , float $angle , string $fontfile , string $text )
                for ($i = 0; $i < count($finalText); $i++) {
                    $bbox = imagettfbbox($fSizeInitial, 0, $font, $finalText[$i]);
                    $x = ceil(($image_width - $bbox[2]) / 2);

                    //the first y determines the position of the text in the image
                    //the next determines line spacing

                    if ($i == 0) {
                        $dist = 2750;
                        $y = $dist;
                    } else {
                        $y = $y + 90;
                    }


                    // imagefttext("Image", "Font Size", "Rotate Text", "Left Position",
                    //"Top Position", "Font Color", "Font Name", "Text To Print");

                    imagefttext($image1, $fSizeInitial, 0, $x, $y, $white, $font, $finalText[$i]);
                }

                //COVER IMAGE

                $image2 = imagecreatefrompng(public_path() . "/assets/img/blitz/{$edition}/cartaz_2/Cartaz02CoverImage.png");
                $image_width = imagesx($image2);

                imagealphablending($image2, true);

                $white = imagecolorallocate($image2, 255, 255, 255);

                //makeTextBlock($text, $fontfile, $fontsize, $width)
                $finalText = $this->makeTextBlock($bandName, $font, 25, 345);
                //imagettfbbox ( float $size , float $angle , string $fontfile , string $text )
                for ($i = 0; $i < count($finalText); $i++) {
                    $bbox = imagettfbbox(25, 0, $font, $finalText[$i]);
                    $x = ceil(($image_width - $bbox[2]) / 2);

                    //the first y determines the position of the text in the image
                    //the next determines line spacing

                    if ($i == 0) {
                        $dist = 160;
                        $y = $dist;
                    } else {
                        $y = $y + 45;
                    }


                    // imagefttext("Image", "Font Size", "Rotate Text", "Left Position",
                    //"Top Position", "Font Color", "Font Name", "Text To Print");

                    imagefttext($image2, 25, 0, 100, $y, $white, $font, $finalText[$i]);
                }

                //POST IMAGE

                $image3 = imagecreatefrompng(public_path() . "/assets/img/blitz/{$edition}/cartaz_2/Cartaz02PostImage.png");
                $image_width = imagesx($image3);

                imagealphablending($image3, true);

                $white = imagecolorallocate($image3, 255, 255, 255);

                //makeTextBlock($text, $fontfile, $fontsize, $width)
                $finalText = $this->makeTextBlock($bandName, $font, 50, ($image_width * 2) / 3);
                //imagettfbbox ( float $size , float $angle , string $fontfile , string $text )
                for ($i = 0; $i < count($finalText); $i++) {
                    $bbox = imagettfbbox(50, 0, $font, $finalText[$i]);
                    $x = ceil(($image_width - $bbox[2]) / 2);

                    //the first y determines the position of the text in the image
                    //the next determines line spacing

                    if ($i == 0) {
                        $dist = 1650;
                        $y = $dist;
                    } else {
                        $y = $y + 75;
                    }



                    // imagefttext("Image", "Font Size", "Rotate Text", "Left Position",
                    //"Top Position", "Font Color", "Font Name", "Text To Print");

                    imagefttext($image3, 50, 0, $x, $y, $white, $font, $finalText[$i]);
                }

                break;
        }




        ImagePng($image1, public_path() . '/uploads/blitzes/' . $edition . '_' . $bandId . '_' . $template . '_1.png');
        ImagePng($image2, public_path() . '/uploads/blitzes/' . $edition . '_' . $bandId . '_' . $template . '_cover_facebook.png');
        ImagePng($image3, public_path() . '/uploads/blitzes/' . $edition . '_' . $bandId . '_' . $template . '_post_facebook.png');

        $imagesToInsert = [
            public_path() . '/uploads/blitzes/' . $edition . '_' . $bandId . '_' . $template . '_1.png',
            public_path() . '/uploads/blitzes/' . $edition . '_' . $bandId . '_' . $template . '_cover_facebook.png',
            public_path() . '/uploads/blitzes/' . $edition . '_' . $bandId . '_' . $template . '_post_facebook.png'
        ];

        $imageNamesToInsert = [
            $edition . '_' . $bandId . '_' . $template . '_1.png',
            $edition . '_' . $bandId . '_' . $template . '_cover_facebook.png',
            $edition . '_' . $bandId . '_' . $template . '_post_facebook.png'
        ];


        //Convert Image 1 to PDF before Zipping

        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        // set auto page breaks
        $pdf->SetAutoPageBreak(FALSE);

        $pdf->SetMargins(0, 0, 0);
        $pdf->SetHeaderMargin(0);
        $pdf->SetFooterMargin(0);

        // add a page


        $pdfName = $edition . '_' . $bandId . '_' . $template . '_cartaz.pdf';
        $pdfPath = public_path() . '/uploads/blitzes/' . $pdfName;

        $pdf->AddPage('P', 'A4');




        //$pdf->Image(public_path().'/uploads/blitzes/'.$bandId.'_'.$template.'_1.png', '', '', 600, 850, 'PNG','', '', true, 200, '', false, false, 0, false, false, false);
        $pdf->Image($imagesToInsert[0], '', '', 0, 0, 'PNG', '', '', true, 200, '', false, false, 0, false, false, true);
        //Close and output PDF document
        $pdf->Output($pdfPath, 'F');
        //Once generation is over we need to Zip contents of the folder created
        //create an instance of ZipArchive class

        $zip = new ZipArchive();

        //create the archive called images.zip and open it

        if (file_exists($zipFilePAth)) {
            @unlink($zipFilePAth);
        }


        $result = $zip->open($zipFilePAth, ZIPARCHIVE::CREATE);

        if ($result) {

            foreach ($imagesToInsert as $idx => $imageToInsert) {
                $zip->addFile($imageToInsert, '/'.$imageNamesToInsert[$idx]);
            }
            $zip->addFile($pdfPath, '/'.$pdfName);


            $zip->close();

            $fields['zip-path'] = $zipFilePAth;
        }

        //remove generated Images from memory
        imagedestroy($image1);
        imagedestroy($image2);
        imagedestroy($image3);

        //Since the images are already zipped, remove them from the file system too.
        foreach ($imagesToInsert as $imageToInsert) {
            @unlink($imageToInsert);
        }
        @unlink($pdfName);



        header('Pragma: public');
        header('Cache-Control: public, no-cache');
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . filesize($fields['zip-path']));
        header('Content-Disposition: attachment; filename="' .
                basename($zipFolderId . '.zip') . '"');
        header('Content-Transfer-Encoding: binary');
        readfile($fields['zip-path']);
    }

}
