<?php

namespace App\Controllers;

use App\Models\ProductImage;
use App\Models\Users;
use App\Models\Stores;
use App\Models\Products;

class Auth extends AdminController
{
    /**
     * function who return the view login 
     * @return string
     */
    public function login()
    {
        return view('login');
    }

    private function uploadImage($file)
    {
        // Define the upload directory
        $uploadPath = 'assets/images/product_image';

        // Ensure the directory exists
        if (!is_dir($uploadPath)) {
            mkdir($uploadPath, 0777, true);
        }


        // Check if the file is uploaded via the form
        // $file = $this->request->getFile('images');
        if ($file && $file->isValid() && !$file->hasMoved()) {
            // Generate a unique file name
            $newName = uniqid() . '.' . $file->getExtension();

            // Move the file to the target directory
            $file->move($uploadPath, $newName);

            // Return the actual file name
            return $newName;
        }

        // If an error occurs, return the error message
        return $file ? $file->getErrorString() : 'No file was uploaded.';
    }

/**
 * function used to login
 * @return \CodeIgniter\HTTP\RedirectResponse
 */
public function loginPost()
{
    $email = $this->request->getPost('email');
    $password = $this->request->getPost('password');

    // Load the model and attempt login
    $userModel = new Users();
    $user = $userModel->attempt($email, $password);

    if ($user) {
        // Ajouter le nom complet et le rôle dans le tableau $user
        $user['username'] = trim(($user['firstname'] ?? '') . ' ' . ($user['lastname'] ?? ''));
        $user['role'] = $user['group_name'] ?? 'Aucun groupe';
        
        // Set user session (garde la structure originale qui fonctionne)
        session()->set('user', $user);
        
        // Ajouter aussi les clés individuelles pour le header
        session()->set([
            'user_id' => $user['id'],
            'username' => $user['username'],
            'role' => $user['role'],
            'email' => $user['email'] ?? '',
            'group_id' => $user['group_id'] ?? null,
            'store_id' => $user['store_id'] ?? null,
            'permission' => $user['permission'] ?? '',
            'logged_in' => true
        ]);

        // Redirect to dashboard
        return redirect()->to('/');
    }

    // If login fails, redirect back with an error
    return redirect()->to('/login')->with('error', 'Invalid email or password.');
}
    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login');
    }

    public function ventes()
    {
        $this->verifyRole('viewCom');
        $data['page_title'] = "Espace commercial";

        $session = session();
        $user_id = $session->get('user');
        $data['id'] = $user_id['store_id'];
        // die(var_dump($user_id['store_id']));


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

    public function fetchProductVente(int $id)
    {
        // Initialize the response array
        $result = ['data' => []];
        $Products = new Products();

        // Fetch product data from the model
        $data = $Products->getProductDataStore($id); // Ensure this method exists in your ProductModel

        foreach ($data as $key => $value) {

            // Construct buttons
            $buttons = '';

            if (in_array('viewCom', $this->permission)) {
                $buttons .= " <a href='/ventes/show/" . $value['id'] . "' class='btn btn-default'><i class='fa fa-eye'></i></a>";
            }

            if (is_array($this->permission) && in_array('createOrder', $this->permission)) {
                $buttons .= ($value['qty'] == 1)
                    ? " <a href='/orders/createFromEspace/" . $value['id'] . "' class='btn btn-default'><i class='fa fa-shopping-cart'></i></a>"
                    : " <button class='btn btn-default' title='0 en stock'><i class='fa fa-shopping-cart'></i></button>";
            }

            // Image HTML
            
            $img = '<img src="' . base_url('assets/images/product_image/' . $value['image']) . '" alt="' . $value['image'] . '" class="img-circle" width="50" height="50" />';
            
            // Populate the result data
            $result['data'][] = [
                $img,
                $value['sku'],
                $value['name'],
                number_format($value['prix_vente'], 0, ',', ' '),
                $value['puissance'] . ' CC',
                $value['numero_de_moteur'],
                $buttons
            ];
        }

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

    public function addImage(int $id)
    {
        $this->verifyRole('updateProduct');
        $data['page_title'] = "Espace commercial";
        $Products = new Products();
        $ProductImage = new ProductImage();

        $data['products'] = $Products->getProductData($id);
        $data['galleries'] = $ProductImage->getAll($id);

        return $this->render_template('commercial/addImage', $data);
    }

    public function uploadImagePub($id)
    {
        $this->verifyRole('updateProduct');
        // die(var_dump($this->request->getFiles()));
        $files = $this->request->getFiles();
        $ProductImage = new ProductImage();
        $isTrue = false;
        for ($i = 0; $i < count($files['images']); $i++) {
            $imageName = $this->uploadImage($files['images'][$i]);
            $data = [
                'product_id' => $id,
                'images' => $imageName
            ];

            if ($ProductImage->create($data)) {
                $isTrue = true;
            } else {
                $isTrue = false;
            }
        }

        if ($isTrue) {
            session()->setFlashdata('success', 'Mise à jour réusit');
            return redirect()->to('/products');
        } else {
            session()->setFlashdata('errors', 'Error occurred while creating the product');
            return redirect()->to('ventes/' . $id);
        }
    }

    public function delete(int $id)
    {
        $this->verifyRole('updateProduct');
        $ProductImage = new ProductImage();
        if ($id) {
            $result = $ProductImage->deleteOne($id);

            if ($result) {
                return redirect()->back();
            }
        }
    }

    public function getSingle(int $id)
    {
        $data['page_title'] = "Espace commercial";
        $Products = new Products();
        $ProductImage = new ProductImage();
        $Stores = new Stores();

        $data['products'] = $Products->getProductData($id);
        $data['stores'] = '';
        $data['galleries'] = $ProductImage->getAll($id);
        $allStores = $Stores->getActiveStore();

        for ($i = 0; $i < count($allStores); $i++) {
            if ($allStores[$i]['id'] == $data['products']['store_id']) {
                $data['stores'] = $allStores[$i]['name'];
            }
        }

        return $this->render_template('commercial/single', $data);
    }
}
