verifyRole('viewOrder'); $data['page_title'] = $this->pageTitle; return $this->render_template('orders/index', $data); } public function fetchOrdersData() { // Load the required helpers helper(['url', 'form']); $Orders = new Orders(); $result = ['data' => []]; // Fetch orders data from the model $data = $Orders->getOrdersData(); $session = session(); $users = $session->get('user'); if($users['group_name'] == "Caissière"){ foreach ($data as $key => $value) { // $count_total_item = $Orders->countOrderItem($value['id']); $date_time = date('d-m-Y h:i a', strtotime($value['date_time'])); // Combine date and time formatting // Initialize buttons $buttons = ''; if (in_array('viewOrder', $this->permission)) { $buttons .= ''; } if (in_array('viewOrder', $this->permission)) { $buttons .= ' '; } if (in_array('updateOrder', $this->permission) && $users["store_id"] == $value['store_id']) { $buttons .= ' '; } // Paid status label $paid_status = ($value['paid_status'] == 1) ? 'Payé' : 'Non payé'; $date1 = new DateTime($date_time); $date2 = new DateTime(); // Current date and time // Calculate the difference in days $interval = $date1->diff($date2); $daysPassed = $interval->days; $statuDate = ''; // die(var_dump($daysPassed)); $Notification = new NotificationController(); // die(var_dump($_SERVER['REQUEST_URI'] == "/orders/fetchOrdersData")); $uri = $_SERVER['REQUEST_URI']; if ($daysPassed < 8 && $value['paid_status'] == 2) { $statuDate = ' depuis ' . $daysPassed . ' Jours'; } else if ($daysPassed >= 8 && $value['paid_status'] == 2) { $Notification->createNotification("Conseil : Confirmation de reservation", "TOUS", (int)$value['store_id'], str_contains($uri, "fetchOrdersData") ? 'orders/#' : 'orders'); $statuDate = ' depuis ' . $daysPassed . ' Jours'; } else if ($daysPassed >= 15 && $value['paid_status'] == 2) { $Notification->createNotification("Conseil : Reservation expiré", "TOUS", (int)$value['store_id'], str_contains($uri, "fetchOrdersData") ? 'orders/#' : 'orders'); $statuDate = ' depuis ' . $daysPassed . ' Jours'; } $Orders_items= new OrderItems(); $sum_order_item = $Orders_items->getSumOrdersItemData($value['id']); // Add data to the result array $result['data'][$key] = [ $value['product_names'], $value['user_name'], $date_time . "
" . $statuDate, $sum_order_item, number_format((int) $value['net_amount'], 0, ',', ' '), $paid_status, $buttons ]; } return $this->response->setJSON($result); } else if($users['group_name'] == "Direction" || $users['group_name'] == "Conseil"){ foreach ($data as $key => $value) { // $count_total_item = $Orders->countOrderItem($value['id']); $date_time = date('d-m-Y h:i a', strtotime($value['date_time'])); // Combine date and time formatting // Initialize buttons $buttons = ''; if (in_array('viewOrder', $this->permission)) { $buttons .= ''; } if (in_array('updateOrder', $this->permission)) { $buttons .= ' '; } if (in_array('deleteOrder', $this->permission)) { $buttons .= ' '; } // Paid status label $paid_status = ($value['paid_status'] == 1) ? 'Payé' : 'Non payé'; $date1 = new DateTime($date_time); $date2 = new DateTime(); // Current date and time // Calculate the difference in days $interval = $date1->diff($date2); $daysPassed = $interval->days; $statuDate = ''; // die(var_dump($daysPassed)); $Notification = new NotificationController(); // die(var_dump($_SERVER['REQUEST_URI'] == "/orders/fetchOrdersData")); $uri = $_SERVER['REQUEST_URI']; if ($daysPassed < 8 && $value['paid_status'] == 2) { $statuDate = ' depuis ' . $daysPassed . ' Jours'; } else if ($daysPassed >= 8 && $value['paid_status'] == 2) { $Notification->createNotification("Conseil : Confirmation de reservation", "TOUS", (int)$value['store_id'], str_contains($uri, "fetchOrdersData") ? 'orders/#' : 'orders'); $statuDate = ' depuis ' . $daysPassed . ' Jours'; } else if ($daysPassed >= 15 && $value['paid_status'] == 2) { $Notification->createNotification("Conseil : Reservation expiré", "TOUS", (int)$value['store_id'], str_contains($uri, "fetchOrdersData") ? 'orders/#' : 'orders'); $statuDate = ' depuis ' . $daysPassed . ' Jours'; } $Orders_items= new OrderItems(); $sum_order_item = $Orders_items->getSumOrdersItemData($value['id']); // Add data to the result array $result['data'][$key] = [ $value['bill_no'], $value['customer_name'], $value['customer_phone'], $date_time . "
" . $statuDate, $sum_order_item, number_format((int) $value['net_amount'], 0, ',', ' '), $paid_status, $buttons ]; } return $this->response->setJSON($result); } else { if($users['group_name'] !== "Direction" || $users['group_name'] !== "Conseil"){ foreach ($data as $key => $value) { // $count_total_item = $Orders->countOrderItem($value['id']); $date_time = date('d-m-Y h:i a', strtotime($value['date_time'])); // Combine date and time formatting // Initialize buttons $buttons = ''; if (in_array('viewOrder', $this->permission)) { $buttons .= ''; } if (in_array('updateOrder', $this->permission) && $users["id"] == $value['user_id']) { $buttons .= ' '; } if (in_array('viewOrder', $this->permission)) { $buttons .= ' '; } if (in_array('deleteOrder', $this->permission) && $users["id"] == $value['user_id']) { $buttons .= ' '; } // Paid status label $paid_status = ($value['paid_status'] == 1) ? 'Payé' : 'Non payé'; $date1 = new DateTime($date_time); $date2 = new DateTime(); // Current date and time // Calculate the difference in days $interval = $date1->diff($date2); $daysPassed = $interval->days; $statuDate = ''; // die(var_dump($daysPassed)); $Notification = new NotificationController(); // die(var_dump($_SERVER['REQUEST_URI'] == "/orders/fetchOrdersData")); $uri = $_SERVER['REQUEST_URI']; if ($daysPassed < 8 && $value['paid_status'] == 2) { $statuDate = ' depuis ' . $daysPassed . ' Jours'; } else if ($daysPassed >= 8 && $value['paid_status'] == 2) { $Notification->createNotification("Conseil : Confirmation de reservation", "TOUS", (int)$value['store_id'], str_contains($uri, "fetchOrdersData") ? 'orders/#' : 'orders'); $statuDate = ' depuis ' . $daysPassed . ' Jours'; } else if ($daysPassed >= 15 && $value['paid_status'] == 2) { $Notification->createNotification("Conseil : Reservation expiré", "TOUS", (int)$value['store_id'], str_contains($uri, "fetchOrdersData") ? 'orders/#' : 'orders'); $statuDate = ' depuis ' . $daysPassed . ' Jours'; } $Orders_items= new OrderItems(); $sum_order_item = $Orders_items->getSumOrdersItemData($value['id']); // Add data to the result array $result['data'][$key] = [ $value['product_names'], $value['user_name'], $date_time . "
" . $statuDate, $sum_order_item, number_format((int) $value['net_amount'], 0, ',', ' '), $paid_status, $buttons ]; } return $this->response->setJSON($result); } } // Return JSON response } /** * function who check if the product is null * and create notification about it * @param array $product_id id of the product * @param int $store_id id of the store * @return void */ private function checkProductisNull(array $product_id, $store_id) { $notification = new NotificationController(); $product = new Products(); for ($i = 0; $i < count($product_id); $i++) { $singleProduct = $product->getProductData($product_id[$i]); if ($singleProduct['product_sold'] == true) { $notification->createNotification("Produit en rupture de stock", "Conseil", $store_id, "products"); } } } private function calculGross($request) { $amount = $request; $montant = 0; for ($i = 0; $i < \count($amount); $i++) { $montant += $amount[$i]; } return $montant; } public function create() { $this->verifyRole('createOrder'); $data['page_title'] = $this->pageTitle; // Load validation service $validation = \Config\Services::validation(); // echo '
';
        // die(var_dump($this->request->getPost('product[]')));

        $products = $this->request->getPost('product[]');

        // Then, manually check for uniqueness
        if ($products !== null && (count($products) !== count(array_unique($products)))) {
            return redirect()->back()->withInput()->with('errors', ['product' => 'Chaque produit sélectionné doit être unique.']);
        }

        // Set validation rules
        $validation->setRules([
            'product[]' => 'required'
        ]);
        // echo '
';
        // die(var_dump($this->request->getPost()));

        $validationData = [
            'product[]' => $this->request->getPost('product[]')
        ];

        $Orders = new Orders();
        $Company = new Company();
        $Products = new Products();

        if ($this->request->getMethod() === 'post' && $validation->run($validationData)) {

            $session = session();
            $users = $session->get('user');
            $user_id = $users['id'];
            $bill_no = 'BILPR-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 4));

            // If validation passes

            $data = [
                'bill_no' => $bill_no,
                'customer_name' => $this->request->getPost('customer_name'),
                'customer_address' => $this->request->getPost('customer_address'),
                'customer_phone' => $this->request->getPost('customer_phone'),
                'customer_cin' => $this->request->getPost('customer_cin'),
                'date_time' => date('Y-m-d H:i:s'),
                'service_charge_rate' => $this->request->getPost('service_charge_rate'),
                'vat_charge_rate' => $this->request->getPost('vat_charge_rate'),
                'vat_charge' => ($this->request->getPost('vat_charge_value') > 0) ? $this->request->getPost('vat_charge_value') : 0,
                'net_amount' => $this->request->getPost('net_amount'),
                'discount' => $this->request->getPost('discount'),
                'paid_status' => 2,
                'user_id' => $user_id,
                // 'qty' => $this->request->getPost('qty[]'),
                'amount_value' => $this->request->getPost('amount_value[]'),
                'gross_amount' => $this->calculGross($this->request->getPost('amount_value[]')),
                'rate_value' => $this->request->getPost('rate_value[]'),
                'store_id' => $users['store_id'],
            ];

            $posts = $this->request->getPost('product[]');

            // echo '
';
            // die(var_dump($data));
            $order_id = $Orders->create($data, $posts);
            $Order_item1 = new OrderItems();
            $order_item_data = $Order_item1->getOrdersItemData($order_id);
            $product_ids = array_column($order_item_data, 'product_id');

            $Notification = new NotificationController();

            if ((int) (int) $this->request->getPost('discount') > 0) {
                $productData = new Products();
                $product_data_results = [];

                foreach ($product_ids as $prod_id) {

                    $id = (int) $prod_id;

                    // Appel de la méthode pour chaque ID
                    $product_data_results[] = $productData->getProductData($id);
                }

                $product_lines = [];

                foreach ($product_data_results as $product) {
                    if (isset($product['sku'], $product['price'])) {
                        $sku = $product['sku'];
                        $price = $product['price'];
                        $product_lines[] = "{$sku}:{$price}";
                    }
                }

                $product_output = implode("\n", $product_lines);


                // data for the remise
                $data1 = [
                    'date_demande' => date('Y-m-d H:i:s'),
                    'montant_demande' => $this->request->getPost('discount'),
                    'total_price' => $this->request->getPost('amount_value[]'),
                    'id_store' => $users['store_id'],
                    'id_order' => $order_id,
                    'product' => $product_output,
                    'demande_status' => 'En attente'
                ];

                $Remise = new Remise();
                $id_remise = $Remise->addDemande($data1);
                $Notification->createNotification("Un nouveau demande de remise été ajouté", "Conseil", (int)$users['store_id'], 'remise');
            }

            if ($order_id) {
                session()->setFlashdata('success', 'Créé avec succès');
                $Notification->createNotification("Un nouveau commade ajouter", "Caissière", (int)$users['store_id'], "orders");
                if ($users["group_name"] != "COMMERCIALE") {

                    $this->checkProductisNull($posts, $users['store_id']);

                    return redirect()->to('orders/update/' . $order_id);
                } else {

                    return redirect()->to('orders/');
                }
            } else {
                session()->setFlashdata('errors', 'Error occurred!!');
                return redirect()->to('orders/create/');
            }
        } else {
            // If validation fails
            $company = $Company->getCompanyData(1);

            $session = session();
            $users = $session->get('user');
            $store_id = $users['store_id'];
            // Prepare data for the view
            $data = [
                'company_data' => $company,
                'is_vat_enabled' => ($company['vat_charge_value'] > 0),
                'is_service_enabled' => ($company['service_charge_value'] > 0),
                'products' => $Products->getProductData2($store_id),
                'validation' => $validation,
                'page_title' => $this->pageTitle,
            ];

            // Render the view with the prepared data
            return $this->render_template('orders/create', $data);
        }
    }

    public function getProductValueById()
    {
        $product_id = $this->request->getPost('product_id');
        if ($product_id) {
            $Products = new Products();
            $product_data = $Products->getProductData($product_id);
            return $this->response->setJSON($product_data);
        }
    }

    public function getTableProductRow()
    {
        $Products = new Products();
        $session = session();
        $users = $session->get('user');
        $store_id = $users['store_id'];

        $product_data = $Products->getProductData2($store_id);
        die(var_dump($product_data));
        return $this->response->setJSON($product_data);
    }


    public function update(int $id)
    {
        $this->verifyRole('updateOrder');
    
        $data['page_title'] = $this->pageTitle;
        $validation = \Config\Services::validation();
    
        // Définir les règles de validation
        $validation->setRules([
            'product' => 'required'
        ]);
    
        $validationData = [
            'product' => $this->request->getPost('product')
        ];
    
        $Orders = new Orders();
        $Company = new Company();
        $Products = new Products();
        $OrderItems = new OrderItems();
    
        if ($this->request->getMethod() === 'post' && $validation->run($validationData)) {
            $dataUpdate = [
                'customer_name' => $this->request->getPost('customer_name'),
                'customer_address' => $this->request->getPost('customer_address'),
                'customer_phone' => $this->request->getPost('customer_phone'),
                'customer_cin' => $this->request->getPost('customer_cin'),
                'gross_amount' => $this->request->getPost('gross_amount_value'),
                'service_charge_rate' => $this->request->getPost('service_charge_rate'),
                'service_charge' => max(0, (float)$this->request->getPost('service_charge_value')),
                'vat_charge_rate' => $this->request->getPost('vat_charge_rate'),
                'vat_charge' => max(0, (float)$this->request->getPost('vat_charge_value')),
                'net_amount' => $this->request->getPost('net_amount_value'),
                'discount' => $this->request->getPost('discount'),
                'paid_status' => $this->request->getPost('paid_status'),
                'product' => $this->request->getPost('product'),
                'product_sold' => true,
                'rate_value' => $this->request->getPost('rate_value'),
                'amount_value' => $this->request->getPost('amount_value'),
                'tranche_1' => $this->request->getPost('tranche_1'),
                'tranche_2' => $this->request->getPost('tranche_2'),
                'order_payment_mode' => $this->request->getPost('order_payment_mode_1'),
                'order_payment_mode_1' => $this->request->getPost('order_payment_mode_2')
            ];
    
            if ($Orders->updates($id, $dataUpdate)) {
                $order_item_data = $OrderItems->getOrdersItemData($id);
                $product_ids = array_column($order_item_data, 'product_id');
    
                $Notification = new NotificationController();
    
                $discount = (int) $this->request->getPost('discount');
    
                if ($discount > 0) {
                    $productData = new Products();
                    $product_data_results = [];
    
                    foreach ($product_ids as $product_id) {
                        $product_data_results[] = $productData->getProductData((int) $product_id);
                    }
    
                    $product_lines = [];
                    foreach ($product_data_results as $product) {
                        if (isset($product['sku'], $product['price'])) {
                            $product_lines[] = "{$product['sku']}:{$product['price']}";
                        }
                    }
    
                    $product_output = implode("\n", $product_lines);
    
                    $session = session();
                    $users = $session->get('user');
                    
                    $data1 = [
                        'date_demande' => date('Y-m-d H:i:s'),
                        'montant_demande' => $this->request->getPost('discount'),
                        'total_price' => $this->request->getPost('amount_value'),
                        'id_store' => $users['store_id'],
                        'id_order' => $id,
                        'product' => $product_output,
                        'demande_status' => 'En attente'
                    ];
    
                    $Remise = new Remise();
                    $Remise->updateRemise1($id,$data1);
                    $Notification->createNotification("Un nouveau demande de remise a été ajouté", "Conseil", (int)$users['store_id'] ?? null, 'remise');
                }
    
                session()->setFlashData('success', 'Commande mise à jour avec succès.');
                return redirect()->to('orders/update/' . $id);
            } else {
                session()->setFlashData('errors', 'Une erreur est survenue lors de la mise à jour.');
                return redirect()->to('orders/update/' . $id);
            }
        }
    
        // En cas d’échec de la validation ou si GET
        $company = $Company->getCompanyData(1);
        $data['company_data'] = $company;
        $data['is_vat_enabled'] = ($company['vat_charge_value'] > 0);
        $data['is_service_enabled'] = ($company['service_charge_value'] > 0);
    
        $orders_data = $Orders->getOrdersData($id);
        $result = ['order' => $orders_data];
        $orders_item = $OrderItems->getOrdersItemData($orders_data['id']);
    
        foreach ($orders_item as $item) {
            $result['order_item'][] = $item;
        }
    
        $data['order_data'] = $result;
        $data['products'] = $Products->getActiveProductData();
        $data['validation'] = $validation;
    
        return $this->render_template('orders/edit', $data);
    }
    
    

    public function lookOrder(int $id)
    {
        $this->verifyRole('viewOrder');
    
        $data['page_title'] = $this->pageTitle;
    
        $Orders = new Orders();
        $Company = new Company();
        $Products = new Products();
        $OrderItems = new OrderItems();
    
        // En cas d’échec de la validation ou si GET
        $company = $Company->getCompanyData(1);
        $data['company_data'] = $company;
        $data['is_vat_enabled'] = ($company['vat_charge_value'] > 0);
        $data['is_service_enabled'] = ($company['service_charge_value'] > 0);
    
        $orders_data = $Orders->getOrdersData($id);
        $sum_order_item = $OrderItems->getSumOrdersItemData($orders_data['id']);
        $result = [
            'order' => $orders_data,
            'sum_order_data' => $sum_order_item
        ];

        $orders_item = $OrderItems->getOrdersItemData($orders_data['id']);
    
        foreach ($orders_item as $item) {
            $result['order_item'][] = $item;
        }
    
        $data['order_data'] = $result;
        $data['products'] = $Products->getActiveProductData();
    
        return $this->response->setJSON($data);

    }

    /**
     * return storename
     * @param int $id
     * @return string
     */
    private function returnStore($id)
    {
        $Stores = new Stores();
        $store = $Stores->getActiveStore();
        $name = "";

        foreach ($store as $key => $value) {
            if ($value['id'] == $id) {
                $name = $value['name'];
            }
        }

        return $name;
    }

    public function print2(int $id)
    {
        $this->verifyRole('viewOrder');

        if ($id) {
            $Orders = new Orders();
            $Company = new Company();
            $Products = new Products();
            $OrderItems = new OrderItems();

            // Récupération des données
            $order_data = $Orders->getOrdersData($id);
            $orders_items = $OrderItems->getOrdersItemData($id);
            $company_info = $Company->getCompanyData(1);
            // die(\var_dump($orders_items));

            $html = '';
            // Vérifier si l'utilisateur a payé
            $paid_status = ($order_data['paid_status'] == 1) ? "Payé" : "Non payé";

            // Génération du HTML
            $html .= '
        
        
            
            
            
            
        
        
            
' . esc($company_info['company_name']) . '

Facture ID : ' . esc($order_data['bill_no']) . '

NIF : ' . esc($company_info['NIF']) . '

STAT : ' . esc($company_info['STAT']) . '

Contact : ' . esc($company_info['phone']) . ' ' . esc($company_info['phone2']) . '

Magasin : ' . esc($this->returnStore($order_data['store_id'])) . '

Nom: ' . esc($order_data['customer_name']) . '

Adresse: ' . esc($order_data['customer_address']) . '

Téléphone: ' . esc($order_data['customer_phone']) . '

CIN: ' . esc($order_data['customer_cin']) . '



Antananarivo le ' . esc(date('d/m/Y')) . '

'; foreach ($orders_items as $item) { $product_data = $Products->getProductData($item['product_id']); $html .= ''; } $html .= '
Marque Moteur Puissance Prix
' . esc($product_data['sku']) . ' ' . esc($product_data['numero_de_moteur']) . ' ' . number_format((float) $item['amount'], 2, '.', ' ') . '
'; $html .= ''; // Vérification et ajout des informations de paiement if (!empty($order_data['order_payment_mode'])) { $html .= ''; } if (!empty($order_data['tranche_1'])) { $html .= ''; } if (!empty($order_data['tranche_2'])) { $html .= ''; } $html .= '
Total: ' . number_format(((float) $order_data['gross_amount'] - ((float) $order_data['gross_amount'] * 0.2)), 2, '.', ' ') . '
TVA: ' . number_format((((float) $order_data['gross_amount'] * 0.2)), 2, '.', ' ') . '
Réduction: ' . number_format((float) $order_data['discount'], 2, '.', ' ') . '
Total à payer: ' . number_format((float) ($order_data['net_amount']), 2, '.', ' ') . '
Statut: ' . $paid_status . '
Mode de paiement: ' . esc($order_data['order_payment_mode']) . '
Tranche 1: ' . number_format((float) $order_data['tranche_1'], 2, '.', ' ') . '
Tranche 2: ' . number_format((float) $order_data['tranche_2'], 2, '.', ' ') . '

L\'acheteur

Le vendeur

'; return $this->response->setBody($html); } } public function print(int $id) { $this->verifyRole('viewOrder'); if ($id) { $Orders = new Orders(); $Company = new Company(); $Products = new Products(); $OrderItems = new OrderItems(); $order_data = $Orders->getOrdersData($id); $orders_items = $OrderItems->getOrdersItemData($id); $company_info = $Company->getCompanyData(1); $paid_status = ($order_data['paid_status'] == 1) ? "Payé" : "Non payé"; foreach ($orders_items as $index => $item) { $product_data = $Products->getProductData($item['product_id']); echo '
' . esc($company_info['company_name']) . '

Facture ID : ' . esc($order_data['bill_no']) . '

NIF : ' . esc($company_info['NIF']) . '

STAT : ' . esc($company_info['STAT']) . '

Contact : ' . esc($company_info['phone']) . ' ' . esc($company_info['phone2']) . '

Magasin : ' . esc($this->returnStore($order_data['store_id'])) . '

Nom: ' . esc($order_data['customer_name']) . '

Adresse: ' . esc($order_data['customer_address']) . '

Téléphone: ' . esc($order_data['customer_phone']) . '

CIN: ' . esc($order_data['customer_cin']) . '



Antananarivo le ' . esc(date('d/m/Y')) . '

Marque Moteur Puissance Prix
' . esc($product_data['sku']) . ' ' . esc($product_data['numero_de_moteur']) . ' ' . number_format((float)$item['amount'], 2, '.', ' ') . '
'; if (!empty($order_data['order_payment_mode'])) { echo ''; } if (!empty($order_data['tranche_1'])) { echo ''; } if (!empty($order_data['tranche_2'])) { echo ''; } echo '
Total: ' . number_format($item['amount'] - ($item['amount'] * 0.2), 2, '.', ' ') . '
TVA: ' . number_format($item['amount'] * 0.2, 2, '.', ' ') . '
Réduction: ' . number_format($order_data['discount'], 2, '.', ' ') . '
Total à payer: ' . number_format($item['amount'] - $order_data['discount'], 2, '.', ' ') . '
Statut: ' . $paid_status . '
Mode de paiement:' . esc($order_data['order_payment_mode']) . '
Tranche 1:' . number_format((float)$order_data['tranche_1'], 2, '.', ' ') . '
Tranche 2:' . number_format((float)$order_data['tranche_2'], 2, '.', ' ') . '

L\'acheteur

Le vendeur

'; } } } public function remove() { $this->verifyRole('deleteOrder'); $order_id = $this->request->getPost('order_id'); $response = []; if ($order_id) { $Orders = new Orders(); if ($Orders->remove($order_id)) { $response['success'] = true; $response['messages'] = "Successfully removed"; } else { $response['success'] = false; $response['messages'] = "Error in the database while removing the product information"; } } else { $response['success'] = false; $response['messages'] = "Refersh the page again!!"; } return $this->response->setJSON($response); } public function createById(int $id) { $this->verifyRole('createOrder'); $data['page_title'] = $this->pageTitle; $Company = new Company(); $Products = new Products(); // If validation fails $company = $Company->getCompanyData(1); // Prepare data for the view $data = [ 'company_data' => $company, 'is_vat_enabled' => ($company['vat_charge_value'] > 0), 'is_service_enabled' => ($company['service_charge_value'] > 0), 'products' => $Products->getProductData($id), 'totalqtt' => $Products->getProductData($id)['qty'], 'pu' => $Products->getProductData($id)['prix_vente'], 'page_title' => $this->pageTitle, ]; return $this->render_template('orders/createbyid', $data); } // update caisse public function update_caisse($data) { $p1 = 0; $p2 = 0; $op = ""; $p3 = 0; $dest = ""; if ($data['tranche2']) { if ($data['order']) { # code... } } } public function print3(int $id) { // Vérification du rôle $this->verifyRole('viewOrder'); if (!$id) { return $this->response->setStatusCode(400, 'ID manquant'); } // Instanciation des modèles $Orders = new Orders(); $Company = new Company(); $OrderItems = new OrderItems(); $Products = new Products(); // Récupération des données $order_data = $Orders->getOrdersData($id); $items = $OrderItems->getOrdersItemData($id); $company_info = $Company->getCompanyData(1); // Statut de paiement $paid_status = $order_data['paid_status'] == 1 ? "Payé" : "Non payé"; // STYLE COMMUN $style = ' '; // --- FACTURES : Une par produit --- foreach ($items as $item) { $product_data = $Products->getProductData($item['product_id']); $unitPrice = (float)$item['amount']; $quantity = isset($item['qty']) ? (int)$item['qty'] : 1; $subtotal = $unitPrice * $quantity; $vatAmount = $subtotal * 0.2; $discount = (float)$order_data['discount']; $totalNet = $subtotal + $vatAmount - $discount; echo ' ' . $style . '
FACTURE

Facture ID : ' . esc($order_data['bill_no']) . '

NIF : ' . esc($company_info['NIF']) . '

STAT : ' . esc($company_info['STAT']) . '

Contact : ' . esc($company_info['phone']) . ' / ' . esc($company_info['phone2']) . '

Magasin : ' . esc($this->returnStore($order_data['store_id'])) . '

Nom: ' . esc($order_data['customer_name']) . '

Adresse: ' . esc($order_data['customer_address']) . '

Téléphone: ' . esc($order_data['customer_phone']) . '

CIN: ' . esc($order_data['customer_cin']) . '

MarqueMoteurPuissancePrix unitaire
' . esc($product_data['sku']) . ' ' . esc($product_data['numero_de_moteur']) . ' ' . esc($product_data['puissance']) . ' ' . number_format($unitPrice, 2, '.', ' ') . '
'; if (!empty($order_data['order_payment_mode'])) { echo ''; } if (!empty($order_data['tranche_1'])) { echo ''; } if (!empty($order_data['tranche_2'])) { echo ''; } echo '
Total:
TVA (20%):
Réduction:
Total à payer:
Statut:
Mode de paiement:
Tranche 1:
Tranche 2:

L\'acheteur

Le vendeur

'; } // --- BON DE COMMANDE : une seule fois après la boucle --- echo ' ' . $style . '
BON DE COMMANDE

Commande ID : ' . esc($order_data['order_no'] ?? $order_data['bill_no']) . '

Magasin : ' . esc($this->returnStore($order_data['store_id'])) . '

Nom: ' . esc($order_data['customer_name']) . '

Adresse: ' . esc($order_data['customer_address']) . '

Téléphone: ' . esc($order_data['customer_phone']) . '

CIN: ' . esc($order_data['customer_cin']) . '

'; $total_ht = 0; foreach ($items as $item) { $product_data = $Products->getProductData($item['product_id']); $total_ht += (float)$item['amount']; echo ''; } $tva = $total_ht * 0.2; $total_ttc = $total_ht + $tva - $order_data['discount']; echo ''; echo '
Marque Moteur Puissance Prix
' . esc($product_data['sku']) . ' ' . esc($product_data['numero_de_moteur']) . ' ' . number_format((float)$item['amount'], 2, '.', ' ') . '
Total:' . number_format($total_ht, 2, '.', ' ') . '
TVA:' . number_format($tva, 2, '.', ' ') . '
Réduction:' . number_format($order_data['discount'], 2, '.', ' ') . '
Total à payer:' . number_format($total_ttc, 2, '.', ' ') . '
'; echo '

L\'acheteur

Le vendeur

'; echo''; echo '
'; echo ''; echo''; } public function print5(int $id) { $this->verifyRole('viewOrder'); if (! $id) { throw new \CodeIgniter\Exceptions\PageNotFoundException(); } // Modèles $Orders = new Orders(); $Company = new Company(); $Products = new Products(); $OrderItems = new OrderItems(); // Récupération des données $order = $Orders->getOrdersData($id); $items = $OrderItems->getOrdersItemData($id); $company = $Company->getCompanyData(1); $today = date('d/m/Y'); // Pré-calculs $totalTTC = (float) $order['gross_amount']; $totalHT = $totalTTC / 1.20; $tva = $totalTTC - $totalHT; $inWords = $this->numberToWords((int) round($totalTTC)); // Statut paiement $paidLabel = $order['paid_status'] == 1 ? 'Payé' : 'Non payé'; // Début du HTML $html = ' Facture '.$order['bill_no'].'

'.esc($company['company_name']).'

NIF : '.esc($company['NIF']).'

STAT : '.esc($company['STAT']).'

Contact : '.esc($company['phone']).' | '.esc($company['phone2']).'

Logo

Facture N° '.esc($order['bill_no']).'

DOIT Nom : '.esc($order['customer_name']).'

Adresse : '.esc($order['customer_address']).'

CIN : '.esc($order['customer_cin']).'

Téléphone : '.esc($order['customer_phone'] ?? '').'

Antananarivo, le '.$today.'

'; foreach ($items as $it) { $p = $Products->getProductData($it['product_id']); $Brand = new Brands(); $Category = new Category(); $html .= ' '; } $html .= '
Nom MARQUE TYPE N° Moteur N° Châssis Puissance (CC) PRIX (Ar)
'.esc($p['name']).' '.esc($Brand->getNameById($p['id'])).' '.esc($Category->getNameById($p['categorie_id'])).' '.esc($p['numero_de_moteur']).' '.esc($p['chasis'] ?? '').' '.esc($p['puissance']).' '.number_format($p['prix_vente'], 0, '', ' ').'
Prix (HT) : '.number_format($totalHT, 0, '', ' ').' Ar
TVA (20%) : '.number_format($tva, 0, '', ' ').' Ar
Total (TTC) : '.number_format($totalTTC, 0, '', ' ').' Ar
Arrêté à la somme de :
'.$inWords.'
L\'Acheteur

__________________
Le Vendeur

__________________

Conditions Générales

Logo
  • Aucun accessoire (casque, rétroviseur, batterie, etc.) n’est inclus avec la moto. Si le client en a besoin, il doit les acheter séparément.
  • Le client doit vérifier soigneusement la marchandise avant de quitter notre établissement.
  • Aucun service après-vente n’est fourni.
  • La moto est vendue sans garantie, car il s’agit d’un modèle d’occasion.
  • La facture étant un document provisoire ne peut se substituer au certificat modèle (si requis) délivré au client au moment de l’achat. Il appartient à ce dernier de procéder à l’immatriculation dans le délai prévu par la loi.
L’Acheteur
'; return $this->response->setBody($html); } /** * Convertit un nombre entier en texte (français, sans décimales). * Usage basique, pour Ariary. */ private function numberToWords(int $num): string { // Cas zéro if ($num === 0) { return 'zéro ariary'; } // Tableaux de base $units = [ '', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf' ]; $tens = [ 2 => 'vingt', 3 => 'trente', 4 => 'quarante', 5 => 'cinquante', 6 => 'soixante', 7 => 'soixante-dix', 8 => 'quatre-vingt', 9 => 'quatre-vingt-dix' ]; // Fonction récursive interne (sans la monnaie) $convert = function(int $n) use (&$convert, $units, $tens): string { if ($n < 20) { return $units[$n]; } if ($n < 100) { $d = intdiv($n, 10); $r = $n % 10; // 70–79 et 90–99 if ($d === 7 || $d === 9) { $base = $d === 7 ? 60 : 80; return $tens[$d] . ($r ? '-' . $units[$n - $base] : ''); } // 20–69 ou 80–89 return $tens[$d] . ($r ? '-' . $units[$r] : ''); } if ($n < 1000) { $h = intdiv($n, 100); $rest = $n % 100; $hundredText = $h > 1 ? $units[$h] . ' cent' : 'cent'; // « deux cents » prend un « s » si pas de reste if ($h > 1 && $rest === 0) { $hundredText .= 's'; } return $hundredText . ($rest ? ' ' . $convert($rest) : ''); } if ($n < 1000000) { $k = intdiv($n, 1000); $rest = $n % 1000; $thousandText = $k > 1 ? $convert($k) . ' mille' : 'mille'; return $thousandText . ($rest ? ' ' . $convert($rest) : ''); } // millions et plus $m = intdiv($n, 1000000); $rest = $n % 1000000; $millionText = $m > 1 ? $convert($m) . ' million' : 'million'; // pas de 's' à million en francais return $millionText . ($rest ? ' ' . $convert($rest) : ''); }; // Construit le texte sans la monnaie, puis ajoute 'ariary' à la fin $words = $convert($num); return trim($words) . ' ariary'; } public function print7(int $id) { $this->verifyRole('viewOrder'); if (! $id) { throw new \CodeIgniter\Exceptions\PageNotFoundException(); } // Modèles $Orders = new Orders(); $Company = new Company(); $Products = new Products(); $OrderItems = new OrderItems(); $Brand = new Brands(); $Category = new Category(); // Récupération des données $order = $Orders->getOrdersData($id); $items = $OrderItems->getOrdersItemData($id); $company = $Company->getCompanyData(1); $today = date('d/m/Y'); // Calculs totaux $totalTTC = (float) $order['net_amount']; $totalHT = $totalTTC / 1.20; $tva = $totalTTC - $totalHT; $paidLabel = $order['paid_status'] == 1 ? 'Payé' : 'Non payé'; // Démarrage du HTML $html = ' Bon de commande '.$order['bill_no'].'

'.esc($company['company_name']).'

NIF : '.esc($company['NIF']).'

STAT : '.esc($company['STAT']).'

Contact : '.esc($company['phone']).' | '.esc($company['phone2']).'

Logo

Bon de commande N° '.esc($order['bill_no']).'

Client : '.esc($order['customer_name']).'

Adresse : '.esc($order['customer_address']).'

Téléphone : '.esc($order['customer_phone']).'

CIN : '.esc($order['customer_cin']).'

Antananarivo, le '.$today.'

'; foreach ($items as $item) { $p = $Products->getProductData($item['product_id']); $html .= ''; } $html .= '
Nom Marque Catégorie N° Moteur Châssis Puissance (CC) Prix Unitaire (Ar)
'.esc($p['name']).' '.esc($Brand->getNameById($p['brand_id'] ?? $p['id'])).' '.esc($Category->getNameById($p['categorie_id'])).' '.esc($p['numero_de_moteur']).' '.esc($p['chasis'] ?? '').' '.esc($p['puissance']).' '.number_format($p['prix_vente'], 0, '', ' ').'
'; if (! empty($order['order_payment_mode'])) { $html .= ''; } $html .= '
Total HT : Ar
TVA (20%) : Ar
Total TTC : Ar
Statut :
Mode de paiement : '.esc($order['order_payment_mode']).'
L\'acheteur

__________________
Le vendeur

__________________

Conditions Générales

Logo
  • Aucun accessoire (casque, rétroviseur, batterie, etc.) n’est inclus avec la moto. Si le client en a besoin, il doit les acheter séparément.
  • Le client doit vérifier soigneusement la marchandise avant de quitter notre établissement.
  • Aucun service après-vente n’est fourni.
  • La moto est vendue sans garantie, car il s’agit d’un modèle d’occasion.
  • La facture étant un document provisoire ne peut se substituer au certificat modèle (si requis) délivré au client au moment de l’achat. Il appartient à ce dernier de procéder à l’immatriculation dans le délai prévu par la loi.
L’Acheteur
'; // Affichage final echo $html; } public function print31(int $id) { // Vérification du rôle $this->verifyRole('viewOrder'); if (! $id) { return $this->response->setStatusCode(400, 'ID manquant'); } // Instanciation des modèles $Orders = new Orders(); $Company = new Company(); $OrderItems = new OrderItems(); $Products = new Products(); $Brand = new Brands(); $Category = new Category(); // Récupération des données $order_data = $Orders->getOrdersData($id); $items = $OrderItems->getOrdersItemData($id); $company_info = $Company->getCompanyData(1); // Statut de paiement $paid_status = $order_data['paid_status'] === 1 ? "Payé" : "Non payé"; // STYLE COMMUN avec page-break-after // --- FACTURES : Une par produit --- foreach ($items as $item) { $p = $Products->getProductData($item['product_id']); $unitPrice = (float) $item['amount']; $quantity = isset($item['qty']) ? (int) $item['qty'] : 1; $subtotal = $unitPrice * $quantity; $vatAmount = $subtotal * 0.2; $discount = (float) $order_data['discount']; $totalNet = $subtotal + $vatAmount - $discount; $inWords = $this->numberToWords((int) round($subtotal)); // Début du document echo ''; echo ''; echo ''; echo ''; echo ""; echo ''; // Wrapper pour nouvelle page echo '
'; // En-tête echo '
'; echo '
'; echo '

' . esc($company_info['company_name']) . '

'; echo '

NIF : ' . esc($company_info['NIF']) . '

'; echo '

STAT : ' . esc($company_info['STAT']) . '

'; echo '

Contact : ' . esc($company_info['phone']) . ' | ' . esc($company_info['phone2']) . '

'; echo '

Magasin : ' . esc($this->returnStore($order_data['store_id'])) . '

'; echo '
'; // infos echo '
'; echo 'Logo'; echo '

Facture N° ' . esc($order_data['bill_no']) . '

'; echo '

Antananarivo, le ' . date('d/m/Y') . '

'; echo '
'; // logo echo '
'; // header // Client echo '
'; echo '

Client : ' . esc($order_data['customer_name']) . '

'; echo '

Adresse : ' . esc($order_data['customer_address']) . '

'; echo '

Téléphone : ' . esc($order_data['customer_phone']) . '

'; echo '

CIN : ' . esc($order_data['customer_cin']) . '

'; echo '
'; // Tableau produits echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo '
NomMarqueCatégorieN° MoteurChâssisPuissance (CC)Prix Unit. (Ar)
' . esc($p['name']) . '' . esc($Brand->getNameById($p['id'])) . '' . esc($Category->getNameById($p['categorie_id'])) . '' . esc($p['numero_de_moteur']) . '' . esc($p['chasis'] ?? '') . '' . esc($p['puissance']) . '' . number_format($p['prix_vente'], 0, '', ' ') . '
'; // Totaux echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo '
Total HT :' . number_format($subtotal, 0, '.', ' ') . ' Ar
TVA (20%) :' . number_format($vatAmount, 0, '.', ' ') . ' Ar
Réduction :' . number_format($discount, 0, '.', ' ') . ' Ar
Total Net :' . number_format($totalNet, 0, '.', ' ') . ' Ar
Statut :' . $paid_status . '
'; echo '
Arrêté à la somme de :
'.$inWords.'
'; // Signature echo '
'; echo '
L'Acheteur

__________________
'; echo '
Le Vendeur

__________________
'; echo '
'; echo '
'; // page-break echo ''; } // --- BON DE COMMANDE : une seule fois après la boucle --- echo ''; echo ''; echo ''; echo ''; echo ""; echo ''; // Wrapper bon de commande echo '
'; echo '
'; echo '
'; echo '

' . esc($company_info['company_name']) . '

'; echo '

Commande ID : ' . esc($order_data['order_no'] ?? $order_data['bill_no']) . '

'; echo '

Magasin : ' . esc($this->returnStore($order_data['store_id'])) . '

'; echo '
'; echo '
'; echo 'Logo'; echo '

Bon de commande N° ' . esc($order_data['order_no'] ?? $order_data['bill_no']) . '

'; echo '

Antananarivo, le ' . date('d/m/Y') . '

'; echo '
'; echo '
'; // header // Corps bon de commande echo '
'; echo '

Client : ' . esc($order_data['customer_name']) . '

'; echo '

Adresse : ' . esc($order_data['customer_address']) . '

'; echo '

Téléphone : ' . esc($order_data['customer_phone']) . '

'; echo '

CIN : ' . esc($order_data['customer_cin']) . '

'; echo '
'; echo ''; echo ''; echo ''; $total_ht = 0; foreach ($items as $item) { $p = $Products->getProductData($item['product_id']); $amount = (float) $item['amount']; $total_ht += $amount; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; } $tva = $total_ht * 0.2; $total_ttc = $total_ht + $tva - (float) $order_data['discount']; echo '
NomMarqueCatégorieN° MoteurChâssisPuissance (CC)Prix Unit. (Ar)
' . esc($p['name']) . '' . esc($Brand->getNameById($p['id'])) . '' . esc($Category->getNameById($p['categorie_id'])) . '' . esc($p['numero_de_moteur']) . '' . esc($p['chasis'] ?? '') . '' . esc($p['puissance']) . '' . number_format($amount, 0, '', ' ') . '
'; echo ''; echo ''; echo ''; echo ''; echo ''; echo '
Total HT :Ar
TVA : Ar
Réduction :Ar
Total TTC : Ar
'; echo '
'; echo '
L\'Acheteur

__________________
'; echo '
Le Vendeur

__________________
'; echo '
'; // --- 3) CONDITIONS GÉNÉRALES (avec rupture AVANT) --- echo '
'; echo '
'; echo '

Conditions Générales

'; echo 'Moto'; echo '
'; echo '

* Aucun accessoire (casque, rétroviseur, batterie, etc.) n\'est inclus avec la moto. ' . 'Si le client en a besoin, il doit les acheter séparément.

'; echo '

* Le client doit s\'assurer de vérifier soigneusement la marchandise avant de quitter notre établissement.

'; echo '

* Aucun service après-vente n\'est fourni.

'; echo '

* La moto est vendue sans garantie, car il s\'agit d\'un modèle d\'occasion.

'; echo '

* La facture étant un document provisoire ne peut se substituer au certificat modèle (si requis) ' . 'délivré au client au moment de l\'achat. Il appartient à ce dernier de procéder à l\'immatriculation ' . 'dans le délai prévu par la loi.

'; echo '
L\'Acheteur
'; echo '
'; echo ''; } }