<?php

/*
 * Copyright (C) 2021 Echedey López Romero <elr@disroot.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// Show errors in screen
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// Repair output with Tidy
// ini_set('tidy.clean_output', '1');
// Empty web browser cache
header('Cache-Control: no-cache');
header('Pragma: no-cache');

// Load functions
require './functions.php';

// Load variables
require './variables.php';

// Start session
session_start();

// Main functionality
if (isset($_SESSION['login']) && $_SESSION['login'] === '1') {
    $UserButton = ['danger', '.?login=0', 'fa-user-alt-slash', 'Logout'];
} else {
    $_SESSION['login'] = 0;
    $UserButton = ['primary', '.?login=1', 'fa-user-alt', 'Login'];
}

if (isset($_COOKIE['viewed']) && is_array(unserialize($_COOKIE['viewed'])) && count(unserialize($_COOKIE['viewed'])) > 0) {
    $Viewed = unserialize($_COOKIE['viewed']);
}

if (isset($_COOKIE['favourites']) && is_array(unserialize($_COOKIE['favourites'])) && count(unserialize($_COOKIE['favourites'])) > 0) {
    $Favourites = unserialize($_COOKIE['favourites']);
}

if (isset($_SESSION['cart']) && is_array(unserialize($_SESSION['cart'])) && count(unserialize($_SESSION['cart'])) > 0) {
    $Cart = unserialize($_SESSION['cart']);
}

$TopButtons = ShowTopButtons(false, $UserButton, $Cart, false);
$Costs = CalculateCosts($Products, $Cart);

if (isset($_POST['operation'])) {
    if ($_POST['operation'] === 'accept') {
        DefineCookie('policy', '1');
        header('Location:.');
    } else {
        DefineCookie('policy', '0');
        $Page = ShowWarning();
    }
} else if (!isset($_COOKIE['policy']) || $_COOKIE['policy'] === '0') {
    $Page = ShowPolicy();
} else {
    $TopButtons = ShowTopButtons(true, $UserButton, $Cart, false);

    if ((isset($_GET) && count($_GET) === 0) || !isset($_GET)) {
        $Page = ShowCatalogue($Products, $Viewed, $Favourites, false);
    } else if (isset($_GET) && count($_GET) > 1) {
        header('Location:.');
    } else {
        if (isset($_REQUEST['validatelogin'])) {
            $LoginCheck = [false, false];

            if (isset($_REQUEST['username']) && $_REQUEST['username'] !== '') {
                $Data = FilterValue($_REQUEST['username']);

                if ($Data === $UserName) {
                    $LoginCheck[0] = true;
                }
            } else {
                array_push($LoginErrors, 'You must introduce an username');
            }

            if (isset($_REQUEST['password']) && $_REQUEST['password'] !== '') {
                $Data = FilterValue($_REQUEST['password']);

                if ($Data === $UserPassword) {
                    $LoginCheck[1] = true;
                }
            } else {
                array_push($LoginErrors, 'You must introduce a password');
            }

            if ($LoginCheck[0] && $LoginCheck[1]) {
                $_SESSION['login'] = '1';
            } else {
                array_push($LoginErrors, 'Your username or password doesn\'t match');
            }
        }

        if (isset($_REQUEST['validatecheckout'])) {
            if (isset($_REQUEST['firstname']) && $_REQUEST['firstname'] !== '') {
                $Data = FilterValue($_REQUEST['firstname']);

                if (ValidateRegex('/^[a-zA-ZñÑáéíóúÁÉÍÓÚü\s]{2,50}$/', $Data)) {
                    $Replies['firstname'] = $Data;
                } else {
                    $Message = 'The first name must contain between 2 and 50 word characters';
                    array_push($CheckoutErrors, $Message);
                }
            } else {
                $Message = 'You must set a first name';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['lastname']) && $_REQUEST['lastname'] !== '') {
                $Data = FilterValue($_REQUEST['lastname']);

                if (ValidateRegex('/^[a-zA-ZñÑáéíóúÁÉÍÓÚü\s]{2,60}$/', $Data)) {
                    $Replies['lastname'] = $Data;
                } else {
                    $Message = 'The last name must contain between 2 and 60 word characters';
                    array_push($CheckoutErrors, $Message);
                }
            } else {
                $Message = 'You must set a last name';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['telephone']) && $_REQUEST['telephone'] !== '') {
                $Data = FilterValue($_REQUEST['telephone']);

                if (ValidateRegex('/^[0-9]{9}$/', $Data)) {
                    $Replies['telephone'] = $Data;
                } else {
                    $Message = 'The telephone must be a number of 9 digits';
                    array_push($CheckoutErrors, $Message);
                }
            } else {
                $Message = 'You must set a telephone number';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['information']) && $_REQUEST['information'] !== '') {
                $Data = FilterValue($_REQUEST['information']);

                if (ValidateRegex('/^[0-9a-zA-ZñÑáéíóúÁÉÍÓÚü,.*-_"\s]{0,2000}$/', $Data)) {
                    $Replies['information'] = $Data;
                } else {
                    $Message = 'The additional information must be a text of a maximum of '
                            . '2000 alphanumeric characters and the specials ones '
                            . '<strong>* - _ "</strong>';
                    array_push($CheckoutErrors, $Message);
                }
            }

            if (isset($_REQUEST['country']) && $_REQUEST['country'] !== '') {
                $Data = FilterValue($_REQUEST['country']);

                if (CheckListValue($Countries, $Data, 'id')) {
                    $Replies['country'] = $Data;
                } else {
                    $Message = 'The country must exist in the available list';
                    array_push($CheckoutErrors, $Message);
                }
            } else {
                $Message = 'You must set a country';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['province']) && $_REQUEST['province'] !== '') {
                $Data = FilterValue($_REQUEST['province']);

                if ($Replies['country'] === $Countries[0]['id']) {
                    if (CheckListValue($Provinces, $Data, 'provincia_id')) {
                        $Replies['province'] = $Data;
                    } else {
                        $Message = 'The province must be correspondent to the selected '
                                . 'country';
                        array_push($CheckoutErrors, $Message);
                    }
                }
            } else {
                $Message = 'You must set a province';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['municipality']) && $_REQUEST['municipality'] !== '') {
                $Data = FilterValue($_REQUEST['municipality']);
                $PossibleValues = GeneratePossibleValues($Municipalities, $Replies['province'], 'provincia_id');

                if (count($PossibleValues) !== 0) {
                    if (CheckListValue($PossibleValues, $Data, 'municipio_id')) {
                        $Replies['municipality'] = $Data;
                    } else {
                        $Message = 'The municipality must be correspondent to the selected '
                                . 'province';
                        array_push($CheckoutErrors, $Message);
                    }
                }
            } else {
                $Message = 'You must set a municipality';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['zipcode']) && $_REQUEST['zipcode'] !== '') {
                $Data = FilterValue($_REQUEST['zipcode']);
                $PossibleValues = GeneratePossibleValues($ZIPCodes, $Replies['municipality'], 'municipio_id');

                if ($Replies['municipality'] !== '' && count($PossibleValues) !== 0) {
                    if (CheckListValue($PossibleValues, $Data, 'cp_id')) {
                        $Replies['zipcode'] = $Data;
                    } else {
                        $Message = 'You must set a ZIP code correspondent to the selected '
                                . 'municipality';
                        array_push($CheckoutErrors, $Message);
                    }
                }
            } else {
                $Message = 'You must set a ZIP code';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['roadtype']) && $_REQUEST['roadtype'] !== '') {
                $Data = FilterValue($_REQUEST['roadtype']);

                if (CheckListValue($RoadTypes, $Data, 'id')) {
                    $Replies['roadtype'] = $Data;
                } else {
                    $Message = 'The road type must exist in the available list';
                    array_push($CheckoutErrors, $Message);
                }
            } else {
                $Message = 'You must set a road type';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['roadname']) && $_REQUEST['roadname'] !== '') {
                $Data = FilterValue($_REQUEST['roadname']);

                if (ValidateRegex('/^[a-zA-ZñÑáéíóúÁÉÍÓÚü\s]{2,80}$/', $Data)) {
                    $Replies['roadname'] = $Data;
                } else {
                    $Message = 'The road name must contain between 2 and 80 word characters';
                    array_push($CheckoutErrors, $Message);
                }
            } else {
                $Message = 'You must set a road name';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['number']) && $_REQUEST['number'] !== '') {
                $Data = FilterValue($_REQUEST['number']);

                if (ValidateRegex('/^[0-9]{1,3}$/', $Data)) {
                    $Replies['number'] = $Data;
                } else {
                    $Message = 'The home number must be a number of between 0 and 999';
                    array_push($CheckoutErrors, $Message);
                }
            } else {
                $Message = 'You must set a number of your home';
                array_push($CheckoutErrors, $Message);
            }

            if (isset($_REQUEST['complement']) && $_REQUEST['complement'] !== '') {
                $Data = FilterValue($_REQUEST['complement']);

                if (ValidateRegex('/^[a-zA-ZñÑáéíóúÁÉÍÓÚü\d\s]{2,50}$/', $Data)) {
                    $Replies['complement'] = $Data;
                } else {
                    $Message = 'The complement must contain between 2 and 50 alphanumeric characters';
                    array_push($CheckoutErrors, $Message);
                }
            }
        }

        if (isset($_REQUEST['view']) && $_REQUEST['view'] !== '') {
            AddProductCookie($Products, $_REQUEST['view'], $Viewed, 'viewed');

            $Page = ShowProduct($Products, $_REQUEST['view'], $Favourites);
        } else if (isset($_REQUEST['favourite']) && $_REQUEST['favourite'] !== '') {
            if ($_REQUEST['favourite'] === 'all') {
                $FavouriteProducts = FilterFavourites($Products, $Favourites);

                $Page = ShowCatalogue($FavouriteProducts, $Viewed, $Favourites, true);
            } else {
                AddProductCookie($Products, $_REQUEST['favourite'], $Favourites, 'favourites', true);
                header('Location:.');
            }
        } else if (isset($_REQUEST['cart']) && $_REQUEST['cart'] !== '') {
            if ($_REQUEST['cart'] === 'all') {
                $TopButtons = ShowTopButtons(true, $UserButton, $Cart, true);
                $Page = ShowCart($Products, $Cart, $Costs);
            } else {
                AddProductCart($Products, $_REQUEST['cart'], $Cart);
                header('Location:.');
            }
        } else if (isset($_REQUEST['nocart']) && $_REQUEST['nocart'] !== '') {
            AddProductCart($Products, $_REQUEST['nocart'], $Cart, true);

            header('Location:.?cart=all');
        } else if (isset($_REQUEST['checkout'])) {
            if ($Costs[2] > 0) {
                $TopButtons = ShowTopButtons(false, $UserButton, $Cart, false);

                if ($_SESSION['login'] === '1') {
                    if (!CheckRepliesEmpty($Replies) && count($LoginErrors) === 0) {
                        $_SESSION['cart'] = serialize(Array());

                        $Page = ShowEnd();
                    } else {
                        array_push($Selects, CreateSelect($Countries, 'country', 'id', 'name', $Replies['country']));
                        array_push($Selects, CreateSelect($Provinces, 'province', 'provincia_id', 'nombre', $Replies['province'], true));
                        array_push($Selects, CreateSelect($Municipalities, 'municipality', 'municipio_id', 'nombre', $Replies['municipality'], true));
                        array_push($Selects, CreateSelect($ZIPCodes, 'zipcode', 'cp_id', 'codigo_postal', $Replies['zipcode'], true));
                        array_push($Selects, CreateSelect($RoadTypes, 'roadtype', 'id', 'name', $Replies['roadtype']));

                        $Page = ShowCheckout($Replies, $Selects, $CheckoutErrors, $Costs);
                    }
                } else {
                    $Page = ShowLogin('.?checkout', $LoginErrors);
                }
            } else {
                header('Location:.?cart=all');
            }
        } else if (isset($_REQUEST['login'])) {
            if ($_REQUEST['login'] === '1') {
                if ($_SESSION['login'] === '1') {
                    header('Location:.');
                } else {
                    $TopButtons = ShowTopButtons(false, $UserButton, $Cart, false);
                    $Page = ShowLogin('.?login=1', $LoginErrors);
                }
            } else {
                $_SESSION['login'] = '0';

                header('Location:.');
            }
        } else {
            header('Location:.');
        }
    }
}

// Load view
require './view.php';
