<?php

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

require_once __DIR__ . "/../required.php";

dieifnotloggedin();
$user = new User($_SESSION['uid']);
if (!$user->hasPermission("HACHEPORTAL_VIEW")) {
    header("Location: ../app.php?msg=no_permission");
    die();
}

use Dompdf\Dompdf;

// Load all families
$familylist = $database->select("families", "familyid", ["ORDER" => ["familyname"]]);
$families = [];
foreach ($familylist as $f) {
    $families[] = (new Family())->load($f);
}

$format = "html";
if (!empty($_GET["format"])) {
    $format = $_GET["format"];
}

$date = date("F j Y");

if ($format == "html") {

    $icons = ".grad {
        background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPHN2ZyB3aWR0aD0iMjMwNCIgaGVpZ2h0PSIxNzkyIiB2aWV3Qm94PSIwIDAgMjMwNCAxNzkyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxwYXRoIGQ9Ik0xNzc0IDgzNmwxOCAzMTZxNCA2OS04MiAxMjh0LTIzNSA5My41LTMyMyAzNC41LTMyMy0zNC41LTIzNS05My41LTgyLTEyOGwxOC0zMTYgNTc0IDE4MXEyMiA3IDQ4IDd0NDgtN3ptNTMwLTMyNHEwIDIzLTIyIDMxbC0xMTIwIDM1MnEtNCAxLTEwIDF0LTEwLTFsLTY1Mi0yMDZxLTQzIDM0LTcxIDExMS41dC0zNCAxNzguNXE2MyAzNiA2MyAxMDkgMCA2OS01OCAxMDdsNTggNDMzcTIgMTQtOCAyNS05IDExLTI0IDExaC0xOTJxLTE1IDAtMjQtMTEtMTAtMTEtOC0yNWw1OC00MzNxLTU4LTM4LTU4LTEwNyAwLTczIDY1LTExMSAxMS0yMDcgOTgtMzMwbC0zMzMtMTA0cS0yMi04LTIyLTMxdDIyLTMxbDExMjAtMzUycTQtMSAxMC0xdDEwIDFsMTEyMCAzNTJxMjIgOCAyMiAzMXoiLz48L3N2Zz4=');
    }
    .phone {
        background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPHN2ZyB3aWR0aD0iMTc5MiIgaGVpZ2h0PSIxNzkyIiB2aWV3Qm94PSIwIDAgMTc5MiAxNzkyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxwYXRoIGQ9Ik0xNjAwIDEyNDBxMCAyNy0xMCA3MC41dC0yMSA2OC41cS0yMSA1MC0xMjIgMTA2LTk0IDUxLTE4NiA1MS0yNyAwLTUzLTMuNXQtNTcuNS0xMi41LTQ3LTE0LjUtNTUuNS0yMC41LTQ5LTE4cS05OC0zNS0xNzUtODMtMTI3LTc5LTI2NC0yMTZ0LTIxNi0yNjRxLTQ4LTc3LTgzLTE3NS0zLTktMTgtNDl0LTIwLjUtNTUuNS0xNC41LTQ3LTEyLjUtNTcuNS0zLjUtNTNxMC05MiA1MS0xODYgNTYtMTAxIDEwNi0xMjIgMjUtMTEgNjguNS0yMXQ3MC41LTEwcTE0IDAgMjEgMyAxOCA2IDUzIDc2IDExIDE5IDMwIDU0dDM1IDYzLjUgMzEgNTMuNXEzIDQgMTcuNSAyNXQyMS41IDM1LjUgNyAyOC41cTAgMjAtMjguNSA1MHQtNjIgNTUtNjIgNTMtMjguNSA0NnEwIDkgNSAyMi41dDguNSAyMC41IDE0IDI0IDExLjUgMTlxNzYgMTM3IDE3NCAyMzV0MjM1IDE3NHEyIDEgMTkgMTEuNXQyNCAxNCAyMC41IDguNSAyMi41IDVxMTggMCA0Ni0yOC41dDUzLTYyIDU1LTYyIDUwLTI4LjVxMTQgMCAyOC41IDd0MzUuNSAyMS41IDI1IDE3LjVxMjUgMTUgNTMuNSAzMXQ2My41IDM1IDU0IDMwcTcwIDM1IDc2IDUzIDMgNyAzIDIxeiIvPjwvc3ZnPg==');
    }
    .email {
        background-image: url('data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aD0iMTc5MiIgaGVpZ2h0PSIxNzkyIiB2aWV3Qm94PSIwIDAgMTc5MiAxNzkyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxwYXRoIGQ9Ik0xMTUyIDY0MHEwLTEwNi03NS0xODF0LTE4MS03NS0xODEgNzUtNzUgMTgxIDc1IDE4MSAxODEgNzUgMTgxLTc1IDc1LTE4MXptMjU2IDBxMCAxMDktMzMgMTc5bC0zNjQgNzc0cS0xNiAzMy00Ny41IDUydC02Ny41IDE5LTY3LjUtMTktNDYuNS01MmwtMzY1LTc3NHEtMzMtNzAtMzMtMTc5IDAtMjEyIDE1MC0zNjJ0MzYyLTE1MCAzNjIgMTUwIDE1MCAzNjJ6Ii8+PC9zdmc+');
    }
    .nocamera {
        background-image: url('data:image/svg+xml;base64,[encoded data, 6548 characters]');
    }";


    $htmltop = <<<END
<!DOCTYPE html>
<title>HACHE Member Directory</title>
<style>
    html, body {
        font-family: Roboto, DejaVu Sans, Arial, sans-serif;
    }
    #memberlist {
        column-count: 2;
    }
    .family {
        margin-bottom: 15px;
    }
    .child {
        margin-left: 10px;
    }
    .letterheading {
        margin-top: 15px;
        border-top: 1px solid black;
        border-bottom: 1px solid black;
        text-align: center;
    }
    .icon {
        width: 16px;
        height: 16px;
        display: inline-block;
        margin-bottom: -3px;
        background-size: 16px 16px;
        -webkit-print-color-adjust: exact !important;
        color-adjust: exact !important;
    }
    $icons
</style>
<h1>HACHE Member Directory</h1>
<p>
    <b>Updated:</b> $date
    <br />
    <b>Icon key:</b>
    <span class="icon grad"></span>: Graduated student | <span class="icon nocamera"></span>: Photo permission denied
    <br />
    You agree to use the information in this directory for homeschool use ONLY.  All other purposes, such as soliciting, is strictly prohibited.
</p>

<div id="memberlist">
END;

    $htmlmiddle = "";

    $currentletter = " ";

    foreach ($families as $f) {
        // Add headings for letters
        if (strtoupper($f->getName()[0]) > $currentletter) {
            $currentletter = strtoupper($f->getName()[0]);
            $htmlmiddle .= "\n<h3 class=\"letterheading\">$currentletter</h3>\n";
        }
        $famhtml = "\n<div class=\"family\">\n"
                . "\t<b>" . $f->getName() . "</b>, " . $f->getFather() . " and " . $f->getMother() . "\n";
        if (!$f->getPhotoPermission()) {
            $famhtml .= "\t<span class=\"icon nocamera\"></span>\n";
        }
        $famhtml .= "\t<br /><span class=\"icon mapmarker\"></span> " . $f->getAddress() . ", " . $f->getCity() . ", " . $f->getState() . " " . $f->getZip() . "\n"
                . "\t<br /><span class=\"icon phone\"></span> <a href=\"tel:" . $f->getPhone() . "\">" . $f->getPhone() . "</a> &nbsp;&nbsp; <span class=\"icon email\"></span> <a href=\"mailto:" . $f->getEmail() . "\">" . $f->getEmail() . "</a>\n";
        foreach ($f->getChildren() as $child) {
            $famhtml .= "\t<div class=\"child\">\n";
            if ($child->isGraduated()) {
                $famhtml .= "\t\t<span class=\"icon grad\"></span>\n";
            } else {
                $famhtml .= "\t\t<span class=\"icon\"></span>\n";
            }
            $famhtml .= "\t\t" . $child->getName() . ", " . date("M y", $child->getBirthday()) . "\n";
            $famhtml .= "\t</div>\n";
        }
        $famhtml .= "</div>\n";
        $htmlmiddle .= $famhtml;
    }

    $htmlbottom = <<<END
</div>
END;

    $html = $htmltop . $htmlmiddle . $htmlbottom;

    header("Content-Type: text/html; charset=UTF-8");
    header("Content-disposition: attachment; filename=\"HACHE_Directory_" . date("Y-m-d") . ".html\"");
    echo $html;
} else {
    \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);
    $phpWord = new \PhpOffice\PhpWord\PhpWord();

    $properties = $phpWord->getDocInfo();
    $properties->setCreator('HACHE Membership Portal');
    $properties->setCompany('HACHE');
    $properties->setTitle('HACHE Member Directory');

    $phpWord->addTitleStyle(1, ['bold' => true, 'size' => 24, 'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER]);
    $phpWord->addTitleStyle(2, ['bold' => true, 'size' => 16]);

    $header = $phpWord->addSection(["paperSize" => "Letter", 'marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 600, 'marginBottom' => 600]);
    $header->addTitle("HACHE Member Directory\n", 1);
    $updated = $header->addTextRun();
    $updated->addText("Updated: ", ['bold' => true]);
    $updated->addText("$date");
    $iconkey = $header->addTextRun();
    $iconkey->addText("Icon key: ", ['bold' => true]);
    $iconkey->addText("◊: Graduated student  |  ►: Photo permission denied");
    $header->addText($Strings->get("You agree to use the information in this directory for homeschool use ONLY. All other purposes, such as soliciting, is strictly prohibited.", false));

    $header->addTextBreak(2);

    $body = $phpWord->addSection(['breakType' => 'continuous', 'colsNum' => 2, "paperSize" => "Letter", 'marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 600, 'marginBottom' => 600]);

    $currentletter = " ";

    foreach ($families as $f) {
        // Add headings for letters
        if (strtoupper($f->getName()[0]) > $currentletter) {
            $currentletter = strtoupper($f->getName()[0]);
            $body->addTitle("$currentletter", 2);
        }
        $famtext = $body->addTextRun();
        if (!$f->getPhotoPermission()) {
            $famtext->addText("►");
        }
        $famtext->addText($f->getName(), ['bold' => true]);
        $famtext->addText(", " . $f->getFather() . " and " . $f->getMother());
        $body->addText($f->getAddress() . ", " . $f->getCity() . ", " . $f->getState() . " " . $f->getZip());
        $links = $body->addTextRun();
        $links->addLink("tel:" . $f->getPhone(), $f->getPhone());
        $links->addText("    ");
        $links->addLink("mailto:" . $f->getEmail(), $f->getEmail());

        foreach ($f->getChildren() as $child) {
            $chtext = $body->addTextRun(["indent" => 1440]);
            if ($child->isGraduated()) {
                $chtext->addText(" ●");
            } else {
                $chtext->addText(" ");
            }
            $chtext->addText($child->getName() . ", " . date("M y", $child->getBirthday()));
        }
        $body->addTextBreak(1);
    }

    header("Content-Description: File Transfer");
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Expires: 0');

    switch ($format) {
        case "docx":
            $phpWord->getCompatibility()->setOoxmlVersion(15);
            $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
            header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            header("Content-disposition: attachment; filename=\"HACHE_Directory_" . date("Y-m-d") . ".docx\"");
            break;
        case "odt":
        default:
            // Paper size is stuck at A4 and margins don't work.
            // See https://github.com/PHPOffice/PHPWord/issues/1531
            // Hopefully they'll get this fixed.
            $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText');
            header("Content-Type: application/vnd.oasis.opendocument.text");
            header("Content-disposition: attachment; filename=\"HACHE_Directory_" . date("Y-m-d") . ".odt\"");
            break;
    }
    $objWriter->save('php://output');
}
?>