<?php

namespace objects;

use classes\db;
use classes\object_property;
use Exception;
use modules\selfserve\helpers\selfserve_lane_command;
use modules\selfserve\helpers\selfserve_lane_services;
use traits\db_object_t;

class department_selfserve_tasks_o extends db
{
    use db_object_t;

    public object_property $department; // The department id
    public object_property $lane; // The lane id
    public object_property $product; // The product id
    public object_property $condition_id; // The question id (if conditional task)
    public object_property $task; // The task
    public object_property $description; // The task description
    public object_property $order_priority; // The order priority of the task (lower numbers are shown first)
    public object_property $services; // The services that the task enables (json), this is used to enable machine wash.
    public object_property $buttons; // The buttons on the departments machine dynamic image that should be enabled by this task (json array of button ids)
    public object_property $dynamic_images_vehicle_type; // The vehicle type selection override on the machine, used by dynamicimages - int or null if not applicable.
    public object_property $created_at;
    public object_property $updated_at;
    public object_property $deleted_at;

    public static function getLaneProducts(int $lane_id): array
    {
        global /** @var db $db */
        $db;
        // Sanitize the input
        $lane_id = (int)$lane_id;
        // Get the products for the lane
        $sql = "SELECT DISTINCT product FROM department_selfserve_tasks WHERE lane = $lane_id AND deleted_at IS NULL ORDER BY product DESC";
        $result = $db->query($sql);
        $products = [];
        while ($row = $db->fetch_assoc($result)) {
            $products[] = (int)$row['product'];
        }
        return $products;
    }


    public function structure(): void
    {
        $this->setTable('department_selfserve_tasks');
    }

    /**
     * Add a task
     * @param int $department The department id
     * @param int $lane The lane id
     * @param int $product The product id
     * @param int|null $condition_id The question id (if conditional task)
     * @param string $task The task text
     * @param string $description The task description
     * @param int $order_priority The order priority of the task (lower numbers are shown first)
     * @param selfserve_lane_services[]|string[]|null $services The services that the task enables (stored as JSON array of service names). May be an array of enum cases or names.
     * @param array<int>|string|null $buttons Optional buttons on the department's machine dynamic image to be enabled by this task (stored as JSON array of button IDs). Accepts array of ints or a parsable string/JSON.
     * @param int|null $dynamic_images_vehicle_type Optional vehicle type selection override for the machine UI. Integer >= 0 or null.
     * @return department_selfserve_tasks_o
     * @throws Exception If the object was not created successfully
     */
    public function add(int $department, int $lane, int $product, int|null $condition_id, string $task, string $description, int $order_priority = 0, ?array $services = null, array|string|null $buttons = null, int|null $dynamic_images_vehicle_type = null): self
    {
        global /** @var db $db */
        $db;
        // Sanitize the input
        $department = (int)$department;
        $lane = (int)$lane;
        $product = (int)$product;
        if (!is_null($condition_id)) {
            $condition_id = (int)$condition_id;
        }
        $task = $db->escape_string($task);
        $description = $db->escape_string($description);
        $order_priority = (int)$order_priority;
        // If the services array is not null, validate and normalize to array of service names (strings)
        $services_names = null;
        if (!is_null($services)) {
            $services_names = [];
            foreach ($services as $service) {
                if ($service instanceof selfserve_lane_services) {
                    $services_names[] = $service->name; // store by name
                    continue;
                }
                if (is_string($service)) {
                    $name = strtoupper(trim($service));
                    $valid = false;
                    foreach (selfserve_lane_services::cases() as $case) {
                        if ($case->name === $name) {
                            $valid = true;
                            break;
                        }
                    }
                    if (!$valid) {
                        throw new Exception("Invalid service: " . $service);
                    }
                    $services_names[] = $name;
                    continue;
                }
                throw new Exception("Invalid service type");
            }
        }
        // Normalize/validate buttons
        $buttons_ids = null;
        if (!is_null($buttons)) {
            $buttons_ids = self::normalizeButtonsInput($buttons);
        }

        // Normalize/validate dynamic_images_vehicle_type (nullable, integer >= 0)
        if (!is_null($dynamic_images_vehicle_type)) {
            $dynamic_images_vehicle_type = (int)$dynamic_images_vehicle_type;
            if ($dynamic_images_vehicle_type < 0) {
                throw new Exception('dynamic_images_vehicle_type must be an integer >= 0');
            }
        }

        // Add the object
        $tmp_id = self::add_object([
            'department' => $department,
            'lane' => $lane,
            'product' => $product,
            ...(!is_null($condition_id) ? ['condition_id' => $condition_id] : []), // If the question is null, it will be set to null in the database
            'task' => $task,
            'description' => $description,
            'order_priority' => $order_priority,
            'services' => $services_names,
            'buttons' => $buttons_ids,
            ...(!is_null($dynamic_images_vehicle_type) ? ['dynamic_images_vehicle_type' => $dynamic_images_vehicle_type] : []),
        ]);
        $this->id = $tmp_id;
        self::getObjectProperties();
        self::objectChanged();
        return $this;
    }


    public function getObjectProperties(): void
    {
        $this->department = new object_property($this->table, $this->id, 'department', 'int', false);
        $this->lane = new object_property($this->table, $this->id, 'lane', 'int', false);
        $this->product = new object_property($this->table, $this->id, 'product', 'int', false);
        $this->condition_id = new object_property($this->table, $this->id, 'condition_id', 'int', true);
        $this->task = new object_property($this->table, $this->id, 'task', 'string', false);
        $this->description = new object_property($this->table, $this->id, 'description', 'string', false);
        $this->order_priority = new object_property($this->table, $this->id, 'order_priority', 'int', false);
        $this->services = new object_property($this->table, $this->id, 'services', 'json', false);
        $this->buttons = new object_property($this->table, $this->id, 'buttons', 'json', false);
        $this->dynamic_images_vehicle_type = new object_property($this->table, $this->id, 'dynamic_images_vehicle_type', 'int', false);
        $this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
        $this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'timestamp', false);
        $this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
    }

    public function objectChanged(): void
    {
        //TODO: Add cache invalidation
    }

    public function asArray(): array
    {
        return [
            'id' => (int)$this->id,
            'department' => (int)$this->department->value(),
            'lane' => (int)$this->lane->value(),
            'product' => (int)$this->product->value(),
            'condition_id' => is_null($this->condition_id->value()) ? null : (int)$this->condition_id->value(),
            'task' => (string)$this->task->value(),
            'description' => (string)$this->description->value(),
            'order_priority' => (int)$this->order_priority->value(),
            'services' => (array)$this->services->value(),
            'buttons' => (array)$this->buttons->value(),
            'dynamic_images_vehicle_type' => (function($v){ return $v === null ? null : (int)$v; })($this->dynamic_images_vehicle_type->value()),
            // Timestamps
            'created_at' => (string)$this->created_at->value(),
            'updated_at' => (string)$this->updated_at->value(),
        ];
    }

    /**
     * Normalize input for dynamic_images_vehicle_type into a nullable non-negative integer.
     * Accepts int, string (numeric), null, or empty string (treated as null).
     * @param mixed $input
     * @return int|null
     * @throws Exception on invalid format or negative values
     */
    public static function normalizeVehicleTypeInput(mixed $input): ?int
    {
        if ($input === null) {
            return null;
        }
        if (is_string($input)) {
            $trim = trim($input);
            if ($trim === '' || strtolower($trim) === 'null') {
                return null;
            }
            if (ctype_digit($trim)) {
                $val = (int)$trim;
            } elseif (is_numeric($trim) && (int)$trim == $trim) {
                $val = (int)$trim;
            } else {
                throw new Exception('Invalid dynamic_images_vehicle_type value');
            }
        } elseif (is_int($input)) {
            $val = $input;
        } else {
            throw new Exception('Invalid dynamic_images_vehicle_type value');
        }
        if ($val < 0) {
            throw new Exception('dynamic_images_vehicle_type must be >= 0');
        }
        return $val;
    }
    /**
     * Normalize mixed input for buttons into an array of integer IDs (>= 0).
     * Accepts:
     *  - array of ints/strings
     *  - JSON array string
     *  - comma-separated string
     * @param mixed $input
     * @return array<int>
     * @throws Exception
     */
    public static function normalizeButtonsInput(mixed $input): array
    {
        $raw = $input;
        if (is_string($raw)) {
            $decoded = json_decode($raw, true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                $raw = $decoded;
            } else {
                $raw = array_filter(array_map(function ($s) { return trim((string)$s); }, explode(',', $raw)), fn($s) => $s !== '');
            }
        }
        if (!is_array($raw)) {
            throw new Exception('Invalid format for buttons. Expected array, JSON array, or comma-separated string of integers.');
        }
        $ids = [];
        foreach ($raw as $btn) {
            if (is_int($btn)) {
                $val = $btn;
            } elseif (is_string($btn) && ctype_digit($btn)) {
                $val = (int)$btn;
            } elseif (is_numeric($btn) && (int)$btn == $btn) {
                $val = (int)$btn;
            } else {
                throw new Exception('Invalid button id: ' . (is_scalar($btn) ? (string)$btn : gettype($btn)));
            }
            if ($val < 0) {
                throw new Exception('Button id must be >= 0: ' . $val);
            }
            $ids[] = $val;
        }
        // de-duplicate while preserving order
        $ids = array_values(array_unique($ids));
        return $ids;
    }
}