<?php

namespace App\Controllers;

use App\Models\Brands;

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

    private $pageTitle = 'Brands';

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

        $Brands = new Brands();

        $result = $Brands->getBrandData();
        $data['results'] = $result;
        // die(var_dump($data));
        return $this->render_template('brands/index', $data);
    }

    public function fetchBrandData()
    {
        $result = ['data' => []];

        // Load the model
        $brandModel = new Brands();
        $data = $brandModel->getBrandData();

        // Loop through the data
        foreach ($data as $key => $value) {
            // Action buttons
            $buttons = '';

            // Check permissions
            if (in_array('viewBrand', $this->permission)) {
                $buttons .= '<button type="button" class="btn btn-default" onclick="editBrand(' . $value['id'] . ')" data-bs-toggle="modal" data-bs-target="#editBrandModal">
                                <i class="fa fa-pencil"></i>
                            </button>';
            }

            if (in_array('deleteBrand', $this->permission)) {
                $buttons .= ' <button type="button" class="btn btn-danger" onclick="removeBrand(' . $value['id'] . ')" data-bs-toggle="modal" data-bs-target="#removeBrandModal">
                                <i class="fa fa-trash"></i>
                            </button>';
            }

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

            // Prepare the data for DataTable
            $result['data'][$key] = [
                $value['name'],
                $status,
                $buttons,
            ];
        }

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

    public function create()
    {
        $this->verifyRole('createBrand');

        $response = [];

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

        $validation->setRules([
            'brand_name' => 'required',
            'active' => 'required',
        ]);
        $validationData = [
            'brand_name' => $this->request->getPost('brand_name'),
            'active' => $this->request->getPost('active'),
        ];
        
        $Brands = new Brands();
        
        if ($validation->run($validationData)) {
            $data = [
                'name' => $this->request->getPost('brand_name'),
                'active' => $this->request->getPost('active'),
            ];
            
            
            if ($Brands->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 fetchBrandDataById(int $id)
    {
        $Brands = new Brands();
        if ($id) {
            $data = $Brands->getBrandData($id);
            return $this->response->setJSON($data);
        }
    }

    public function update(int $id)
    {
        $this->verifyRole('updateBrand');

        $response = [];

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

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

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

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

                if ($Brands->updateBrand($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('deleteBrand');
        $response = [];

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

        if ($brand_id) {
            $Brands = new Brands();

            if ($Brands->delete($brand_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);
    }

}