<?php

namespace App\Controllers;

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

class MecanicienController extends AdminController
{
    public function __construct()
    {
        parent::__construct();
    }

    private $pageTitle = 'Mécanicien';

    public function index()
    {
        $data['page_title'] = $this->pageTitle;

        $session = session();
        $user_id = $session->get('user');
        $data['id'] = $user_id['id'];
        $data['user_role'] = $user_id['group_name'];
        
        $Products = new Products();
        $Users = new Users();
        $Stores = new Stores();

        $data['moto'] = $Products->getActiveProductData();
        $data['users'] = $Users->getUsers();
        $data['stores'] = $Stores->getActiveStore();

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

    public function fetchmecanicienSingle($id)
    {
        if ($id) {
            $Mecanicien = new Mecanicien();
            $data = $Mecanicien->getReparationSingle($id);
            echo json_encode($data);
        }
    }

    /**
     * ✅ MODIFIÉ : Utilise mecanic_id au lieu de store_id
     */
    public function fetchMecanicien()
    {
        $Mecanicien = new Mecanicien();
        $session = session();
        $user_id = $session->get('user');
        
        // ✅ RÉCUPÉRER LES PARAMÈTRES DE FILTRE
        $startDate = $this->request->getGet('startDate');
        $endDate = $this->request->getGet('endDate');
        $mecanicId = $this->request->getGet('mecanic_id'); // ✅ CHANGÉ: store_id → mecanic_id
        
        log_message('debug', '=== FILTRES RÉPARATIONS ===');
        log_message('debug', 'startDate: ' . ($startDate ?? 'vide'));
        log_message('debug', 'endDate: ' . ($endDate ?? 'vide'));
        log_message('debug', 'mecanic_id: ' . ($mecanicId ?? 'vide'));
        
        $data['id'] = $user_id['id'];
        
        // ✅ UTILISER LA MÉTHODE AVEC FILTRES (mecanicId au lieu de storeId)
        $reparation = $Mecanicien->getReparationWithFilters($data['id'], $startDate, $endDate, $mecanicId);
        
        $result = ['data' => []];
    
        foreach ($reparation as $key => $repa) {
            $buttons = '';
            
            if (in_array('updateMecanicien', $this->permission)) {
                $buttons .= '<button type="button" class="btn btn-default" onclick="editFunc(' . $repa['reparationsID'] . ')" data-toggle="modal" data-target="#editModal"><i class="fa fa-pencil"></i></button>';
            }
    
            if (in_array('deleteMecanicien', $this->permission)) {
                $buttons .= ' <button type="button" class="btn btn-default" onclick="removeFunc(' . $repa['reparationsID'] . ')" data-toggle="modal" data-target="#removeModal"><i class="fa fa-trash"></i></button>';
            }
    
            $image = '<img src="' . base_url('assets/images/products/' . $repa['image']) . '" alt="' . $repa['name'] . '" class="img-circle" width="50" height="50" />';
            $produit = $repa['name'] . ' (' . $repa['sku'] . ')';
            
            $status = '';
            if ($repa['reparation_statut'] == 1) {
                $status = '<span class="label label-warning">En cours</span>';
            } elseif ($repa['reparation_statut'] == 2) {
                $status = '<span class="label label-success">Réparer</span>';
            } else {
                $status = '<span class="label label-danger">Non réparer</span>';
            }
            
            $username = $repa['firstname'] . ' ' . $repa['lastname'];
            $observation = $repa['reparation_observation'];
            $date_debut = date("d/m/Y", strtotime($repa['reparation_debut']));
            $date_fin = date("d/m/Y", strtotime($repa['reparation_fin']));
            
            $storeName = $repa['store_name'] ?? 'N/A';
            
            $result['data'][$key] = [
                $image,
                $produit,
                $username,       // Index 2 - Mécanicien
                $storeName,      // Index 3 - Magasin
                $status,         // Index 4 - Statut (utilisé pour les stats)
                $observation,
                $date_debut,
                $date_fin,
                $buttons
            ];
        }
    
        log_message('debug', '📊 Nombre de réparations trouvées: ' . count($result['data']));
    
        return $this->response->setJSON($result);
    }

    public function create()
    {
        $this->verifyRole('createMecanicien');
        $response = [];
        $data = [];
    
        $validation = \Config\Services::validation();
        $validation->setRules([
            'motos' => 'required',
            'mecano' => 'required',
            'statut' => 'required',
            'observation' => 'required',
            'date_debut' => 'required',
            'date_fin' => 'required',
        ]);
    
        $validationData = [
            'motos' => $this->request->getPost('motos'),
            'mecano' => $this->request->getPost('mecano'),
            'statut' => $this->request->getPost('statut'),
            'observation' => $this->request->getPost('observation'),
            'date_debut' => $this->request->getPost('date_debut'),
            'date_fin' => $this->request->getPost('date_fin'),
        ];
    
        if ($validation->run($validationData)) {
            $productModel = new \App\Models\Products();
            $product = $productModel->find($this->request->getPost('motos'));
            $storeId = $product['store_id'] ?? null;
            
            $data = [
                'user_id' => $this->request->getPost('mecano'),
                'produit_id' => $this->request->getPost('motos'),
                'reparation_observation' => $this->request->getPost('observation'),
                'reparation_statut' => $this->request->getPost('statut'),
                'reparation_debut' => $this->request->getPost('date_debut'),
                'reparation_fin' => $this->request->getPost('date_fin'),
                'store_id' => $storeId,
            ];
    
            $Mecanicien = new Mecanicien();
            if ($Mecanicien->createRepation($data)) {
                $response['success'] = true;
                $response['messages'] = 'Créé avec succès';
            } else {
                $response['success'] = false;
                $response['messages'] = 'Erreur de base de données';
            }
        } else {
            $response['success'] = false;
            $response['messages'] = $validation->getErrors();
        }
    
        return $this->response->setJSON($response);
    }

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

        $reparation_id = $this->request->getPost('reparation_id');

        if ($reparation_id) {
            $Mecanicien = new Mecanicien();

            if ($Mecanicien->delete($reparation_id)) {
                $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";
            }
        } else {
            $response['success'] = false;
            $response['messages'] = "Référez à nouveau la page !!";
        }

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

    public function update(int $id)
    {
        $this->verifyRole('updateMecanicien');
        $response = [];
    
        if ($id) {
            $validation = \Config\Services::validation();
    
            $validation->setRules([
                'motos' => 'required',
                'mecano' => 'required',
                'statut' => 'required',
                'observation' => 'required',
                'date_debut' => 'required',
                'date_fin' => 'required',
            ]);
    
            $validationData = [
                'motos' => $this->request->getPost('motos'),
                'mecano' => $this->request->getPost('mecano'),
                'statut' => $this->request->getPost('statut'),
                'observation' => $this->request->getPost('observation'),
                'date_debut' => $this->request->getPost('date_debut'),
                'date_fin' => $this->request->getPost('date_fin'),
            ];
    
            $Mecanicien = new Mecanicien();
            
            if ($validation->run($validationData)) {
                $productModel = new \App\Models\Products();
                $product = $productModel->find($this->request->getPost('motos'));
                $storeId = $product['store_id'] ?? null;
                
                $data = [
                    'user_id' => $this->request->getPost('mecano'),
                    'produit_id' => $this->request->getPost('motos'),
                    'reparation_statut' => (int) $this->request->getPost('statut'),
                    'reparation_observation' => $this->request->getPost('observation'),
                    'reparation_debut' => $this->request->getPost('date_debut'),
                    'reparation_fin' => $this->request->getPost('date_fin'),
                    'store_id' => $storeId,
                ];
    
                if ($Mecanicien->updateReparation($data, $id)) {
                    $response['success'] = true;
                    $response['messages'] = 'Mise à jour réussie';
                } else {
                    $response['success'] = false;
                    $response['messages'] = 'Erreur dans la base de données';
                }
            } else {
                $response['success'] = false;
                $response['messages'] = $validation->getErrors();
            }
        } else {
            $response['success'] = false;
            $response['messages'] = 'Erreur, veuillez actualiser la page à nouveau !!';
        }
    
        return $this->response->setJSON($response);
    }

    /**
     * ✅ MODIFIÉ : Utilise mecanic_id au lieu de pvente
     */
    public function fetchMecanicienPerformances()
    {
        $Mecanicien = new Mecanicien();
        $session = session();
        $users = $session->get('user');
        
        // ✅ RÉCUPÉRER LES PARAMÈTRES DE FILTRE
        $startDate = $this->request->getGet('startDate');
        $endDate = $this->request->getGet('endDate');
        $mecanicId = $this->request->getGet('mecanic_id'); // ✅ CHANGÉ: pvente → mecanic_id
        
        log_message('debug', '=== FILTRES PERFORMANCES MÉCANICIEN ===');
        log_message('debug', 'startDate: ' . ($startDate ?? 'vide'));
        log_message('debug', 'endDate: ' . ($endDate ?? 'vide'));
        log_message('debug', 'mecanic_id: ' . ($mecanicId ?? 'vide'));
        
        $data['id'] = $users['id'];
        
        // ✅ PASSER LES FILTRES AU MODÈLE (mecanicId au lieu de pvente)
        $reparation = $Mecanicien->getReparationWithFilters($data['id'], $startDate, $endDate, $mecanicId);
        
        $result = ['data' => []];
    
        if($users['group_name'] == "SuperAdmin" || $users['group_name'] == "Direction" || $users['group_name'] == "DAF"){
            foreach ($reparation as $key => $repa) {
                $image = '<img src="' . base_url('assets/images/products/' . $repa['image']) . '" alt="' . $repa['name'] . '" class="img-circle" width="50" height="50" />';
                $produit = esc($repa['name']);
                $first_name = esc($repa['firstname']);
                $last_name = esc($repa['lastname']);
                $user_name = $first_name . ' ' . $last_name;
                $date_debut = date("d/m/Y", strtotime($repa['reparation_debut']));
                $date_fin = date("d/m/Y", strtotime($repa['reparation_fin']));
                $storeName = $repa['store_name'] ?? 'N/A';
                
                $result['data'][$key] = [
                    $user_name,
                    $image,
                    $produit,
                    $repa['sku'],
                    $storeName,
                    $date_debut,
                    $date_fin,
                ];
            }
        } else {
            foreach ($reparation as $key => $repa) {
                $image = '<img src="' . base_url('assets/images/products/' . $repa['image']) . '" alt="' . $repa['name'] . '" class="img-circle" width="50" height="50" />';
                $produit = $repa['name'];
                $username = $repa['username'];
                $date_debut = date("d/m/Y", strtotime($repa['reparation_debut']));
                $date_fin = date("d/m/Y", strtotime($repa['reparation_fin']));
                $storeName = $repa['store_name'] ?? 'N/A';
                
                $result['data'][$key] = [
                    $image,
                    $produit,
                    $repa['sku'],
                    $storeName,
                    $date_debut,
                    $date_fin,
                ];
            }
        }
        
        log_message('debug', '📊 Nombre de réparations (performances) trouvées: ' . count($result['data']));
    
        return $this->response->setJSON($result);
    }
}