<?php
namespace app\controllers;

use app\models\addresses;
use app\models\magic_links;
use app\models\transactions;
use app\models\users;
use app\models\user_settings;

class account
{
    public static function index($defaults): void
    {
        echo $GLOBALS['twig']->render('lib/pages/index.twig', array_merge($defaults, [
            'child_template' => 'account/index.twig',
            'page_title'     => 'Manage Account - ' . $_ENV['APP_NAME'],
            'user'           => users::getById($_SESSION['user_id']),
            'addresses'      => addresses::getByUserId($_SESSION['user_id']),
            'balance'        => transactions::getUserBalance($_SESSION['user_id']),
            'breadcrumbs'    => [
                [
                    'url'   => null,
                    'title' => 'My Account',
                ],
            ],
        ]));
    }

    public static function billing($defaults)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $bill = addresses::validatePost("billing_");
            if (isset($bill['error'])) {
                header('Location: /account/billing');
                exit;
            }
            $bill_id = addresses::add(
                $_SESSION['user_id'],
                $bill['name'],
                $bill['company'],
                $bill['addressLine1'],
                $bill['addressLine2'],
                $bill['city'],
                $bill['state'],
                $bill['zip'],
                $bill['phone'],
            );
            $_SESSION['success'] = "Billing address saved!";
            header('Location: /account/billing');
            exit;
        }
        echo $GLOBALS['twig']->render('lib/pages/index.twig', array_merge($defaults, [
            'child_template' => 'account/billing.twig',
            'page_title'     => 'Billing Information - ' . $_ENV['APP_NAME'],
            'user'           => users::getById($_SESSION['user_id']),
            'addresses'      => addresses::getByUserId($_SESSION['user_id']),
            'breadcrumbs'    => [
                [
                    'url'   => '/account',
                    'title' => 'My Account',
                ],
                [
                    'url'   => null,
                    'title' => 'Billing',
                ],
            ],
        ]));
    }
    public static function profile()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            users::updateProfileById($_SESSION['user_id'], $_POST);
            $dark_theme = $_POST['dark_theme'] ?? false;
            user_settings::update($_SESSION['user_id'], ['dark_theme' => $dark_theme]);
            $_SESSION['success'] = 'Profile information updated sucessfully!';
            header('Location: /account');
            exit;
        }
    }

    public static function email()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $email = $_POST['email'] ?? null;
            if (empty($email)) {
                $_SESSION['error'] = "Enter your email to get a login link";
                header('Location: /account');
                exit;
            } else {
                $user_id = $_SESSION['user_id'];
                $token   = magic_links::add($email, $user_id);
                users::updateReplaceEmailTokenById($user_id, $token);
                header('Location: /account/verify');
                exit;
            }
        }
    }

    public static function verify($defaults)
    {
        echo $GLOBALS['twig']->render('lib/pages/index.twig', array_merge($defaults, [
            'child_template' => 'account/verify.twig',
            'page_title'     => $_ENV['APP_NAME'],
            'breadcrumbs'    => [
                [
                    'url'   => '/account',
                    'title' => 'My Account',
                ],
                [
                    'url'   => null,
                    'title' => 'Verify',
                ],
            ],
        ]));
    }

    public static function login($defaults)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $email = $_POST['email'] ?? false;
            if (empty($email)) {
                $_SESSION['error'] = "Enter your email to get a login link";
                header('Location: /account/login');
                exit;
            } else {
                $token = magic_links::add($email, null);
                header('Location: /account/verify');
                exit;
            }
        }
        if (isset($_SESSION['user_id'])) {
            header('Location: /account');
            exit;
        }
        echo $GLOBALS['twig']->render('lib/pages/index.twig', array_merge($defaults, [
            'child_template' => 'account/login.twig',
            'page_title'     => 'Sign In or Create an Account!',
            'breadcrumbs'    => [
                [
                    'url'   => null,
                    'title' => 'My Account',
                ],
            ],
        ]));
    }

    public static function notifications($defaults)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $opt_in_promotional  = isset($_POST['opt_in_promotional']) ? (bool) $_POST['opt_in_promotional'] : false;
            $opt_in_subscription = isset($_POST['opt_in_subscription']) ? (bool) $_POST['opt_in_subscription'] : false;
            $opt_in_order        = isset($_POST['opt_in_order']) ? (bool) $_POST['opt_in_order'] : false;
            users::updateOptIn($_SESSION['user_id'], $opt_in_promotional, $opt_in_subscription, $opt_in_order);
            $_SESSION['success'] = "Notification preferences updated successfully.";
            header('Location: /account');
            exit;
        }
    }

    public static function logout()
    {
        session_unset();
        session_destroy();
        header('Location: /');
    }

    public static function orders($defaults)
    {
        echo $GLOBALS['twig']->render('lib/pages/index.twig', array_merge($defaults, [
            'child_template' => 'account/orders.twig',
            'page_title'     => 'View ' . $_ENV['APP_NAME'] . ' Orders',
            'breadcrumbs'    => [
                [
                    'url'   => '/account',
                    'title' => 'My Account',
                ],
                [
                    'url'   => null,
                    'title' => 'Orders',
                ],
            ],
        ]));
    }

    public static function returns($defaults)
    {
        echo $GLOBALS['twig']->render('lib/pages/index.twig', array_merge($defaults, [
            'child_template' => 'account/returns.twig',
            'page_title'     => 'View ' . $_ENV['APP_NAME'] . ' Returns',
            'breadcrumbs'    => [
                [
                    'url'   => '/account',
                    'title' => 'My Account',
                ],
                [
                    'url'   => null,
                    'title' => 'Returns',
                ],
            ],
        ]));
    }
    public static function shipping($defaults)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $ship = addresses::validatePost("shipping_");
            if (isset($ship['error'])) {
                header('Location: /account/shipping');
                exit;
            }
            $ship_id = addresses::add(
                $_SESSION['user_id'],
                $ship['name'],
                $ship['company'],
                $ship['addressLine1'],
                $ship['addressLine2'],
                $ship['city'],
                $ship['state'],
                $ship['zip'],
                $ship['phone'],
            );
            $_SESSION['success'] = "Shipping address saved!";
            header('Location: /account/shipping');
            exit;
        }

        echo $GLOBALS['twig']->render('lib/pages/index.twig', array_merge($defaults, [
            'child_template' => 'account/shipping.twig',
            'page_title'     => $_ENV['APP_NAME'] . ' Shipping',
            'user'           => users::getById($_SESSION['user_id']),
            'addresses'      => addresses::getByUserId($_SESSION['user_id']),
            'breadcrumbs'    => [
                [
                    'url'   => '/account',
                    'title' => 'My Account',
                ],
                [
                    'url'   => null,
                    'title' => 'Shipping',
                ],
            ],
        ]));
    }
    public static function set_default_shipping($defaults)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $address_id = $_POST['address_id'] ?? null;
            if ($address_id) {
                users::setDefaultShipping($_SESSION['user_id'], $address_id);
                $_SESSION['success'] = "Default shipping address set successfully!";
            } else {
                $_SESSION['error'] = "Failed to set default shipping address.";
            }
            header('Location: /account/shipping');
            exit;
        }
    }

    public static function set_default_billing($defaults)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $address_id = $_POST['address_id'] ?? null;
            if ($address_id) {
                users::setDefaultBilling($_SESSION['user_id'], $address_id);
                $_SESSION['success'] = "Default billing address set successfully!";
            } else {
                $_SESSION['error'] = "Failed to set default billing address.";
            }
            header('Location: /account/billing');
            exit;
        }
    }

    public static function signup($defaults)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $email = $_POST['email'];
            if (empty($email)) {
                $_SESSION['error'] = 'Email is required.';
            }
            $existingUser = users::getByEmail($email);
            if ($existingUser) {
                $token = magic_links::add($email, $user_id);
                header("Location: /account/verify");
                exit;
            }
            $useShipping = $_POST['use_shipping'] ?? false;
            $ship        = addresses::validatePost("shipping_");
            if (isset($ship['error'])) {
                $_SESSION['error']     = "Shipping address verification failed. " . $_SESSION['error'];
                $_SESSION['last_post'] = $_POST;
                header('Location: /account/signup');
                exit;
            }
            if (! $useShipping) {
                $bill = addresses::validatePost("billing_");
                if (isset($bill['error'])) {
                    $_SESSION['error']     = "Billing address verification failed. " . $_SESSION['error'];
                    $_SESSION['last_post'] = $_POST;
                    header('Location: /account/signup');
                    exit;
                }
            }
            if (isset($_SESSION['error'])) {
                $_SESSION['last_post'] = $_POST;
                header('Location: /account/signup');
                exit;
            }
            $ship_id = addresses::add(
                null,
                $ship['name'],
                $ship['company'],
                $ship['addressLine1'],
                $ship['addressLine2'],
                $ship['city'],
                $ship['state'],
                $ship['zip'],
                $ship['phone'],
            );
            $bill_id = $ship_id;
            if (! $useShipping) {
                $bill_id = addresses::add(
                    null,
                    $bill['name'],
                    $bill['company'],
                    $bill['addressLine1'],
                    $bill['addressLine2'],
                    $bill['city'],
                    $bill['state'],
                    $bill['zip'],
                    $bill['phone'],
                );
            }
            $opt_in_promotional = $_POST['opt_in_promotional'] ?? false;
            $verified           = isset($_SESSION['user_email']);
            $dark_theme         = $defaults['theme'] == 'dark';
            $user_id            = users::add(
                $email,
                $ship_id,
                $bill_id,
                $opt_in_promotional,
                $verified,
                $dark_theme
            );
            $_SESSION['user_id'] = $user_id;
            if (! $verified) {
                $token = magic_links::add($email, $user_id);
                header("Location: /account/verify");
                exit;
            }
            header('Location: /account');
            exit;
        } // endif request === POST

        if (isset($_SESSION['user_id'])) {
            header('Location: /account');
            exit;
        }

        echo $GLOBALS['twig']->render('lib/pages/index.twig', array_merge($defaults, [
            'child_template' => 'account/signup.twig',
            'page_title'     => 'Create an Account - ' . $_ENV['APP_NAME'],
        ]));
    }
}
