<?php

namespace App\Controllers;

use App\Models\Products;
use App\Models\Avance;

class AvanceController extends AdminController
{
    private $pageTitle = 'Avances';

    public function __construct()
    {
        parent::__construct();
    }

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

        return $this->render_template('avances/avance', $data);
    }

    public function fetchAvanceData()
    {
        helper(['url', 'form']);
        $Avance = new Avance();

        $result = ['data' => []];
        $data   = $Avance->getAvanceData();
        $session = session();
        $users   = $session->get('user');
        $isAdmin = in_array($users['group_name'], ['Conseil', 'Direction']);
        $isCommerciale = in_array($users['group_name'], ['COMMERCIALE']);
        $isCaissier = in_array($users['group_name'], ['Caissier']);
        foreach ($data as $key => $value) {
            $isOwner    = $users['id'] === $value['user_id'];
            $date_time  = date('d-m-Y h:i a', strtotime($value['avance_date']));

            // Boutons d’action
            $buttons = '';
            if (in_array('updateAvance', $this->permission) && ($isAdmin || $isOwner)) {
                $buttons .= '<button type="button" class="btn btn-default" onclick="editFunc('. $value['avance_id'] .')">'
          . '<i class="fa fa-pencil"></i></button>';
          }
            if (in_array('deleteAvance', $this->permission) && ($isAdmin || $isOwner)) {
                $buttons .= ' <button type="button" class="btn btn-danger" onclick="removeFunc('.$value['avance_id'].')"><i class="fa fa-trash"></i></button>';
            }
            if (in_array('viewAvance', $this->permission) && !$isAdmin) {
                $buttons .= ' <a href="#" data-order-id="'.$value['id'].'" class="btn btn-default btn-view" title="Voir"><i class="fa fa-eye"></i></a>';
            }
            if ($isAdmin) {
                $row = [
                    $value['customer_name'],
                    $value['customer_phone'],
                    $value['customer_address'],
                    number_format((int)$value['gross_amount'], 0, ',', ' '),
                    number_format((int)$value['avance_amount'], 0, ',', ' '),
                    $date_time,
                    $buttons,
                ];   
                $result['data'][] = $row;
            }
            if ($isCommerciale || $isCaissier) {
                $row = [
                    $value['avance_id'],
                    number_format((int)$value['avance_amount'], 0, ',', ' '),
                    number_format((int)$value['amount_due'], 0, ',', ' '),
                    $date_time,
                    $buttons,
                ];   
                $result['data'][] = $row;
            }
        }

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

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

        $validation = \Config\Services::validation();
        $products   = $this->request->getPost('product');

        // Unicité des produits
        if ($products !== null && count($products) !== count(array_unique($products))) {
            return redirect()->back()->withInput()->with('errors', ['product' => 'Chaque produit sélectionné doit être unique.']);
        }

        // Règles de validation
        $validation->setRules([
            'product' => 'required'
        ]);

        $validationData = ['product' => $products];
        $Avance = new Avance();
        $Products = new Products();
        $Notification = New NotificationController();

        if ($this->request->getMethod() === 'post' && $validation->run($validationData)) {
            $session = session();
            $users   = $session->get('user');

            $data = [
                'customer_name'    => $this->request->getPost('customer_name_avance'),
                'customer_address' => $this->request->getPost('customer_address_avance'),
                'customer_phone'   => $this->request->getPost('customer_phone_avance'),
                'customer_cin'     => $this->request->getPost('customer_cin_avance'),
                'avance_date'      => date('Y-m-d H:i:s'),
                'user_id'         => $users['id'],
                'store_id'         => $users['store_id'],
                'product_id'    => $this->request->getPost('product_id'),
                'gross_amount'       => (float)$this->request->getPost('gross_amount_avance'),
                'avance_amount'    => (float)$this->request->getPost('avance_amount'),
                'amount_due'       => (float)$this->request->getPost('amount_due'),
            ];
            $posts = $products;

           if($avance_id = $Avance->createAvance($data)){
            $Notification->createNotification('Une avance a été créé', "Conseil",$users['store_id'], 'avance');
            return $this->response->setJSON([
                'success' => true,
                'messages' => 'Avance créé avec succès !'
            ]);
           }
           else{
            return $this->response->setJSON([
                'success' => false,
                'messages' => 'Une erreur est survenue lors de la création d\une avance !'
            ]);
           }
        }
    }

    public function updateAvance(int $id)
    {
        $this->verifyRole('updateAvance');
        $data['page_title'] = $this->pageTitle;

        $Products   = new Products();
        $Avance = new Avance();

        if ($this->request->getMethod() === 'post') {
            $data = [
                'customer_name'   => $this->request->getPost('customer_name_avance'),
                'customer_address'=> $this->request->getPost('customer_address_avance'),
                'customer_phone'  => $this->request->getPost('customer_phone_avance'),
                'customer_cin'    => $this->request->getPost('customer_cin_avance'),
                'avance_amount'   => (float)$this->request->getPost('avance_amount'),
                'amount_due'   => (float)$this->request->getPost('amount_due'),
            ];

            if ($Avance->updates($id, $data)) {
                session()->setFlashData('success', 'Avance mise à jour avec succès.');
            } else {
                session()->setFlashData('errors', 'Une erreur est survenue lors de la mise à jour.');
            }
        }
    }

    public function remove()
    {
        $this->verifyRole('deleteAvance');
        $avance_id =  $this->request->getPost('avance_id');
        $response = [];

        $Avance = new Avance();
        if ($Avance->remove($avance_id)) {
            $response['success'] = true;
            $response['messages'] = "Avance Supprimé avec succès";
        } else {
            $response['success'] = false;
            $response['messages'] = "une erreur est survenue lors de la suppression d'une avance";
        }
        return $this->response->setJSON($response);
    }

    public function fetchSingleAvance($avance_id)
{
    $this->verifyRole('updateAvance');

    try {
       $avanceModel = new Avance();

        $data = $avanceModel->fetchSingleAvance($avance_id);

        return $this->response->setJSON($data);
    } 
    catch (\Throwable $th) {
        log_message('error', "Erreur lors de la récupération d'une avance: " . $th->getMessage());

        return $this->response
                    ->setStatusCode(500)
                    ->setJSON(['error' => 'Une erreur interne est survenue. Lors de la création d\'une avance']);
    }
}
// Avances complètes (reste = 0)
public function fetchAvanceComplete()
{
    $this->verifyRole('viewAvance');
    $Avance = new Avance();
    $data   = $Avance->getAvanceComplete(); // méthode à créer dans le modèle

    $result = ['data' => []];
    $session = session();
    $users   = $session->get('user');
    $isAdmin = in_array($users['group_name'], ['Conseil', 'Direction']);
    $isCommerciale = in_array($users['group_name'], ['COMMERCIALE']);
    $isCaissier = in_array($users['group_name'], ['Caissier']);

    foreach($data as $value) {
        $buttons = '';
        $isOwner = $users['id'] === $value['user_id'];

        if (in_array('updateAvance', $this->permission) && ($isAdmin || $isOwner))
            $buttons .= '<button type="button" class="btn btn-default" onclick="editFunc('. $value['avance_id'] .')"><i class="fa fa-pencil"></i></button>';
        if (in_array('deleteAvance', $this->permission) && ($isAdmin || $isOwner))
            $buttons .= ' <button type="button" class="btn btn-danger" onclick="removeFunc('.$value['avance_id'].')"><i class="fa fa-trash"></i></button>';

        $date_time = date('d-m-Y h:i a', strtotime($value['avance_date']));

        if ($isAdmin) {
            $row = [
                $value['customer_name'],
                $value['customer_phone'],
                $value['customer_address'],
                number_format((int)$value['gross_amount'],0,',',' '),
                number_format((int)$value['avance_amount'],0,',',' '),
                number_format((int)$value['amount_due'],0,',',' '),
                $date_time,
                $buttons
            ];
            $result['data'][] = $row;
        }

        if ($isCommerciale || $isCaissier) {
            $row = [
                $value['avance_id'],
                number_format((int)$value['avance_amount'],0,',',' '),
                number_format((int)$value['amount_due'],0,',',' '),
                $date_time,
                $buttons
            ];
            $result['data'][] = $row;
        }
    }

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

// Avances expirées (deadline dépassée)
public function fetchExpiredAvance()
{
    $this->verifyRole('viewAvance');
    $Avance = new Avance();
    $data   = $Avance->getAvanceExpired(); // méthode à créer dans le modèle

    $result = ['data' => []];
    $session = session();
    $users   = $session->get('user');
    $isAdmin = in_array($users['group_name'], ['Conseil', 'Direction']);
    $isCommerciale = in_array($users['group_name'], ['COMMERCIALE']);
    $isCaissier = in_array($users['group_name'], ['Caissier']);

    foreach($data as $value) {
        $buttons = '';
        $isOwner = $users['id'] === $value['user_id'];

        if (in_array('updateAvance', $this->permission) && ($isAdmin || $isOwner))
            $buttons .= '<button type="button" class="btn btn-default" onclick="editFunc('. $value['avance_id'] .')"><i class="fa fa-pencil"></i></button>';
        if (in_array('deleteAvance', $this->permission) && ($isAdmin || $isOwner))
            $buttons .= ' <button type="button" class="btn btn-danger" onclick="removeFunc('.$value['avance_id'].')"><i class="fa fa-trash"></i></button>';

        $date_time = date('d-m-Y h:i a', strtotime($value['avance_date']));

        if ($isAdmin) {
            $row = [
                $value['customer_name'],
                $value['customer_phone'],
                $value['customer_address'],
                number_format((int)$value['gross_amount'],0,',',' '),
                number_format((int)$value['avance_amount'],0,',',' '),
                number_format((int)$value['amount_due'],0,',',' '),
                $date_time,
                $buttons
            ];
            $result['data'][] = $row;
        }

        if ($isCommerciale || $isCaissier) {
            $row = [
                $value['avance_id'],
                number_format((int)$value['avance_amount'],0,',',' '),
                number_format((int)$value['amount_due'],0,',',' '),
                $date_time,
                $buttons
            ];
            $result['data'][] = $row;
        }
    }

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


}
