<?php

namespace App\Controllers;

use App\Controllers\AdminController;
use App\Models\Notification;
use App\Models\Orders;
use App\Models\Remise;

class RemiseController extends AdminController
{
    public function __construct()
    {
        parent::__construct();
    }

    private $pageTitle = 'Remise';

    public function index()
    {
        $this->verifyRole('viewRemise');
        
        $data = json_decode($this->fetchTotal(),true);
        
        $this->render_template('demande/index', $data);
    }


    public function fetchTotal(){
        $data = [
            'user_permission' => $this->permission,
            'page_title' => $this->pageTitle
        ];
        return json_encode($data);
    }


    public function fetchRemiseData()
{
    helper(['url', 'form']);
    $Remise = new Remise(); // Assure-toi du bon namespace

    $draw = intval($this->request->getVar('draw'));
    $data = $Remise->getAllDemandeRemiseToday();
    $totalRecords = count($data);
   
    $result = [
        "draw" => $draw,
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => []
    ];
    foreach ($data as $key => $value) {
        $buttons = '';

        if (in_array('validateRemise', $this->permission) && $value['demande_status'] == 'En attente') {
            $buttons .= '<button type="submit" class="btn btn-success" onclick="valideFunc(' . $value['id_demande'] . ')">';
            $buttons .= '<i class="fa fa-check-circle"></i>';
            $buttons .= '</button>';
        }

        if (in_array('refusedRemise', $this->permission) && $value['demande_status'] == 'En attente') {
            $buttons .= ' <button type="button" class="btn btn-danger" onclick="refuseFunc(' . $value['id_demande'] . ')">';
            $buttons .= '<i class="fa fa-times-circle"></i>';
            $buttons .= '</button>';
        }
        // die(var_dump($value));
        $result['data'][$key] = [
            $value['id_demande'],
            $value['product'],
            number_format($value['total_price'], 0, '.', ' '),
            number_format($value['montant_demande'], 0, '.', ' '),
            $value['demande_status'],
            $buttons
        ];
    }

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


    public function updateRemise($id_demande) {
        $this->verifyRole('validateRemise');

        // Load validation service
        $validation = \Config\Services::validation();

        $data['page_title'] = $this->pageTitle;

        $validation->setRules([
            'demande_status' => 'required'
        ]);

        $validationData = [
            'demande_status' => $this->request->getPost('demande_status')
        ];
        $data = [
            'demande_status' => $this->request->getPost('demande_status')
        ];

        $Remise = new Remise();
        if ($this->request->getMethod()=='post') {
            $today = date('Y-m-d');
            $data = [
                'demande_status' => $this->request->getPost('demande_status'),
                'date_demande' => $today,
            ];

            if ($Remise->updateRemise($id_demande, $data)) {
                $remise_product = $Remise->getProductByDemandeId($id_demande);
                $Notification = new NotificationController();
                $session = session();
                $users = $session->get('user');
                $Notification->createNotification("Une demande de remise a été " . $this->request->getPost('demande_status')." Pour le produit: ".$remise_product,"Caissière",(int)$users['store_id'],'remise/');
                return $this->response->setJSON([
                    'success' => true,
                    'messages' => 'Vous avez '.$this->request->getPost('demande_status').' la remise'
                ]);
            } else {
                return $this->response->setJSON([
                    'success' => false,
                    'messages' => 'Erreur lors de la modification de la remise.'
                ]);
            }
        }

    }

}
