verifyRole('viewReports'); $data['page_title'] = $this->pageTitle; // Get the current year or the selected year from the form $today_year = date('Y'); if ($this->request->getPost('select_year')) { $today_year = $this->request->getPost('select_year'); } // Fetch order data and years $Reports = new Reports(); $Orders = new Orders(); $Store = new Stores(); $parking_data = $Reports->getOrderData($today_year); $data['report_years'] = $Reports->getOrderYear(); // Process the parking data and calculate total amounts $final_parking_data = []; foreach ($parking_data as $month => $orders) { $total_amount_earned = 0; // Initialize the total amount for the month if (!empty($orders)) { foreach ($orders as $order) { $total_amount_earned += (float) $order['net_amount']; } } $final_parking_data[$month] = $total_amount_earned; } // Data for the camembert (pie chart) $paymentModes = $Orders->getPaymentModes(); $total_mvola1 = $paymentModes->total_mvola1; $total_mvola2 = $paymentModes->total_mvola2; $total_espece1 = $paymentModes->total_espece1; $total_espece2 = $paymentModes->total_espece2; $total_banque1 = $paymentModes->total_virement_bancaire1; $total_banque2 = $paymentModes->total_virement_bancaire2; $total_mvola = $total_mvola1 + $total_mvola2; $total_banque = $total_banque1 + $total_banque2; $total_espece = $total_espece1 + $total_espece2; $totalOrders = $Orders->getTotalOrders(); $totalAmountPerPaymentModes = ["MVOLA" => $total_mvola, "Espece" => $total_espece, "Virement Bancaire" => $total_banque]; $totalOrdersCount = (int) $totalOrders->total_orders; $labels = []; $totals = []; if ($totalOrdersCount > 0) { foreach ($totalAmountPerPaymentModes as $mode => $total) { $labels[] = $mode; $totals[] = $total; } } $data['labels'] = json_encode($labels); $data['totals'] = json_encode($totals); // Prepare data for product chart $OrderItem = new OrderItems(); $productTable = $OrderItem->getAllSoldProductToday(); $product_sold = (int) $productTable->total_product_sold; $unsold_product = (int) $productTable->total_unsold_product; $labels1 = ["Produits vendus", "Produits non vendus"]; $totals2 = [$product_sold, $unsold_product]; $data['labels_product'] = json_encode($labels1); $data['totals_product'] = json_encode($totals2); // Prepare data for the view $data['selected_year'] = $today_year; $data['company_currency'] = $this->companycurrency(); $data['results'] = $final_parking_data; // Data for the camembert in dashboard $totalStoreOrder = $Orders->getTotalOrderPerStore(); $totalOrders = $Orders->getTotalOrders(); $totalOrdersCount = (int) $totalOrders->total_orders; // Initialisation des variables pour éviter l'erreur "Undefined variable" $labelStore = []; $totalPerStore = []; foreach ($totalStoreOrder as $totalOrdersInStore) { $storeList = $Store->getStoreById($totalOrdersInStore->store_id); $labelStore[] = $storeList->name ?? 'Inconnu'; $totalPerStore[] = ((int) $totalOrdersInStore->total / $totalOrdersCount) * 100; } $data['labelStore'] = json_encode($labelStore); $data['totalPerStore'] = json_encode($totalPerStore); // Load the view return $this->render_template('reports/index', $data); } private function companycurrency() { return 'AR'; // Replace with your actual logic for company currency } public function stockDetail() { $this->verifyRole('viewReports'); $data['page_title'] = $this->pageTitle; $Orders = new Orders(); $Products = new Products(); $Stores = new Stores(); $productVente = $Orders->getTotalProductvente(); $produitStock = $Products->getProductData(); $stor = $Stores->getActiveStore(); $data['ventes'] = \json_encode($productVente); $data['stock'] = \json_encode($produitStock); $data['stores'] = $stor; // echo '
';
        // die(var_dump($produitStock));

        return $this->render_template('reports/stockDetail', $data);
    }

    private function returnName(int $id)
    {
        $Stores = new Stores();
        $stor = $Stores->getActiveStore();
        $Storename = "";
        foreach ($stor as $key => $value) {
            if ($value['id'] == $id) {
                $Storename = $value['name'];
            }
        }

        return $Storename;
    }

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

        $productVente = $Orders->getTotalProductvente2($id);
        $result = ['data' => []];

        foreach ($productVente as $key => $value) {
            // die(var_dump($value)); // Debugging: Check what $value contains

            // Add the row data
            $result['data'][$key] = [
                $value->sku,
                $value->date_time,
                $this->returnName($value->store_id)
            ];
        }

        // Return data in JSON format
        return $this->response->setJSON($result);
    }

    private function checkArrivalDate($dateArivage)
    {
        $dateArivage = new DateTime($dateArivage);
        $today = new DateTime();
        $interval = $dateArivage->diff($today);

        // Return the date only if it is within the last 15 days
        return $interval->days . " Jours";
    }

    public function fetchProductStock(int $id)
    {
        $Products = new Products();

        $produitStock = $Products->getProductData2($id);
        $result = ['data' => []];

        foreach ($produitStock as $key => $value) {
            // die(var_dump($value)); // Debugging: Check what $value contains

            // Add the row data
            $result['data'][$key] = [
                $value['brand_name'],
                $value['total_product'] . " Motos",
                $this->returnName($value['store_id'])
            ];
        }

        // Return data in JSON format
        return $this->response->setJSON($result);
    }

    public function fetchProductStock2(int $id)
    {
        $Products = new Orders();

        $produitStock = $Products->getOrderVendue();
        $result = ['data' => []];
        // echo '
';
        // die(var_dump($produitStock));

        foreach ($produitStock as $key => $value) {
            // die(var_dump($value)); // Debugging: Check what $value contains

            // Add the row data
            $result['data'][$key] = [
                $value['sku'],
                $value['qty'],
                $value['totalNet'],
                (new DateTime($value['DateTime']))->format('Y-m-d'),
                $this->returnName($value['store_id'])
            ];
        }

        // Return data in JSON format
        return $this->response->setJSON($result);
    }

    public function performancedetail()
    {
        $this->verifyRole('viewReports');
        $data['page_title'] = $this->pageTitle;
        $Stores = new Stores();

        // echo '
';
        // die(var_dump($orderTest));
        $data['stores'] = $Stores->getActiveStore();

        return $this->render_template('reports/performance', $data);
    }

    public function fetchPerformances()
    {
        $result = ['data' => []];
        $Orders = new Orders();
        $session = session();
        $users = $session->get('user');
        if ($users['group_name'] === "Conseil" || $users['group_name'] === "Direction" ) {
            $orderPaid = $Orders->getPerformanceByOrders();
            foreach ($orderPaid as $key => $value) {
                $benefice = 
                $result['data'][$key] = [
                    $value['firstname'] . ' ' . $value['lastname'],
                    $value['email'],
                    ($value['sku'] == "" ? $value['motoname'] : $value['sku']),
                    (new DateTime($value['datevente']))->format('Y-m-d'),
                    number_format($value['price'],0,'.',' '),
                    number_format($value['prix_vente'],0,'.',' '),
                    $this->returnName($value['store_id']),
                    number_format($value['prix_vente'] - $value['price'],0,'.',' '),
                ];
            }

            // Return data in JSON format
            return $this->response->setJSON($result);
        }
        if ($users['group_name'] === "Conseil" || $users['group_name'] === "Direction") {
            $orderPaid = $Orders->getPerformanceByOrders1();
            foreach ($orderPaid as $key => $value) {
                $benefice = 
                $result['data'][$key] = [
                    $value['firstname'] . ' ' . $value['lastname'],
                    $value['email'],
                    ($value['sku'] == "" ? $value['motoname'] : $value['sku']),
                    (new DateTime($value['datevente']))->format('Y-m-d'),
                    number_format($value['price'],0,'.',' '),
                    number_format($value['prix_vente'],0,'.',' '),
                    $this->returnName($value['store_id']),
                    number_format($value['prix_vente'] - $value['price'],0,'.',' '),

                ];
            }

            // Return data in JSON format
            return $this->response->setJSON($result);
        }
        if ($users['group_name'] === "COMMERCIALE") {
            $orderPaid = $Orders->getPerformanceByOrders2();
            foreach ($orderPaid as $key => $value) {
                $benefice = 
                $result['data'][$key] = [
                    $value['firstname'] . ' ' . $value['lastname'],
                    ($value['sku'] == "" ? $value['motoname'] : $value['sku']),
                    (new DateTime($value['datevente']))->format('Y-m-d'),
                    number_format($value['prix_vente'],0,'.',' '),
                ];
            }

            // Return data in JSON format
            return $this->response->setJSON($result);
        }

        if ($users['group_name'] === "Cheffe d'Agence") {
            $orderPaid = $Orders->getPerformanceByOrders1();
            foreach ($orderPaid as $key => $value) {
                $benefice = 
                $result['data'][$key] = [
                    $value['firstname'] . ' ' . $value['lastname'],
                    ($value['sku'] == "" ? $value['motoname'] : $value['sku']),
                    (new DateTime($value['datevente']))->format('Y-m-d'),
                    number_format($value['prix_vente'],0,'.',' '),
                ];
            }

            // Return data in JSON format
            return $this->response->setJSON($result);
        }
    }

    public function fetchmecperformance()
    {
        $result = ['data'=> []];
        
    }
}