<?php

namespace helpers;

use classes\motorapi;
use objects\customer_vehicles_o;
use objects\products_o;

class xlvask_parser_stor_bil extends xlvask_product_parser
{
    use xlvask_product_parser_t;

    public function __construct()
    {
        $this->setup('Stor bil');
    }


    /**
     * @inheritDoc
     * @throws \Exception
     */
    protected function parse(xlvask_wash_item $wash_item, xlvask_usage_log $xlvask_usage_log): products_o
    {
        //echo 'Attempting to parse Stor Bil product: ' . $this->OriginalProductName . PHP_EOL;
        //echo ' Step 1: Validating wash item and usage log.' . PHP_EOL;
        $registrationNumber = $xlvask_usage_log->RegistrationNumber;
        $vehicleType = $xlvask_usage_log->VehicleType; // E.g. "Bus/autocamper, M"
        /**
         * All the vehicle types that this parser supports.
         * Copied from XL Vask's vehicle types @ 10:32 10/06/2025
         * **
         * Anlægsmaskine
         * Bus/autocamper, L
         * Bus/autocamper, M
         * Bus/autocamper, S
         * Containerbil
         * Containerbil med hænger
         * Containertræk
         * Entreprenør forvogn/trækker
         * Entreprenør sættevogn
         * Forvogn med hænger
         * Forvogn med hænger, autotransport
         * Forvogn med krogehejs
         * Forvogn, L
         * Forvogn, lave sider
         * Forvogn, M
         * Forvogn, S
         * Forvogn, skraldebil
         * Kassevogn/Varevogn, L
         * Kassevogn/Varevogn, S
         * Kun trailer
         * Landbrugstraktor
         * Minibus
         * Personbil
         * Pickup
         * Sættevognstræk
         * Sættevognstræk, maskintrailer
         * Tankvogn
         * Tankvogn, Slamsuger
         * Tankvognstræk
         * Tankvognstræk, silobil
         * Trækker
         * Tømmerbil
         */

        $vehicleTypes = [
            // Formats for vehicle types
            // 'exact match' => ['Vehicle Type 1', 'Vehicle Type 2'], - Matches when the vehicle type is exactly one of these.
            // 'contains' => ['Vehicle Type 3', 'Vehicle Type 4'], - Matches when the vehicle type contains any of these substrings.
            // 'matchFunction' => function($vehicleType) { return true; } - Matches when the vehicle type passes this function.
            // product_id => ['exact match' => ['Vehicle Type 1', 'Vehicle Type 2'], 'contains' => ['Vehicle Type 3', 'Vehicle Type 4'], 'matchFunction' => function]
            // Trækker (1)
            1 => [
                'exact match' => ['Trækker'],
                'contains' => ['Trækker'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Trækker$/', $vehicleType);
                }
            ],
            // Trailer (2)
            2 => [
                'exact match' => ['Kun trailer'],
                'contains' => ['Trailer'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Kun trailer$/', $vehicleType);
                }
            ],
            // Sættevognstræk (3)
            3 => [
                'exact match' => ['Sættevognstræk'],
                'contains' => ['Sættevognstræk'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Sættevognstræk$/', $vehicleType);
                }
            ],
            // Dolly (4)
            4 => [
                'exact match' => ['Dolly'],
                'contains' => ['Dolly'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Dolly$/', $vehicleType);
                }
            ],
            // Forvogn (5)
            5 => [
                'exact match' => ['Forvogn, L', 'Forvogn, M', 'Forvogn, S', 'Forvogn, lave sider', 'Forvogn med krogehejs', 'Forvogn, skraldebil'],
                'contains' => ['Forvogn'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Forvogn/', $vehicleType);
                }
            ],
            // Forvogn med hænger (6)
            6 => [
                'exact match' => ['Forvogn med hænger', 'Forvogn med hænger, autotransport'],
                'contains' => ['Forvogn med hænger'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Forvogn med hænger/', $vehicleType);
                }
            ],
            // Tankvogn (7)
            7 => [
                'exact match' => ['Tankvogn', 'Tankvogn, Slamsuger'],
                'contains' => ['Tankvogn'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Tankvogn/', $vehicleType);
                }
            ],
            // Tankvogn med hænger (8)
            8 => [
                'exact match' => ['Tankvognstræk', 'Tankvognstræk, silobil'],
                'contains' => ['Tankvognstræk'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Tankvognstræk/', $vehicleType);
                }
            ],
            // Tankvognstræk (9)
            9 => [
                'exact match' => ['Tankvognstræk', 'Tankvognstræk, silobil'],
                'contains' => ['Tankvognstræk'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Tankvognstræk/', $vehicleType);
                }
            ],
            // Kassevogn/Varevogn (15)
            15 => [
                'exact match' => ['Kassevogn/Varevogn, L', 'Kassevogn/Varevogn, S'],
                'contains' => ['Kassevogn', 'Varevogn'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Kassevogn\/Varevogn/', $vehicleType);
                },
                'MotorAPI match' => ['use' => ['Buskørsel' => false, 'Busku00f8rsel' => false]],
            ],
            // Campingvogn/Autocamper (16)
            16 => [
                'exact match' => ['Bus/autocamper, L', 'Bus/autocamper, M', 'Bus/autocamper, S'],
                'contains' => ['Bus', 'Autocamper'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Bus\/autocamper/', $vehicleType);
                },
                'MotorAPI match' => ['use' => ['Buskørsel' => false, 'Busku00f8rsel' => false]],
            ],
            // Bus (17)
            17 => [
                'exact match' => ['Bus/autocamper, L', 'Bus/autocamper, M', 'Bus/autocamper, S'],
                'contains' => ['Bus'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Bus\/autocamper/', $vehicleType);
                },
                'MotorAPI match' => ['use' => ['Buskørsel' => true, 'Busku00f8rsel' => true]],
            ],
            // Entreprenør forvogn (18)
            18 => [
                'exact match' => ['Entreprenør forvogn/trækker'],
                'contains' => ['Entreprenør forvogn', 'Trækker'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Entreprenør forvogn/', $vehicleType);
                }
            ],
            // Entreprenør forvogn med kærre (19)
            19 => [
                'exact match' => ['Entreprenør sættevogn'],
                'contains' => ['Entreprenør sættevogn'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Entreprenør sættevogn$/', $vehicleType);
                }
            ],
            // Entreprenør sættevogn (20)
            20 => [
                'exact match' => ['Entreprenør sættevogn'],
                'contains' => ['Entreprenør sættevogn'],
                'matchFunction' => function ($vehicleType) {
                    return preg_match('/^Entreprenør sættevogn$/', $vehicleType);
                }
            ],
        ];

        // Check if the vehicle type matches any of the defined vehicle types
        $isValidVehicleType = false;
        $productId = null; // Initialize product_id to null
        // Check if the vehicle is present in the customer vehicles
        $customer_vehicles = new customer_vehicles_o();
        try {
            $customer_vehicle = $customer_vehicles->selectByPlate($registrationNumber);
            // If the vehicle type is above 0, we can assume it's that exact type
            if (isset($customer_vehicle->id) && (int)$customer_vehicle->type->value() > 0) {
                $isValidVehicleType = true; // Set to true to indicate a valid vehicle type
                $productId = (int)$customer_vehicle->type->value();
            }
        } catch (\Exception $e) {
            // If the vehicle is not found, we can still proceed with the vehicle type validation
        }
        foreach ( $vehicleTypes as $product_id => $conditions ) {
            if ($isValidVehicleType) {
                // If we have already determined a valid vehicle type from customer vehicles, skip further checks
                break;
            }
            if (isset($conditions['MotorAPI match']) && is_array($conditions['MotorAPI match'])) {
                if (!$this->checkMotorAPI($registrationNumber, $conditions['MotorAPI match'])) {
                    // If the MotorAPI check fails, skip to the next vehicle type
                    continue;
                } else {
                    // If the MotorAPI check passes, continue with the vehicle type validation
                    $isValidVehicleType = true; // Set to true to indicate a valid vehicle type
                    $productId = $product_id; // Set the product_id if the MotorAPI check passes
                    break; // Break out of the loop since we found a valid vehicle type
                }
            }
            if (in_array($vehicleType, $conditions['exact match'], true)) {
                $isValidVehicleType = true;
                $productId = $product_id; // Set the product_id if an exact match is found
                break;
            }
            foreach ( $conditions['contains'] as $substring ) {
                if (strpos($vehicleType, $substring) !== false) {
                    $isValidVehicleType = true;
                    $productId = $product_id; // Set the product_id if a substring match is found
                    break 2; // Break out of both loops
                }
            }
            if (isset($conditions['matchFunction']) && is_callable($conditions['matchFunction']) && $conditions['matchFunction']($vehicleType)) {
                $isValidVehicleType = true;
                $productId = $product_id; // Set the product_id if the match function returns true
                break;
            }
        }
        if (!$isValidVehicleType) {
            //echo 'Step 2: Vehicle type does not match any of the defined vehicle types.' . PHP_EOL;
            throw new \Exception('Vehicle type does not match any of the defined vehicle types.');
        }
        //echo ' Found matching vehicle type: ' . $vehicleType . PHP_EOL;
        //echo ' Step 3: Vehicle type is valid, proceeding with product creation.' . PHP_EOL;


        // Check if the vehicle
        //print_r($xlvask_usage_log);

        // Create a new product object
        return (new products_o())->select((int)$productId);
    }

    protected function checkMotorAPI($registrationNumber, $motorAPIMatch): bool
    {
        // Check if the MotorAPI match is set and if the registration number matches the conditions
        $motorAPI = new motorapi();
        try {
            $motorAPI_result = $motorAPI->getLicensePlateInformation($registrationNumber, false);
        } catch (\Exception $e) {
            return false;
            // throw new \Exception('Error fetching data from MotorAPI: ' . $e->getMessage());
        }
        foreach ($motorAPIMatch as $key => $value) {
            if (isset($motorAPI_result->$key)) {
                $subkeys = array_keys($value);
                if (in_array($motorAPI_result->$key, $subkeys, true)) {
                    return (bool)$value[$motorAPI_result->$key]; 
                } else {
                    // If the key does not match any of the subkeys, check if there's any subkey requiring a true value
                    foreach ($subkeys as $subkey) {
                        if ($value[$subkey] === true) {
                            // If any subkey requires a true value, return false
                            return false;
                        }
                    }
                }
            } else {
                // If the key does not exist in the MotorAPI result, return false
                return false;
            }
        }
        // If all conditions are met, return true
        return true;
    }
}