<?php

/**
 * namesearch.php is used to show the names of persons born or died in a certain place from the map page.
 * 
 * TODO: maybe remove the born and died items, and search for all events.
 */

session_start();

// *** Autoload composer classes ***
require __DIR__ . '/../vendor/autoload.php';

include_once(__DIR__ . "/../include/db_login.php"); //Inloggen database.

$generalSettings = new Genealogy\Include\GeneralSettings();
$humo_option = $generalSettings->get_humo_option($dbh);

$userSettings = new Genealogy\Include\UserSettings();
$user = $userSettings->get_user_settings($dbh);

$processLinks = new Genealogy\Include\ProcessLinks();

$tree_id = $_SESSION['tree_id'];

$db_functions = new Genealogy\Include\DbFunctions($dbh);
$db_functions->set_tree_id($tree_id);

// *** Language processing after header("..") lines. ***
$language_cls = new Genealogy\Languages\LanguageCls;
$language_file = $language_cls->get_languages();
$selected_language = $language_cls->get_selected_language($humo_option);
$language = $language_cls->get_language_data($selected_language);
// *** .mo language text files ***
include_once(__DIR__ . "/../languages/gettext.php");
// *** Load ***
Load_default_textdomain();

// Start of the namesearch part
if (isset($_GET['max'])) {
    $map_max = $_GET['max'];
} else {
    // Logically we can never get here because this file is always called with this parameter
    $map_max = date('Y'); //this year
}

if (isset($_GET['thisplace'])) {
    $thisplace = urldecode($_GET['thisplace']);     // should be done automatically but it doesn't hurt
    $thisplace = str_replace("\'", "'", $thisplace);  // in some settings the \ is passed on with the ' while in others not
    $thisplace = str_replace("'", "''", $thisplace);     // for MySQL single quote has to be written as 2 single quotes: '' in the mysql query
} else {
    // Logically we can never get here because this file is always called with this parameter
    $thisplace = "NONFOUND";
}

function mapbirthplace($place)
{
    global $dbh, $tree_id, $language, $map_max, $processLinks;

    $personName = new Genealogy\Include\PersonName();
    $personPrivacy = new Genealogy\Include\PersonPrivacy();
    $datePlace = new Genealogy\Include\DatePlace();
    $db_functions = new Genealogy\Include\DbFunctions($dbh);
    $db_functions->set_tree_id($tree_id);

    if (isset($_GET['namestring'])) {
        $temparray = explode("@", $_GET['namestring']);
        $namestring = " (";
        foreach ($temparray as $value) {
            //echo $value.'<br>';
            //$namestring .=  "pers_lastname = '".$value."' OR ";
            $namestring .= "CONCAT(pers_lastname,'_',LOWER(SUBSTRING_INDEX(pers_prefix,'_',1))) = '" . $value . "' OR ";
        }
        $namestring = substr($namestring, 0, -3) . ") AND "; //echo $namestring;
    } else {
        $namestring = '';
    }

    $desc_arr = '';
    $idstring = '';
    if (isset($_SESSION['desc_array'])) {
        $desc_arr = $_SESSION['desc_array'];
        $idstring = ' (';
        foreach ($desc_arr as $value) {
            $idstring .= " pers_gedcomnumber = '" . $value . "' OR ";
        }
        $idstring = substr($idstring, 0, -3) . ') AND ';
    }

    $anc_arr = '';
    $anc_idstring = '';
    if (isset($_SESSION['anc_array'])) {
        $anc_arr = $_SESSION['anc_array'];
        $anc_idstring = ' (';
        foreach ($anc_arr as $value) {
            $anc_idstring .= " pers_gedcomnumber = '" . $value . "' OR ";
        }
        $anc_idstring = substr($anc_idstring, 0, -3) . ') AND ';
    }

    if ($anc_idstring != '') {
        $idstring = $anc_idstring;
    }

    $min = 1;
    if ($place != "NONFOUND") {
        if ($_SESSION['type_birth'] == 1) {
            if (isset($_GET['all'])) {
                // the 'All birth locations' button
?>
                <b><u><?= __('All persons born here: '); ?></u></b><br>

            <?php
                $sql = "SELECT p.*, CONCAT(p.pers_lastname, p.pers_firstname) AS wholename
                    FROM humo_persons p
                    INNER JOIN humo_events e ON e.person_id = p.pers_id
                    INNER JOIN humo_location l ON e.place_id = l.location_id
                    WHERE p.pers_tree_id = '" . $tree_id . "'
                    AND " . $idstring . $namestring . "
                    (e.event_kind = 'birth' AND l.location_location = '" . $place . "')
                    ORDER BY wholename";
                $maplist = $dbh->query($sql);
            } else {
                // *** Slider is used ***
            ?>
                <b><u><?= __('Persons born here until ') . $map_max; ?>:</u></b><br>
        <?php
                // TODO use date_year
                $sql = "SELECT p.*, CONCAT(p.pers_lastname, p.pers_firstname) AS wholename, e.date_year AS pers_birth_date
                    FROM humo_persons p
                    INNER JOIN humo_events e ON e.event_gedcomnumber = p.pers_gedcomnumber
                    INNER JOIN humo_location l ON e.place_id = l.location_id
                    WHERE p.pers_tree_id = '" . $tree_id . "'
                    AND " . $idstring . $namestring . "
                    (e.event_kind = 'birth' AND l.location_location = '" . $place . "')
                    AND (e.date_year < " . $map_max . " AND e.date_year > " . $min . ")
                    ORDER BY wholename";

                $maplist = $dbh->query($sql);
            }
        } elseif ($_SESSION['type_death'] == 1) {
            if (isset($_GET['all'])) {
                // the 'All birth locations' button
                echo '<b><u>' . __('All persons that died here: ') . '</u></b><br>';

                $sql = "SELECT p.*, CONCAT(p.pers_lastname, p.pers_firstname) AS wholename
                    FROM humo_persons p
                    INNER JOIN humo_events e ON e.event_gedcomnumber = p.pers_gedcomnumber
                    INNER JOIN humo_location l ON e.place_id = l.location_id
                    WHERE p.pers_tree_id = '" . $tree_id . "'
                    AND " . $idstring . $namestring . "
                    (e.event_kind = 'death' AND l.location_location = '" . $place . "')
                    ORDER BY wholename";
                $maplist = $dbh->query($sql);
            } else {
                // *** Slider is used ***
                echo '<b><u>' . __('Persons that died here until ') . $map_max . ':</u></b><br>';

                $sql = "SELECT p.*, CONCAT(p.pers_lastname, p.pers_firstname) AS wholename, e.date_year AS pers_death_date
                    FROM humo_persons p
                    INNER JOIN humo_events e ON e.event_gedcomnumber = p.pers_gedcomnumber
                    INNER JOIN humo_location l ON e.place_id = l.location_id
                    WHERE p.pers_tree_id = '" . $tree_id . "' AND " . $idstring . $namestring . "
                    (e.event_kind = 'death' AND l.location_location = '" . $place . "')
                    AND (e.date_year < " . $map_max . " AND e.date_year > " . $min . ")
                    ORDER BY wholename";
                $maplist = $dbh->query($sql);
            }
        }
        //echo 'TEST: '.$sql;
        ?>

        <div style="direction:ltr">
            <?php
            while ($maplist2Db = $maplist->fetch(PDO::FETCH_OBJ)) {
                $maplistDb = $db_functions->get_person_with_id($maplist2Db->pers_id);
                $privacy_man = $personPrivacy->get_privacy($maplistDb);
                $name = $personName->get_person_name($maplistDb, $privacy_man);
                if ($name["show_name"] == true) {
                    $pers_family = '';
                    if ($maplistDb->parent_relation_gedcomnumber) {
                        $pers_family = $maplistDb->parent_relation_gedcomnumber;
                    }
                    $relations = $db_functions->get_first_relation($maplistDb->pers_id);
                    $pers_family = $relations->gedcomnumber;

                    $vars['pers_family'] = $pers_family;
                    $link = $processLinks->get_link('', 'family', $maplistDb->pers_tree_id, true, $vars);
                    $link .= "main_person=" . $maplistDb->pers_gedcomnumber;
                    echo '<a href=' . $link . ' target="blank">';
                }
                if ($_SESSION['type_birth'] == 1) {
                    echo $name["index_name"];
                    $date = $maplistDb->pers_birth_date;
                    $sign = __('born') . ' ';
                    if (!$maplistDb->pers_birth_date and $maplistDb->pers_bapt_date) {
                        $date = $maplistDb->pers_bapt_date;
                        $sign = __('baptised') . ' ';
                    }
                }
                if ($_SESSION['type_death'] == 1) {
                    echo $name["index_name"];
                    $date = $maplistDb->pers_death_date;
                    $sign = __('died') . ' ';
                    if (!$maplistDb->pers_death_date and $maplistDb->pers_buried_date) {
                        $date = $maplistDb->pers_buried_date;
                        $sign = __('buried') . ' ';
                    }
                }
                if (!$privacy_man and $date and $name["show_name"] == true) {
                    echo ' (' . $sign . $datePlace->date_place($date, '') . ')';
                }
                if ($name["show_name"] == true) {
                    echo '</a>';
                }
            ?>
                <br>
            <?php } ?>
        </div>
<?php
    } else {
        // Logically we can never get here
        echo 'No persons found';
    }
}

mapbirthplace($thisplace);
