<?php

namespace App\Controllers;

use App\Models\Attributes;

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

    private $pageTitle = 'Attributes';

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

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

    public function fetchAttributeDataById(int $id)
    {
        if ($id) {
            $Attributes = new Attributes();
            $data = $Attributes->getAttributeData($id);
            return $this->response->setJSON($data);
        }
    }

    public function fetchCategoryData()
    {
        // Prepare the response array
        $result = ['data' => []];

        $Attributes = new Attributes();
        // Get category data
        $data = $Attributes->getAttributeData(); // 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>';
            }
            // Check if the user has permission to delete
            if (in_array('deleteCategory', $this->permission)) {
                $buttons .= ' <a class="btn btn-default" href="values/' . $value['id'] . '"><i class="fa fa-plus"></i></a>';
            }

            // Determine the status label
            $status = ($value['active'] == 1) ? '<span class="label label-success">Active</span>' : '<span class="label label-warning">Inactive</span>';
            $attributCount = $Attributes->countAttributeValue($value['id']);
            // Add data to the result array
            $result['data'][] = [
                $value['name'],
                $attributCount,
                $status,
                $buttons
            ];
        }
        // Return the result as JSON
        return $this->response->setJSON($result);
    }

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

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

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

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

        $Attributes = new Attributes();

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

            if ($Attributes->create($data)) {
                $response['success'] = true;
                $response['messages'] = 'Crée 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 update(int $id)
    {
        $this->verifyRole('updateAttribute');
        $response = [];

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

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

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

            $Attributes = new Attributes();

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

                if ($Attributes->updateAttribute($data, $id)) {
                    $response['success'] = true;
                    $response['messages'] = 'Succesfully updated';
                } else {
                    $response['success'] = false;
                    $response['messages'] = 'Error in the database while updated the brand information';
                }
            } else {
                $response['success'] = false;
                $response['messages'] = $validation->getErrors();
            }
        } else {
            $response['success'] = false;
            $response['messages'] = 'Error please refresh the page again!!';
        }
        return $this->response->setJSON($response);
    }

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

        if ($attribute_id) {
            $Attributes = new Attributes();
            if ($Attributes->delete($attribute_id)) {
                $response['success'] = true;
                $response['messages'] = "Successfully removed";
            } else {
                $response['success'] = false;
                $response['messages'] = "Error in the database while removing the brand information";
            }
        } else {
            $response['success'] = false;
            $response['messages'] = "Refersh the page again!!";
        }
        return $this->response->setJSON($response);
    }

    public function getValue(int $id)
    {
        $Attributes = new Attributes();
        $data['attribute_data'] = $Attributes->getAttributeData($id);
        $this->verifyRole('viewCategory');
        $data['page_title'] = $this->pageTitle;
        // die(var_dump($data));
        $data['test'] = $id;

        return $this->render_template('attributes/addvalue', $data);
    }

    public function fetchCategoryValueData(int $id)
    {
        if ($id) {
            // Prepare the response array
            $result = ['data' => []];

            $Attributes = new Attributes();
            // Get category data
            $data = $Attributes->getAttributeValueData($id); // 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>';
                }

                // Add data to the result array
                $result['data'][] = [
                    $value['value'],
                    $buttons
                ];
            }
            // Return the result as JSON
            return $this->response->setJSON($result);
        }
    }

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

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

        $validation->setRules([
            'attribute_value_name' => 'required',
            'attribute_parent_id' => 'required',
        ]);

        $validationData = [
            'attribute_value_name' => $this->request->getPost('attribute_value_name'),
            'attribute_parent_id' => $this->request->getPost('attribute_parent_id'),
        ];

        $Attributes = new Attributes();

        if ($validation->run($validationData)) {
            $data = [
                'value' => $this->request->getPost('attribute_value_name'),
                'attribute_parent_id' => $this->request->getPost('attribute_parent_id'),
            ];

            if ($Attributes->createValue($data)) {
                $response['success'] = true;
                $response['messages'] = 'Crée 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 fetchAttributeValueById(int $id)
    {
        if ($id) {
            $Attributes = new Attributes();
            $data = $Attributes->getAttributeValueById($id);
            return $this->response->setJSON($data);
        }
    }

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

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

        $validation->setRules([
            'edit_attribute_value_name' => 'required',
            'attribute_parent_id' => 'required',
        ]);

        $validationData = [
            'edit_attribute_value_name' => $this->request->getPost('edit_attribute_value_name'),
            'attribute_parent_id' => $this->request->getPost('attribute_parent_id'),
        ];

        $Attributes = new Attributes();

        if ($validation->run($validationData)) {
            $data = [
                'value' => $this->request->getPost('edit_attribute_value_name'),
                'attribute_parent_id' => $this->request->getPost('attribute_parent_id'),
            ];

            if ($Attributes->updateValue($data, $id)) {
                $response['success'] = true;
                $response['messages'] = 'Succesfully updated';
            } else {
                $response['success'] = false;
                $response['messages'] = 'Error in the database while updated the brand information';
            }
        } else {
            $response['success'] = false;
            $response['messages'] = $validation->getErrors();
        }

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

    public function removeValue()
    {
        $response = [];
        $Attributes = new Attributes();

        if ($this->request->getPost('attribute_value_id') && $Attributes->removeValue($this->request->getPost('attribute_value_id'))) {
            $response['success'] = true;
            $response['messages'] = 'Succesfully removed';
        } else {
            $response['success'] = false;
            $response['messages'] = 'Error in the database while updated the brand information';
        }

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