<?php

namespace App\Models;

use CodeIgniter\Model;

class Historique extends Model
{
    protected $table = 'historique';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'table_name',
        'action',
        'row_id',
        'product_name',
        'sku',
        'store_name',
        'description',
        'created_at'
    ];
    protected $useTimestamps = false;
    protected $createdField = 'created_at';

    /**
     * Récupérer tous les historiques avec pagination
     */
    public function getHistoriqueData($limit = null, $offset = null)
    {
        $builder = $this->select('*')
                        ->orderBy('created_at', 'DESC');
        
        if ($limit !== null) {
            $builder->limit($limit, $offset);
        }
        
        return $builder->get()->getResultArray();
    }

    /**
     * Récupérer l'historique pour un produit spécifique
     */
    public function getHistoriqueByProduct($productId)
    {
        return $this->where('row_id', $productId)
                    ->where('table_name', 'products')
                    ->orderBy('created_at', 'DESC')
                    ->findAll();
    }

    /**
     * Récupérer l'historique pour un magasin spécifique
     */
    public function getHistoriqueByStore($storeName)
    {
        return $this->where('store_name', $storeName)
                    ->orderBy('created_at', 'DESC')
                    ->findAll();
    }

    /**
     * Récupérer l'historique par type d'action
     */
    public function getHistoriqueByAction($action)
    {
        return $this->where('action', $action)
                    ->orderBy('created_at', 'DESC')
                    ->findAll();
    }

    /**
     * Récupérer les statistiques d'historique
     */
    public function getHistoriqueStats()
    {
        $stats = [];
        
        // Total des mouvements
        $stats['total_mouvements'] = $this->countAll();
        
        // Mouvements par action
        $actions = ['CREATE', 'UPDATE', 'DELETE', 'ASSIGN_STORE', 'ENTRER', 'SORTIE'];
        foreach ($actions as $action) {
            $stats['mouvements_' . strtolower($action)] = $this->where('action', $action)->countAllResults();
        }
        
        // Mouvements aujourd'hui
        $stats['mouvements_today'] = $this->where('DATE(created_at)', date('Y-m-d'))->countAllResults();
        
        // Mouvements cette semaine
        $stats['mouvements_week'] = $this->where('created_at >=', date('Y-m-d', strtotime('-7 days')))->countAllResults();
        
        return $stats;
    }

    /**
     * Enregistrer un mouvement dans l'historique
     */
    public function logMovement($tableName, $action, $rowId, $productName, $sku, $storeName, $description = null)
    {
        $data = [
            'table_name' => $tableName,
            'action' => $action,
            'row_id' => $rowId,
            'product_name' => $productName,
            'sku' => $sku,
            'store_name' => $storeName,
            'description' => $description,
            'created_at' => date('Y-m-d H:i:s')
        ];

        return $this->insert($data);
    }

    /**
     * Nettoyer l'historique ancien (plus de X jours)
     */
    public function cleanOldHistory($days = 365)
    {
        $cutoffDate = date('Y-m-d', strtotime("-{$days} days"));
        return $this->where('created_at <', $cutoffDate)->delete();
    }

    /**
     * Récupérer l'historique avec filtres
     *
     * @param array $filters Filtres pour la requête
     * @return array
     */
    public function getHistoriqueWithFilters($filters = [])
    {
        $builder = $this->select('*');

        if (!empty($filters['action']) && $filters['action'] !== 'all') {
            $builder->where('action', $filters['action']);
        }

        if (!empty($filters['store_name']) && $filters['store_name'] !== 'all') {
            $builder->where('store_name', $filters['store_name']);
        }

        if (!empty($filters['product_name'])) {
            $builder->like('product_name', $filters['product_name']);
        }

        if (!empty($filters['sku'])) {
            $builder->like('sku', $filters['sku']);
        }

        if (!empty($filters['date_from'])) {
            $builder->where('created_at >=', $filters['date_from'] . ' 00:00:00');
        }

        if (!empty($filters['date_to'])) {
            $builder->where('created_at <=', $filters['date_to'] . ' 23:59:59');
        }

        return $builder->orderBy('created_at', 'DESC')->findAll();
    }

    /**
     * Exporter l'historique en CSV
     */
    public function exportHistorique($filters = [])
    {
        $data = $this->getHistoriqueWithFilters($filters);
        
        $csvData = "ID,Table,Action,ID Produit,Nom Produit,SKU,Magasin,Description,Date/Heure\n";
        
        foreach ($data as $row) {
            $csvData .= '"' . $row['id'] . '",';
            $csvData .= '"' . $row['table_name'] . '",';
            $csvData .= '"' . $row['action'] . '",';
            $csvData .= '"' . $row['row_id'] . '",';
            $csvData .= '"' . str_replace('"', '""', $row['product_name']) . '",';
            $csvData .= '"' . $row['sku'] . '",';
            $csvData .= '"' . $row['store_name'] . '",';
            $csvData .= '"' . str_replace('"', '""', $row['description'] ?? '') . '",';
            $csvData .= '"' . $row['created_at'] . '"' . "\n";
        }
        
        return $csvData;
    }
}