<?php

namespace App\Models;

use CodeIgniter\Model;

class Mecanicien extends Model
{
    /**
     * table name
     * @var string
     */
    protected $table = 'reparations';
    protected $primaryKey = 'reparation_id';
    protected $allowedFields = ['user_id', 'produit_id', 'reparation_statut', 'reparation_observation', 'reparation_debut', 'reparation_fin','store_id'];
    protected $useTimestamps = false;

    public function createRepation(array $data)
    {
        return $this->insert($data);
    }

    public function getReparation(int $id = null) 
    {
        $session = session();
        $user = $session->get('user');
        if ($user['group_name'] == "SuperAdmin" || $user['group_name'] == "Direction") {
            $reparation = $this->select('reparations.reparation_id as reparationsID, reparations.user_id, reparations.reparation_statut, reparations.produit_id, reparations.reparation_observation, reparations.reparation_debut, reparations.reparation_fin, users.*, products.*')
             ->join('users', 'reparations.user_id = users.id')
             ->join('products', 'reparations.produit_id = products.id')
             ->findAll();    
        } else {
            if ($id !== null) {
                $reparation = $this->select('reparations.reparation_id as reparationsID, reparations.user_id, reparations.reparation_statut, reparations.produit_id, reparations.reparation_observation, reparations.reparation_debut, reparations.reparation_fin, users.*, products.*')
                    ->join('users', 'reparations.user_id = users.id')
                    ->join('products', 'reparations.produit_id = products.id')
                    ->where('users.id', $id)
                    ->findAll();
            } else {
                $reparation = [];
            }
        }

        return $reparation;
    }

    public function getReparationSingle(int $id)
    {
        $reparation = $this->select('reparations.reparation_id as reparationsID, reparations.user_id, reparations.reparation_statut, reparations.reparation_statut, reparations.produit_id, reparations.reparation_observation, reparations.reparation_debut, reparations.reparation_fin, users.*, products.*')
            ->join('users', 'reparations.user_id = users.id')
            ->join('products', 'reparations.produit_id = products.id')
            ->where('reparations.reparation_id', $id)
            ->first();

        return $reparation;
    }

    public function updateReparation(array $data, int $id)
    {
        return $this->update($id, $data);
    }

    public function deleteReparation(int $id)
    {
        return $this->delete($id);
    }

    public function getTotalReparationPerStatut(){
        return $this->db->table('reparation')
            ->select('COUNT(*) as total') 
            ->where('reparation_statut', 2)
            ->get()
            ->getRow();
    }

    /**
     * ✅ NOUVELLE MÉTHODE : Filtrage par mécanicien au lieu de magasin
     * @param int|null $id ID de l'utilisateur connecté
     * @param string|null $startDate Date de début
     * @param string|null $endDate Date de fin
     * @param int|null $mecanicId ID du mécanicien à filtrer
     * @return array
     */
    public function getReparationWithFilters(int $id = null, $startDate = null, $endDate = null, $mecanicId = null) 
    {
        $session = session();
        $user = $session->get('user');
        
        $builder = $this->select('
                reparations.reparation_id as reparationsID, 
                reparations.user_id, 
                reparations.reparation_statut, 
                reparations.produit_id, 
                reparations.reparation_observation, 
                reparations.reparation_debut, 
                reparations.reparation_fin, 
                users.*, 
                products.*, 
                stores.name as store_name,
                COALESCE(reparations.store_id, products.store_id) as final_store_id
            ')
             ->join('users', 'reparations.user_id = users.id')
             ->join('products', 'reparations.produit_id = products.id')
             ->join('stores', 'COALESCE(reparations.store_id, products.store_id) = stores.id', 'left');
        
        // Filtre par utilisateur si pas admin
        if ($user['group_name'] != "SuperAdmin" && $user['group_name'] != "Direction" && $user['group_name'] != "DAF") {
            $builder->where('users.id', $id);
        }
        
        // ✅ FILTRE PAR DATEs
        if (!empty($startDate) && !empty($endDate)) {
            $builder->where('DATE(reparations.reparation_debut) >=', $startDate);
            $builder->where('DATE(reparations.reparation_debut) <=', $endDate);
        } elseif (!empty($startDate)) {
            $builder->where('DATE(reparations.reparation_debut) >=', $startDate);
        } elseif (!empty($endDate)) {
            $builder->where('DATE(reparations.reparation_debut) <=', $endDate);
        }
        
        // ✅ FILTRE PAR MÉCANICIEN (remplace le filtre magasin)
        if (!empty($mecanicId)) {
            $builder->where('reparations.user_id', $mecanicId);
        }
        
        $builder->orderBy('reparations.reparation_debut', 'DESC');
        
        return $builder->findAll();
    }
}