<?php

namespace App\Controllers;

use App\Models\Stores;

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

    private $pageTitle = 'Stores';

    public function index()
    {
        $this->verifyRole('viewStore');
        $data['page_title'] = $this->pageTitle;
        
        return $this->render_template('stores/index', $data);
    }

    public function fetchStoresDataById($id) 
	{
		if($id) {
            $Stores = new Stores();

			$data = $Stores->getStoresData($id);
			echo json_encode($data);
		}
	}

    public function fetchStoresData()
    {
        $storeModel = new Stores(); // Load the StoreModel
        $stores = $storeModel->findAll(); // Fetch all data
        $result = ['data' => []];

        // Iterate through the data
        foreach ($stores as $key => $store) {
            // Action buttons
            $buttons = '';

            // Check permissions for updating the store
            if (in_array('updateStore', $this->permission)) {
                $buttons .= '<button type="button" class="btn btn-default" onclick="editFunc(' . $store['id'] . ')" data-toggle="modal" data-target="#editModal"><i class="fa fa-pencil"></i></button>';
            }

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

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

            // Add the row data
            $result['data'][$key] = [
                $store['name'], // Store name
                $status,        // Active or inactive status
                $buttons        // Action buttons
            ];
        }

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

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

        // Set validation rules
        $validation = \Config\Services::validation();
        $validation->setRules([
            'store_name' => 'required',
            'active' => 'required',
        ]);

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

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

            // Load the model and create the store
            $storeModel = new Stores();
            if ($storeModel->createStore($data)) {
                $response['success'] = true;
                $response['messages'] = 'Successfully created';
            } else {
                $response['success'] = false;
                $response['messages'] = 'Error in the database while creating the store';
            }
        } else {
            // Validation failed, return error messages
            $response['success'] = false;
            $response['messages'] = $validation->getErrors();
        }

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

    public function update(int $id)
    {
        $this->verifyRole('updateStore');
        $response = [];
        // die(var_dump($this->request->getPost()));
        if ($id) {
            // Set validation rules
            $validation = \Config\Services::validation();

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

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

            $storeModel = new Stores();

            if ($validation->run($validationData)) {

                $data = [
                    'name' => $this->request->getPost('edit_store_name'),
                    'active' => $this->request->getPost('edit_active'),
                ];
                
                if ($storeModel->updateStore($data, $id)) {
                    $response['success'] = true;
                    $response['messages'] = 'Mise à jour réussie';
                } else {
                    $response['success'] = false;
                    $response['messages'] = 'Erreur dans la base de données lors de la mise à jour du magasin';
                }
                
            } 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 remove()
    {
        $this->verifyRole('deleteStore');
        $response = [];

        $storeId = $this->request->getPost('store_id');

        if ($storeId) {
            $storeModel = new Stores();

            if ($storeModel->delete($storeId)) {
                $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);
    }
}