<?php

namespace routes;

use classes\entra;
use classes\redis;
use dynamicimages\images\machine_1;
use goals\classes\goals;
use goals\classes\goals_criteria;
use objects\collected_order_invoices_o;
use objects\departments_o;
use objects\order_items_o;
use objects\orders_o;
use objects\products_o;
use objects\users_o;
use traits\route_t;

class exampleRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/example', function () {
            global $response;
            // This is very hack-y, but it works for now
            // Check if it's monday
            if ((int)date('N') === 1) {
                // Check if the time is between 06:00 and 17:00
                if (!redis->exists('system:last_sent_monday_message') && (date('H') >= 6 && date('H') < 17)) {
                    // Set the key to expire in 24 hours
                    redis->set('system:last_sent_monday_message', date('Y-m-d H:i:s'));
                    redis->expire('system:last_sent_monday_message', 86400);
                    // Send the messages
                    $departments = [
                        1,
                        2,
                        3,
                        4,
                        5,
                        6,
                        7,
                    ];
                    foreach ($departments as $department_id) {
                        $department = (new departments_o())->select((int)$department_id);
                        $days = 7;
                        // The time should be from 00:00:00 of the start date to 23:59:59 of the end date
                        $date_end = date('Y-m-d 23:59:59', strtotime("-1 days")); // Yesterday (Sunday) at 23:59:59
                        $date_start = date('Y-m-d 00:00:00', strtotime("-$days days")); // $days ago at 00:00:00
                        $department->sendPeriodStatisticsToSlack($date_start, $date_end); // Sends message to "daglig-ledelse".
                    }
                    $department->sendSlackInternalStatisticNotification($date_start, $date_end, $departments);
                }
            }
            $response->success(['message' => 'Hello World!']);
        });

        $this->get('/tmp-customer-list-overcharged', function () {
            global $response;
            $response->error(['message' => 'This route is deprecated.']);
            /**
             * Steps:
             * 1. Get a list of all collected order invoices in january
             * 2. Extract the customers, and make sure they haven't been charged more than once for product ID: 78.
             * 3. Get a list of the amount of times, at what price and for what order IDs they have been charged.
             * 4. If they have been charged more than once, add them to a list of overcharged customers.
             * 5. Return the list of overcharged customers.
             */
            // Step 1: Get a list of all collected order invoices in january
            $invoices = [];
            $product = (new products_o())->select(78);
            $all_invoices = (new collected_order_invoices_o())->getObjectsWhereClause("closed_at BETWEEN '2026-01-31 00:00:00' AND '2026-02-01 23:59:59'");
            // Filter out empty invoices
            foreach ($all_invoices as $invoice) {
                if ($invoice->isEmpty()) {
                    continue;
                }
                $invoices[] = $invoice;
            }
            // Get all orders related to the invoices
            $overcharged_customers = [];
            $order_ids = (new orders_o())->getFieldsWhereIn([
                'deleted_at' => null,
                'invoice_collection_id' => array_map(function ($invoice) {
                    return $invoice->id;
                    }, $invoices)],
                ['id', 'customer_id']);
            $order_id_to_customer_id = array_column($order_ids, 'customer_id', 'id');
            $order_ids = array_map(function ($order) {
                return (int)$order['id'];
            }, $order_ids);
            // Get all the products in the orders
            $order_items = (new order_items_o())->getFieldsWhereIn(['order_id' => $order_ids, 'product_id' => [$product->id], 'deleted_at' => null], ['price', 'quantity', 'order_id', 'id']);
            // Define the customers => items map
            $customer_items_map = [];
            foreach ($order_items as $order_item) {
                $customer_items_map[(string)$order_id_to_customer_id[(string)$order_item['order_id']]][] = $order_item;
            }
            // Ignore the first item for each customer (as that is correct)
            foreach ($customer_items_map as $customer_id => $items) {
                array_shift($customer_items_map[$customer_id]);
            }
            // Create a total per customer number of items and price map
            foreach ($customer_items_map as $customer_id => $items) {
                $total_quantity = 0;
                $total_price = 0.0;
                foreach ($items as $item) {
                    $total_quantity += (int)$item['quantity'];
                    $total_price += (float)$item['price'] * (int)$item['quantity'];
                }
                // If the total quantity is more than 1, add to overcharged customers
                if ($total_quantity > 1) {
                    $overcharged_customers[$customer_id] = [
                        'total_quantity' => $total_quantity,
                        'total_price' => $total_price,
                        'items' => $items,
                    ];
                }
            }

            // Format message
            foreach ($overcharged_customers as $customer_id => $data) {
                $customer = (new users_o())->getUserByCustomerNumber((int)$customer_id);
                $message = "Customer number: {$customer->customer_number->value()} - x{$data['total_quantity']} items for a total of {$data['total_price']} DKK\n";
                //$message .= "Items:\n";
                foreach ($data['items'] as $item) {
                    //$message .= "- Order Item ID: {$item['id']}, Order ID: {$item['order_id']}, Price: {$item['price']}, Quantity: {$item['quantity']}\n";
                }
                echo $message . "\n";
            }

            $response->success(['message' => 'Customer list overcharged', 'inv_count' => count($invoices), 'ord_count' => count($order_ids), 'order_ids' => $order_ids, 'order_items' => count($order_items), 'customer_items_map' => $customer_items_map, 'overcharged_customers' => $overcharged_customers]);
        });

        $this->get('/debug', function () {
            global $response;
            $response->success(['message' => 'Debugging route!']);
            $machine_1 = new machine_1();
            //$machine_1->debugAssets();
            $machine_1->current_step = 0;
            $machine_1->only_generate_current_step = false;
            $machine_1->highlighted_buttons = [
                //0, 2, 4, 7
            ];
            $machine_1->setup();
            $machine_1->servePicture();
            exit;
            $response->success(['message' => 'Debugging route!', 'base64_image' => $machine_1->exportAsBase64()]);
        });
    }
}