<?php

namespace App\Controllers;

use App\Models\Groups;
use App\Models\Orders;
use App\Models\Products;
use App\Models\Stores;
use App\Models\Users;

class StatistiqueController extends AdminController
{
    public function index()
    {
        $orderModel = new Orders();
        $userModel = new Users();
        $storeModel = new Stores();

        // 7 is the role Commercial
        $allUsers = $userModel->getUsersByGroup();
        $orderPaid = $orderModel->getPaidOrderData();
        
        $newData = [];
        for ($i = 0; $i < count($orderPaid); $i++) {
            $transitionData = [];
            for ($k = 0; $k < count($allUsers); $k++) {
                if ($allUsers[$k]['id'] == $orderPaid[$i]['user_id']) {
                    $transitionData2 = [
                        'userId' => $allUsers[$k]['id'],
                        'userName' => $allUsers[$k]['username'],
                        'billId' => $orderPaid[$i]['id'],
                        'billNo' => $orderPaid[$i]['bill_no'],
                        'dateVente' => $orderPaid[$i]['date_time'],
                        'montantNet' => $orderPaid[$i]['net_amount'],
                    ];
                    $transitionData[] = $transitionData2;
                }
            }
            $newData[] = $transitionData;
        }

        // filter to keep non empty array
        $filteredArray = array_filter($newData, function ($item) {
            return !empty($item); // Keep only non-empty arrays
        });
        

        // Re-index the array (optional, if you want sequential keys)
        $userWhoSoldProducts = array_values($filteredArray);

        // Count occurrences of each userId
        $userIdCounts = array_reduce($userWhoSoldProducts, function($carry, $item) {
            $userId = $item[0]['userId'];
            if (!isset($carry[$userId])) {
                $carry[$userId] = 0;
            }
            $carry[$userId]++;
            return $carry;
        }, []);

        foreach ($allUsers as &$user) {
            $userId = (int)$user['id'];
            if (isset($userIdCounts[$userId])) {
                $user['totalVente'] = $userIdCounts[$userId];
            } else {
                $user['totalVente'] = 0; // or any default value you want to assign if the user ID is not found in $userIdCount
            }
        }

        $data['allUsers'] = $allUsers;
        $data['page_title'] = 'Statistique';
        // Check if the user is an Conseil
        $session = session();
        $user_id = $session->get('user');
        // $data['is_admin'] = ($user_id['id'] == 1);
        // echo '<pre>';
        // var_dump($allUsers);
        // echo '</pre>';
        $data['is_admin'] = false;
        
        if ($user_id['group_name'] == "Direction" || $user_id['group_name'] == "SuperAdmin") {
            $data['is_admin'] = true;
        }
        
        // echo '<pre>';
        // die(var_dump($newData));

        return $this->render_template('statistic/index', $data);
    }

    public function testindex()
    {
        // Sample data
        $data = [
            [
                [
                    "userId" => "7",
                    "userName" => "Billy",
                    "billId" => "10",
                    "billNo" => "BILPR-500F",
                    "dateVente" => "2025-01-25 14:33:54",
                    "montantNet" => "638580.96"
                ]
            ],
            // [
            //     [
            //         "userId" => "9",
            //         "userName" => "john does",
            //         "billId" => "5",
            //         "billNo" => "BILPR-3D87",
            //         "dateVente" => "2025-01-19 14:33:54",
            //         "montantNet" => "12.90"
            //     ]
            // ],
            [
                [
                    "userId" => "7",
                    "userName" => "Billy",
                    "billId" => "4",
                    "billNo" => "BILPR-A004",
                    "dateVente" => "2025-01-18 14:33:54",
                    "montantNet" => "12.90"
                ]
            ]
            // [
            //     [
            //         "userId" => "9",
            //         "userName" => "john does",
            //         "billId" => "3",
            //         "billNo" => "BILPR-7C26",
            //         "dateVente" => "2025-01-17 14:33:54",
            //         "montantNet" => "438.60"
            //     ]
            // ]
        ];

        // Process data
        $userData = [];
        foreach ($data as $entry) {
            $record = $entry[0];
            $userId = $record['userId'];
            $userName = $record['userName'];

            // Ensure user exists in the array
            if (!isset($userData[$userId])) {
                $userData[$userId] = [
                    'name' => $userName,
                    'dates' => [],
                    'values' => []
                ];
            }

            // Store date and montantNet
            $userData[$userId]['dates'][] = $record['dateVente'];
            $userData[$userId]['values'][] = (float) $record['montantNet'];
        }

        $data['userData'] = json_encode($userData);
        $data['page_title'] = 'Statistique';
        // die(var_dump($data));
        // return view('chart_view', ['userData' => json_encode($userData)]);
        return $this->render_template('statistic/single', $data);
    }

    public function singleStat(int $id)
    {
        $Order = new Orders();

        $data['user_order'] = json_encode($Order->getSingleStat($id), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
        $data['page_title'] = 'Statistique';
        
        return $this->render_template('statistic/single', $data);
    }
}
