<?php

namespace routes;

use classes\authentication;
use classes\customer_rule_product_restriction_service;
use objects\logs_o;
use objects\users_o;
use traits\route_t;

class customerAttributes
{
    use route_t;

    public function run(): void
    {
        $this->get('/customer/attributes', function () {
            // Require the user to be logged in
            global $response;
            // Get the user object
            $auth = new authentication();
            $user = $auth->get_user();
            $subuser = $auth->get_subuser();
            // Check if the request was successful
            if ($user || $subuser) {
                // Get the query parameters from the URL
                $data = $_GET;
                // Check if the required fields are set
                if (!isset($data['customer_number']) && !isset($data['user_id'])) {
                    $response->error('User ID or Customer Number is required', 400);
                }
                // Validate that the number is a number
                if (isset($data['customer_number']) && !is_numeric($data['customer_number'])) {
                    $response->error('Customer Number must be a number', 400);
                }
                // Check if the user exists
                $target_user = (new users_o())->automaticGetTargetUserFromRequest();
                if (!$target_user->exists()) {
                    $response->error('Customer not found', 400);
                }
                if (!$this->canListTargetCustomerAttributes($target_user)) {
                    $this->requirePermission('list_customer_attributes');
                }
                // Log the incident
                $actor_id = $user !== false ? (int)$user->id : (int)($subuser->id ?? 0);
                (new logs_o())->add('customer_attributes', 'global', 1, $actor_id, 'LIST_CUSTOMER_ATTRIBUTES', 'Successfully listed customer attributes');
                // Return the list of customer notes
                $response->success((new customer_rule_product_restriction_service())->enrichAttributes(
                    (int)$target_user->customer_number->value(),
                    $target_user->getUserAttributes()
                ));
            } else {
                // Log the incident
                (new logs_o())->add('customer_attributes', 'global', 1, 0, 'LIST_CUSTOMER_ATTRIBUTES', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'list_customer_attributes' => 'List all customer attributes. Authenticated customer accounts may list their own customer attributes without this permission.'
            ]
        );

        $this->post('/customer/attributes', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('add_customer_attribute');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Get the post data
                $data = json_decode(file_get_contents('php://input'), true);
                // Check if the required fields are set
                if (!isset($data['user_id']) && !isset($data['customer_number'])) {
                    $response->error('User ID or Customer Number is required', 400);
                }
                if (!isset($data['attribute'])) {
                    $response->error('Attribute is required', 400);
                }
                if (!in_array((string)$data['attribute'], customer_rule_product_restriction_service::SUPPORTED_ATTRIBUTES, true)) {
                    $response->error('Unsupported customer attribute', 422);
                }
                // Add the note to the customer
                (new users_o())->automaticGetTargetUserFromRequest()->addAttribute((string)$data['attribute']);
                // Log the incident
                (new logs_o())->add('customer_attributes', 'global', 1, $user->id, 'ADD_CUSTOMER_ATTRIBUTE', 'Successfully added a customer attribute');
                // Return a success message
                $response->success(['message' => 'Customer attribute added']);
            } else {
                // Log the incident
                (new logs_o())->add('customer_attributes', 'global', 1, 0, 'ADD_CUSTOMER_ATTRIBUTE', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'add_customer_attribute' => 'Add a customer attribute'
            ]
        );

        $this->delete('/customer/attributes', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('delete_customer_attribute');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Get the query parameters from the URL
                $data = $_GET;
                // Check if the required fields are set
                if (!isset($data['user_id']) && !isset($data['customer_number'])) {
                    $response->error('User ID or Customer Number is required', 400);
                }
                if (!isset($data['attribute'])) {
                    $response->error('Attribute is required', 400);
                }
                if (!in_array((string)$data['attribute'], customer_rule_product_restriction_service::SUPPORTED_ATTRIBUTES, true)) {
                    $response->error('Unsupported customer attribute', 422);
                }
                // Check if the user exists
                if (!(new users_o())->automaticGetTargetUserFromRequest()->exists()) {
                    $response->error('Customer not found', 400);
                }
                // Add the note to the customer
                (new users_o())->automaticGetTargetUserFromRequest()->deleteAttribute($data['attribute']);
                // Log the incident
                (new logs_o())->add('customer_attributes', 'global', 1, $user->id, 'DELETE_CUSTOMER_ATTRIBUTE', 'Successfully deleted a customer attribute');
                // Return a success message
                $response->success(['message' => 'Customer attribute deleted']);
            } else {
                // Log the incident
                (new logs_o())->add('customer_attributes', 'global', 1, 0, 'DELETE_CUSTOMER_ATTRIBUTE', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'delete_customer_attribute' => 'Delete a customer attribute'
            ]
        );
    }

    private function canListTargetCustomerAttributes(users_o $target_user): bool
    {
        if (!$target_user->exists()) {
            return false;
        }

        $target_customer_number = (int)$target_user->customer_number->value();
        if ($target_customer_number <= 0) {
            return false;
        }

        $auth = new authentication();
        $user = $auth->get_user();
        if (
            $user !== false
            && $user->exists()
            && $this->hasPermission('user')
            && (int)$user->customer_number->value() === $target_customer_number
        ) {
            return true;
        }

        return $auth->get_subuser() !== false && $this->isOwnCustomerContext($target_customer_number);
    }
}
