<?php

require_once BASE_PATH
    . '/app/controllers/customer/CustomerBaseController.php';

require_once BASE_PATH
    . '/app/models/CustomerAddress.php';


class CustomerAddressController
    extends CustomerBaseController
{
    private CustomerAddress $addressModel;


    public function __construct()
    {
        $this->requireCustomer();

        $this->addressModel =
            new CustomerAddress();
    }


    public function index(): void
    {
        $customerId =
            (int)
            $_SESSION['user']['id'];


        $addresses =
            $this->addressModel
                ->getByUserId(
                    $customerId
                );


        require BASE_PATH
            . '/app/views/customer/addresses.php';
    }


    public function create(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $customerId =
            (int)
            $_SESSION['user']['id'];


        $data =
            $this->validateAddress();


        $this->addressModel
            ->create(
                $customerId,
                $data
            );


        $this->flashSuccess(
            'Đã thêm địa chỉ giao hàng.'
        );


        $this->redirect(
            'customer/addresses'
        );
    }


    public function update(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $customerId =
            (int)
            $_SESSION['user']['id'];


        $addressId =
            (int)
            ($_POST['address_id'] ?? 0);


        $address =
            $this->addressModel
                ->findOwned(
                    $addressId,
                    $customerId
                );


        if (!$address) {

            $this->flashError(
                'Địa chỉ không tồn tại.'
            );

            $this->redirect(
                'customer/addresses'
            );
        }


        $data =
            $this->validateAddress();


        $this->addressModel
            ->update(
                $addressId,
                $customerId,
                $data
            );


        $this->flashSuccess(
            'Đã cập nhật địa chỉ.'
        );


        $this->redirect(
            'customer/addresses'
        );
    }


    public function delete(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $customerId =
            (int)
            $_SESSION['user']['id'];


        $addressId =
            (int)
            ($_POST['address_id'] ?? 0);


        $this->addressModel
            ->delete(
                $addressId,
                $customerId
            );


        $this->flashSuccess(
            'Đã xóa địa chỉ.'
        );


        $this->redirect(
            'customer/addresses'
        );
    }


    public function setDefault(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $customerId =
            (int)
            $_SESSION['user']['id'];


        $addressId =
            (int)
            ($_POST['address_id'] ?? 0);


        try {

            $this->addressModel
                ->setDefault(
                    $addressId,
                    $customerId
                );


            $this->flashSuccess(
                'Đã đặt làm địa chỉ mặc định.'
            );

        } catch (RuntimeException $e) {

            $this->flashError(
                $e->getMessage()
            );
        }


        $this->redirect(
            'customer/addresses'
        );
    }


    private function validateAddress(): array
    {
        $recipientName =
            trim(
                $_POST['recipient_name']
                ?? ''
            );


        $phone =
            trim(
                $_POST['phone']
                ?? ''
            );


        $addressLine =
            trim(
                $_POST['address_line']
                ?? ''
            );


        if (
            $recipientName === ''
            || $phone === ''
            || $addressLine === ''
        ) {

            $this->flashError(
                'Vui lòng nhập đầy đủ thông tin địa chỉ.'
            );

            $this->redirect(
                'customer/addresses'
            );
        }


        if (
            !preg_match(
                '/^0[0-9]{9}$/',
                $phone
            )
        ) {

            $this->flashError(
                'Số điện thoại người nhận không hợp lệ.'
            );

            $this->redirect(
                'customer/addresses'
            );
        }


        return [

            'recipient_name' =>
                $recipientName,

            'phone' =>
                $phone,

            'address_line' =>
                $addressLine,

            'ward' =>
                trim(
                    $_POST['ward']
                    ?? ''
                ),

            'district' =>
                trim(
                    $_POST['district']
                    ?? ''
                ),

            'province' =>
                trim(
                    $_POST['province']
                    ?? ''
                ),

            'is_default' =>
                isset(
                    $_POST['is_default']
                )
                    ? 1
                    : 0
        ];
    }
}