<?php

namespace App\Controllers;

use App\Models\Category;

class CategoryController extends AdminController
{
    public function __construct()
    {
        parent::__construct();   
        // Assuming permission is being set from a session
        helper(['form', 'url']);
    }

    private $pageTitle = 'Categorie';

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

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

    public function fetchCategoryData()
    {
        // Prepare the response array
        $result = ['data' => []];
        $Category = new Category();
        // Get category data
        $data = $Category->getCategoryData(); // Make sure this function exists in your CategoryModel

        // Iterate through each category and build the response
        foreach ($data as $key => $value) {

            // Initialize button HTML
            $buttons = '';

            // Check if the user has permission to update
            if (in_array('updateCategory', $this->permission)) {
                $buttons .= '<button type="button" class="btn btn-default" onclick="editFunc(' . $value['id'] . ')" data-toggle="modal" data-target="#editModal"><i class="fa fa-pencil"></i></button>';
            }

            // Check if the user has permission to delete
            if (in_array('deleteCategory', $this->permission)) {
                $buttons .= ' <button type="button" class="btn btn-default" onclick="removeFunc(' . $value['id'] . ')" data-toggle="modal" data-target="#removeModal"><i class="fa fa-trash"></i></button>';
            }

            // Determine the status label
            $status = ($value['active'] == 1) ? '<span class="label label-success">Active</span>' : '<span class="label label-warning">Inactive</span>';

            // Add data to the result array
            $result['data'][] = [
                $value['name'],
                $status,
                $buttons
            ];
        }

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

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

        // Set validation rules
        $validation = \Config\Services::validation();

        $validation->setRules([
            'category_name' => 'required',
            'active' => 'required',
        ]);

        $validationData = [
            'category_name' => $this->request->getPost('category_name'),
            'active' => $this->request->getPost('active'),
        ];

        $Category = new Category();

        if ($validation->run($validationData)) {
            $data = [
                'name' => $this->request->getPost('category_name'),
                'active' => $this->request->getPost('active'),
            ];

            if ($Category->create($data)) {
                $response['success'] = true;
        		$response['messages'] = 'Créé avec succès';
            } else {
                $response['success'] = false;
        		$response['messages'] = 'Erreur dans la base de données lors de la création des informations sur la marque';
            }
            
        } else {
            $response['success'] = false;
            $response['messages'] = $validation->getErrors();
        }
        return $this->response->setJSON($response);
    }

    public function fetchCategoryDataById(int $id)
    {
        if ($id) {
            $Category = new Category();
            $data = $Category->getCategoryData($id);
            return $this->response->setJSON($data);
        }
    }

    public function update(int $id)
    {
        $this->verifyRole('updateCategory');
        $response = [];

        if ($id) {
            // Set validation rules
            $validation = \Config\Services::validation();

            $validation->setRules([
                'edit_category_name' => 'required',
                'edit_active' => 'required',
            ]);

            $validationData = [
                'edit_category_name' => $this->request->getPost('edit_category_name'),
                'edit_active' => $this->request->getPost('edit_active'),
            ];

            $Category = new Category();

            if ($validation->run($validationData)) {
                $data = [
                    'name' => $this->request->getPost('edit_category_name'),
                    'active' => $this->request->getPost('edit_active'),
                ];

                if ($Category->updateCategory($data, $id)) {
                    $response['success'] = true;
	        		$response['messages'] = 'Mis à jour avec succès';
	        	}
	        	else {
	        		$response['success'] = false;
	        		$response['messages'] = 'Erreur dans la base de données lors de la mise à jour des informations sur la marque';
                }
                
            } 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);
    }

    public function remove()
    {
        $this->verifyRole('deleteCategory');
        $category_id = $this->request->getPost('category_id');

        $response = [];

        if ($category_id) {
            $Category = new Category();
            
            if ($Category->remove($category_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'] = "Erreur, veuillez actualiser la page à nouveau !!";
        }
        return $this->response->setJSON($response);
    }
}