<?php

namespace App\Controllers;

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

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');
        // if($user_id CONTAINS MECANICIEN)
        // is mecanicien true
        $data['id'] = $user_id['id'];
        $Products = new Products();
        $Users = new Users();

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

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

    public function fetchmecanicienSingle($id)
    {
        // die(var_dump($id));
        if ($id) {
            $Mecanicien = new Mecanicien();

            $data = $Mecanicien->getReparationSingle($id);
            echo json_encode($data);
        }
    }

    public function fetchMecanicien()
    {
        $Mecanicien = new Mecanicien();
        $session = session();
        $user_id = $session->get('user');
        
        $data['id'] = $user_id['id'];
        $reparation = $Mecanicien->getReparation($data['id']);
        $result = ['data' => []];

        function strReparation($repastatus)
        {
            $reparation = '';
            if ($repastatus == 1) {
                $reparation = 'En cours de réparation';
            } else if ($repastatus == 2) {
                $reparation = 'Réparer';
            } else {
                $reparation = 'Non réparer';
            }

            return $reparation;
        }

        // Iterate through the data
        foreach ($reparation as $key => $repa) {
            // Action buttons
            $buttons = '';
            // dd($repa['reparationsID']);
            // Check permissions for updating the store
            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>';
            }

            // Check permissions for deleting the store
            if (in_array('deleteMecanicien', $this->permission)) {
                $buttons .= ' <button type="button" class="btn btn-danger" onclick="removeFunc(' . $repa['reparationsID'] . ')" data-toggle="modal" data-target="#removeModal"><i class="fa fa-trash"></i></button>';
            }

            $image = '<img src="' . base_url('assets/images/product_image/' . $repa['image']) . '" alt="' . $repa['name'] . '" class="img-circle" width="50" height="50" />';
            $produit = $repa['sku'];
            // Status display
            $status = strReparation($repa['reparation_statut']);
            $username = $repa['username'];

            $observation = $repa['reparation_observation'];
            $date_debut = date("d/m/Y", strtotime($repa['reparation_debut']));
            $date_fin = date("d/m/Y", strtotime($repa['reparation_fin']));
            // Add the row data
            $result['data'][$key] = [
                $image,
                $produit,
                $username,
                $status,
                $observation,
                $date_debut,
                $date_fin,
                $buttons
            ];
        }

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

    public function fetchMecanicien_1(int $id)
    {
        $Mecanicien = new Mecanicien();

        $reparation = $Mecanicien->getReparation($id);
        $result = ['data' => []];

        // die(var_dump($reparation));
        // Iterate through the data
        foreach ($reparation as $key => $repa) {
            // Action buttons
            $buttons = '';
            // dd($repa['reparationsID']);
            // Check permissions for updating the store
            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>';
            }

            // Check permissions for deleting the store
            if (in_array('deleteMecanicien', $this->permission)) {
                $buttons .= ' <button type="button" class="btn btn-danger" onclick="removeFunc(' . $repa['reparationsID'] . ')" data-toggle="modal" data-target="#removeModal"><i class="fa fa-trash"></i></button>';
            }

            $image = '<img src="' . base_url('assets/images/product_image/' . $repa['image']) . '" alt="' . $repa['name'] . '" class="img-circle" width="50" height="50" />';
            $produit = $repa['name'];
            // Status display
            $status = $repa['reparation_statut'];
            $username = $repa['username'];

            $observation = $repa['reparation_observation'];
            $date_debut = date("d/m/Y", strtotime($repa['reparation_debut']));
            $date_fin = date("d/m/Y", strtotime($repa['reparation_fin']));

            // Add the row data
            $result['data'][$key] = [
                $image,
                $produit,
                $username,
                $status,
                $observation,
                $date_debut,
                $date_fin,
                $buttons
            ];
        }

        // Return data in JSON format
        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'),
        ];

        // Run validation
        if ($validation->run($validationData)) {
            //     // Prepare data
            $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'),
            ];

            // Load the model and create the store
            $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 {
            // Validation failed, return error messages
            $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 des informations sur la marque";
            }
        } 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) {
            // Set validation rules
            $validation = \Config\Services::validation();

            $validation->setRules([
                'motos_edit' => 'required',
                'mecano' => 'required',
                'statut_edit' => 'required',
                'observation_edit' => 'required',
                'date_debut_edit' => 'required',
                'date_fin_edit' => 'required',
            ]);
            $statutList = [
                "1" => "En cours de réparation",
                "2" => "Reparé",
                "3" => "Non reparé"
            ];
            $statut =  $this->request->getPost('statut');
            $validationData = [
                'motos_edit' => $this->request->getPost('motos'),
                'mecano' => $this->request->getPost('mecano'),
                'statut_edit' => $statutList[$statut],
                'observation_edit' => $this->request->getPost('observation'),
                'date_debut_edit' => $this->request->getPost('date_debut'),
                'date_fin_edit' => $this->request->getPost('date_fin'),
            ];

            $Mecanicien = new Mecanicien();
            
            if ($validation->run($validationData)) {
                
                $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'),
                ];
                // echo '<pre>';
                // die(var_dump($data));

                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 {
                // Validation failed, return error messages
                $response['success'] = false;
                $response['messages'] = $validation->getErrors();
            }
        } else {
            $response['success'] = false;
            $response['messages'] = 'Erreur, veuillez actualiser la page à nouveau !!';
        }

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

    public function fetchMecanicienPerformances()
    {
        $Mecanicien = new Mecanicien();
        $session = session();
        $users = $session->get('user');
        
        $data['id'] = $users['id'];
        $reparation = $Mecanicien->getReparation($data['id']);
        $result = ['data' => []];

        
        // Iterate through the data
        if($users['group_name'] == "Conseil" || $users['group_name'] == "Direction"){
            foreach ($reparation as $key => $repa) {
                $image = '<img src="' . base_url('assets/images/product_image/' . $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']));
                // Add the row data
                $result['data'][$key] = [
                    $user_name,
                    $image,
                    $produit,
                    $repa['sku'],
                    $date_debut,
                    $date_fin,
                ];
            }
            return $this->response->setJSON($result);
        }
        else{
            foreach ($reparation as $key => $repa) {
                $image = '<img src="' . base_url('assets/images/product_image/' . $repa['image']) . '" alt="' . $repa['name'] . '" class="img-circle" width="50" height="50" />';
                $produit = $repa['name'];
                // Status display
                $username = $repa['username'];
    
                $date_debut = date("d/m/Y", strtotime($repa['reparation_debut']));
                $date_fin = date("d/m/Y", strtotime($repa['reparation_fin']));
                // Add the row data
                $result['data'][$key] = [
                    $image,
                    $produit,
                    $repa['sku'],
                    $date_debut,
                    $date_fin,
                ];
            }
    
            // Return data in JSON format
            return $this->response->setJSON($result);
        }
        // Iterate through the data
        
    }
}
