<?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/. */

/**
 * Make things happen when buttons are pressed and forms submitted.
 */
require_once __DIR__ . "/required.php";

if ($VARS['action'] !== "signout") {
    dieifnotloggedin();
}

/**
 * Redirects back to the page ID in $_POST/$_GET['source'] with the given message ID.
 * The message will be displayed by the app.
 * @param string $msg message ID (see lang/messages.php)
 * @param string $arg If set, replaces "{arg}" in the message string when displayed to the user.
 */
function returnToSender($msg, $arg = "") {
    global $VARS;
    if ($arg == "") {
        header("Location: app.php?page=" . urlencode($VARS['source']) . "&msg=" . $msg);
    } else {
        header("Location: app.php?page=" . urlencode($VARS['source']) . "&msg=$msg&arg=$arg");
    }
    die();
}

switch ($VARS['action']) {
    case "signout":
        session_destroy();
        header('Location: index.php');
        die("Logged out.");
    case "editfamily":
        if (!(new User($_SESSION['uid']))->hasPermission("HACHEPORTAL_EDIT")) {
            returnToSender("no_permission");
        }

        $family = new Family();
        $editing = false;

        if (!empty($VARS['familyid']) && $database->has("families", ['familyid' => $VARS['familyid']])) {
            $family = (new Family())->load($VARS['familyid']);
            $editing = true;
        }

        function errorBack(string $errormsg) {
            global $family, $editing;
            if ($editing) {
                returnToSender($errormsg, "&id=" . $family->getID());
            }
            returnToSender($errormsg);
        }

        $database->action(function($database) {
            global $family, $VARS, $editing;

            try {
                $lastname = $VARS['familyname'];
                $father = $VARS['fathername'];
                $mother = $VARS['mothername'];

                if (empty($lastname)) {
                    errorBack("Enter a last name.");
                }
                if (empty($father)) {
                    errorBack("Enter a father name.");
                }
                if (empty($mother)) {
                    errorBack("Enter a mother name.");
                }

                $family->setName($lastname);
                $family->setFather($father);
                $family->setMother($mother);

                $family->setPhone($VARS['phone']);
                $family->setEmail($VARS['email']);

                if ($editing) {
                    if ($database->has("families", ["AND" => ["email" => $family->getEmail(), "familyid[!]" => $family->getID()]])) {
                        errorBack("That email address is already in use with another family.");
                    }
                } else {
                    if ($database->has("families", ["email" => $family->getEmail()])) {
                        errorBack("That email address is already in use with another family.");
                    }
                }

                $address = $VARS['streetaddress'];
                $city = $VARS['city'];
                $state = strtoupper($VARS['state']);
                $zip = $VARS['zip'];
                if (empty($address)) {
                    errorBack("Enter a street address.");
                }
                if (empty($city)) {
                    errorBack("Enter a city.");
                }
                $family->setAddress($address);
                $family->setCity($city);
                $family->setState($state);
                $family->setZip($zip);


                $newsletter = $VARS['newsletter_method'];
                $membership_cost = 2500;
                if (empty($newsletter)) {
                    errorBack("Select a newsletter preference.");
                }
                $family->setNewsletter($newsletter);
                switch ($newsletter) {
                    case 1: // Email only
                        $membership_cost = 2500;
                        break;
                    case 2: // Print only
                        $membership_cost = 3500;
                        break;
                    case 3: // Email and print
                        $membership_cost = 3500;
                        break;
                    default:
                        errorBack("Select a valid newsletter preference.");
                }

                $photopermission = $VARS['photo_permission'];
                if (!empty($photopermission) && $photopermission == "1") {
                    $photopermission = true;
                } else {
                    $photopermission = false;
                }
                $family->setPhotoPermission($photopermission);

                $family->save();

                //
                // Children
                //
                $children = $VARS['child'];

                $childObjects = $family->getChildren();

                $childrenToDelete = [];

                foreach ($children['ids'] as $cid) {
                    if (empty($children['name'][$cid])) {
                        $childrenToDelete[] = $cid;
                        continue;
                    }

                    if (!preg_match("/^([1-9]|1[012])$/", $children['month'][$cid])) {
                        errorBack("Invalid birth month chosen for " . htmlentities($children['name'][$cid]) . ".");
                    }

                    if (!is_numeric($children['year'][$cid])) {
                        errorBack("Invalid birth year chosen for " . htmlentities($children['name'][$cid]) . ".");
                    }
                    $children['year'][$cid] = $children['year'][$cid] * 1;
                    if ($children['year'][$cid] < 1980 || $children['year'][$cid] > date("Y")) {
                        errorBack("Invalid birth year chosen for " . htmlentities($children['name'][$cid]) . ".");
                    }

                    if (Child::exists($cid, $family->getID())) {
                        // iterate over existing children to find the correct one
                        for ($i = 0; $i < count($childObjects); $i++) {
                            if ($childObjects[$i]->getID() == $cid) {
                                $childObjects[$i]->setName($children['name'][$cid]);
                                $childObjects[$i]->setBirthday(null, $children['year'][$cid] . "-" . $children['month'][$cid] . "-00");
                                $childObjects[$i]->setGraduated(empty($children['graduate'][$cid]) ? false : true);
                            }
                        }
                    } else {
                        $child = new Child();
                        $child->setName($children['name'][$cid]);
                        $child->setBirthday(null, $children['year'][$cid] . "-" . $children['month'][$cid] . "-00");
                        $child->setGraduated(empty($children['graduate'][$cid]) ? false : true);
                        $child->setFamilyID($family->getID());
                        $childObjects[] = $child;
                    }
                }

                foreach ($childObjects as $child) {
                    $child->save();
                }

                foreach ($childrenToDelete as $rip) {
                    $database->delete("people", ['personid' => $rip]);
                }
            } catch (Exception $ex) {
                errorBack($ex->getMessage());
            }
        });

        returnToSender("family_saved", "&id=" . $family->getID());
        break;
    case "deletefamily":
        if (!(new User($_SESSION['uid']))->hasPermission("HACHEPORTAL_EDIT")) {
            returnToSender("no_permission");
        }

        if (!empty($VARS['familyid']) && $database->count("families", ['familyid' => $VARS['familyid']]) === 1) {
            $database->delete("people", ["familyid" => $VARS['familyid']]);
            $database->delete("interests", ["familyid" => $VARS['familyid']]);
            $database->delete("payments", ["familyid" => $VARS['familyid']]);
            $database->delete("families", ["familyid" => $VARS['familyid']]);
            returnToSender("family_deleted");
        } else {
            returnToSender("family_doesnt_exist");
        }
        break;
    case "editevents":
        if (!(new User($_SESSION['uid']))->hasPermission("HACHEPORTAL_EDIT")) {
            returnToSender("no_permission");
        }

        foreach ($_POST['events'] as $k => $v) {
            if ($database->has("events", ["eventid" => $k])) {
                if (empty($v)) {
                    $database->delete("interests", ["eventid" => $k]);
                    $database->delete("events", ["eventid" => $k]);
                    continue;
                }
                $database->update("events", ["event" => $v], ["eventid" => $k]);
            } else {
                if (empty($v)) {
                    continue;
                }
                $database->insert("events", ["event" => $v]);
            }
        }
        returnToSender("events_updated");
}