<?php

namespace App\Controllers;

use App\Models\Securite;
use App\Models\Products;
use App\Models\Orders;
use App\Models\Stores;

class SecuriteController extends AdminController
{
    public function __construct()
    {
        parent::__construct();   
        helper(['form', 'url']);
    }

    private $pageTitle = 'Validation sortie motos';

    public function index() // ou validateSecurite() ou autre nom
    {
        $this->verifyRole('viewSecurite'); // ou autre permission
        
        $session = session();
        $user = $session->get('user');
        
        $data['page_title'] = 'Validation Sécurité';
        $data['user_role'] = $user['group_name']; // ✅ AJOUTER CETTE LIGNE
        $data['user_permission'] = $this->permission;
        
        // ✅ RÉCUPÉRER LES MAGASINS
        $storeModel = new \App\Models\Stores();
        $data['stores'] = $storeModel->getActiveStore();
        
        return $this->render_template('securite/index', $data);
    }
    public function fetchSecuriteData()
    {
        $securiteModel = new Securite();
        $Products      = new Products();
        $securites     = $securiteModel->getAllSecuriteData();
        $result        = ['data' => []];

        foreach ($securites as $securite) {
            if ($securite['status'] === 'PENDING') {
                $product = $Products->getProductData($securite['product_id']);
                if (! $product) continue;

                // Bouton d’action
                $buttons = in_array('validateCommande1', $this->permission)
                    ? '<button type="button" class="btn btn-success" onclick="editFunc(' . $securite['id'] . ')" data-toggle="modal" data-target="#editModal"><i class="fa fa-check"></i></button>'
                    : '';

                // Statut
                $statut = '<span class="label label-warning">EN ATTENTE DE VALIDATION</span>';

                // Image
                $img = '<img src="' . base_url('assets/images/product_image/' . $product['image']) . '" '
                     . 'alt="' . esc($product['name']) . '" class="img-circle" width="50" height="50" />';

                     $result['data'][] = [
                        'image'       => $img,
                        'ugs'         => esc($product['sku']),
                        'designation' => esc($product['name']),
                        'statut'      => $statut,
                        'action'      => $buttons
                      ];
                      
            }
        }

        return $this->response->setJSON($result);
    }

    public function fetchSecuriteDataById($id) 
    {
        
        if ($id) {
            $Securite = new Securite();
            $Orders    = new Orders();
            $Products  = new Products();

            $data        = $Securite->getSecuriteData($id);
            $order_data  = $Orders->getOrdersDataByBillNo($data['bill_no']);
            $product     = $Products->getProductData($data['product_id']);

            $response = [
                'image'          => base_url('assets/images/product_image/' . $product['image']),
                'nom'            => $product['name'],
                'ugs'            => $product['sku'],
                'bill_no'        => $data['bill_no'],
                'customer_name'  => $order_data['customer_name'],
                'customer_address' => $order_data['customer_address'],
                'customer_phone' => $order_data['customer_phone'],
                'customer_cin'   => $order_data['customer_cin'],
            ];

            return $this->response->setJSON($response);
        }
    }

    public function update(int $id)
    {
        $this->verifyRole('updateCommande1');
        $storeModel = new Securite();
        $post       = $this->request->getPost();
        $response   = [];

        if ($id && isset($post['status'])) {
            $data = [
                'status' => $post['status'],
                'active' => 0
            ];
            $session = session();
            $users = $session->get('user');
            $Notification =  new NotificationController();
            if ($storeModel->updateSecurite($data, $id)) {
                if ($post['status'] === "Validé") {
                    $Notification->createNotification('Une commande a été validé', "COMMERCIALE",(int)$users['store_id'], 'orders');
                }
                 $response = ['success' => true,  'messages' => 'Mise à jour réussie'];
            } else {
                $response = ['success' => false, 'messages' => 'Erreur en base lors de la mise à jour'];
            }
        } else {
            $response = ['success' => false, 'messages' => 'ID ou statut manquant'];
        }

        return $this->response->setJSON($response);
    }



    public function remove()
    {
        $this->verifyRole('deleteCommande1');
        $response = [];

        $storeId = $this->request->getPost('store_id');

        if ($storeId) {
            $storeModel = new Stores();

            if ($storeModel->delete($storeId)) {
                $response['success'] = true;
				$response['messages'] = "Supprimé avec succès";	
            } else {
                $response['success'] = false;
				$response['messages'] = "Erreur dans la base de données lors de la suppression des informations sur la marque";
            }
            
        } else {
            $response['success'] = false;
			$response['messages'] = "Référez à nouveau la page !!";
        }

        return $this->response->setJSON($response);
    }
}