<?php
namespace app\controllers;

use app\models\addresses;
use app\models\users;

class address
{
    public static function edit($defaults, $address_id)
    {
        $address = addresses::getById($address_id);
        if ($_SESSION['user_id'] != $address['user_id']) {
            http_response_code(403);
            exit;
        }
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $address = addresses::validatePost();
            if (! isset($address['error'])) {
                addresses::updateById(
                    $address_id,
                    $address['name'],
                    $address['company'],
                    $address['addressLine1'],
                    $address['addressLine2'],
                    $address['city'],
                    $address['state'],
                    $address['zip'],
                    $address['phone']
                );
                $_SESSION['success'] = "Address was updated successfully";
            }
            header('Location: /address/edit/' . $address_id);
            exit;
        }

        echo $GLOBALS['twig']->render('lib/pages/index.twig', array_merge($defaults, [
            'child_template' => 'address/edit.twig',
            'page_title'     => 'Edit Address - ' . $_ENV['APP_NAME'],
            'address'        => $address,
            'breadcrumbs'    => [
                [
                    'url'   => '/account',
                    'title' => 'My Account',
                ],
                [
                    'url'   => null,
                    'title' => 'Edit Address',
                ],
            ],
        ]));
    }

    public static function delete($defaults, $address_id)
    {
        $address = addresses::getById($address_id);
        if ($_SESSION['user_id'] != $address['user_id']) {
            http_response_code(403);
            exit;
        }
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $user = users::getById($address['user_id']);
            if ($address_id == $user['shipping_address_id'] || $address_id == $user['billing_address_id']) {
                $_SESSION['error'] = "Cannot delete default address.";
                header('Location: ' . $_GET['redirect']);
                exit;
            }
            addresses::deleteById($address_id);
            $_SESSION['success'] = "Address successfully deleted!";
            header('Location: ' . $_GET['redirect']);
            exit;
        }
    }
}
