<?php
// app/model/service/EtatAvancementService.php
require_once __DIR__ . '/../core/AbstractPdo.php';

class EtatAvancementService extends AbstractPdo {
    protected $table = 'etat_avancement';
    protected $primaryKey = 'id';

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

    /**
     * Rechercher des états d'avancement avec critères
     */
    public function search($searchData, $page = 1, $perPage = 10) {
        $filters = [];

        $searchFields = ['id', 'libelle', 'code', 'description'];
        foreach ($searchFields as $field) {
            if (!empty($searchData[$field])) {
                $filters[$field] = [
                    'value' => $searchData[$field],
                    'like' => true
                ];
            }
        }

        $offset = ($page - 1) * $perPage;
        $etats = $this->findWithFilters($filters, $perPage, $offset);
        $total = $this->countWithFilters($filters);

        return [
            'data' => $etats,
            'total' => $total,
            'page' => $page,
            'perPage' => $perPage,
            'totalPages' => ceil($total / $perPage)
        ];
    }

    /**
     * Find etats with filters
     */
    public function findWithFilters($filters = [], $limit = null, $offset = null) {
        $sql = "SELECT * FROM etat_avancement";

        $where = [];
        $params = [];

        foreach ($filters as $key => $filter) {
            $field = $key;

            if (isset($filter['like']) && $filter['like'] && !empty($filter['value'])) {
                $paramKey = str_replace('.', '_', $key);
                $where[] = "{$field} LIKE :{$paramKey}";
                $params[":{$paramKey}"] = '%' . $filter['value'] . '%';
            } elseif (!empty($filter['value'])) {
                $paramKey = str_replace('.', '_', $key);
                $where[] = "{$field} = :{$paramKey}";
                $params[":{$paramKey}"] = $filter['value'];
            }
        }

        if (!empty($where)) {
            $sql .= " WHERE " . implode(' AND ', $where);
        }

        $sql .= " ORDER BY libelle ASC";

        if ($limit !== null) {
            $sql .= " LIMIT " . (int)$limit;
            if ($offset !== null) {
                $sql .= " OFFSET " . (int)$offset;
            }
        }

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    /**
     * Count etats with filters
     */
    public function countWithFilters($filters = []) {
        $sql = "SELECT COUNT(*) as count FROM etat_avancement";

        $where = [];
        $params = [];

        foreach ($filters as $key => $filter) {
            $field = $key;

            if (isset($filter['like']) && $filter['like'] && !empty($filter['value'])) {
                $paramKey = str_replace('.', '_', $key);
                $where[] = "{$field} LIKE :{$paramKey}";
                $params[":{$paramKey}"] = '%' . $filter['value'] . '%';
            } elseif (!empty($filter['value'])) {
                $paramKey = str_replace('.', '_', $key);
                $where[] = "{$field} = :{$paramKey}";
                $params[":{$paramKey}"] = $filter['value'];
            }
        }

        if (!empty($where)) {
            $sql .= " WHERE " . implode(' AND ', $where);
        }

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        $result = $stmt->fetch();
        return (int)$result['count'];
    }

    /**
     * Obtenir un état d'avancement par ID
     */
    public function getEtatAvancement($id) {
        return $this->findOne($id);
    }

    /**
     * Obtenir un état d'avancement par code
     */
    public function getEtatAvancementByCode($code) {
        return $this->findOneBy(['code' => $code]);
    }

    /**
     * Créer un nouvel état d'avancement
     */
    public function createEtatAvancement($data) {
        if (empty($data['libelle'])) {
            throw new Exception("Le libellé est obligatoire");
        }
        if (empty($data['code'])) {
            throw new Exception("Le code est obligatoire");
        }

        $this->checkDuplicates($data);

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





    /**
     * Mettre à jour un état d'avancement
     */
    public function updateEtatAvancement($id, $data) {
        $existing = $this->findOne($id);
        if (!$existing) {
            throw new Exception("État d'avancement non trouvé");
        }

        $this->checkDuplicates($data, $id);

        return $this->update($id, $data);
    }

    /**
     * Vérifier les doublons
     */
    private function checkDuplicates($data, $excludeId = null) {
        $uniqueFields = ['code'];

        foreach ($uniqueFields as $field) {
            if (isset($data[$field]) && !empty($data[$field])) {
                $criteria = [$field => $data[$field]];
                $existing = $this->findOneBy($criteria);

                if ($existing && ($excludeId === null || $existing['id'] != $excludeId)) {
                    throw new Exception("Le champ '$field' est déjà utilisé par un autre état d'avancement");
                }
            }
        }
    }

    /**
     * Supprimer un état d'avancement
     */
    public function deleteEtatAvancement($id) {
        // Vérifier si l'état est utilisé par des avancements
        $sql = "SELECT COUNT(*) as count FROM avancement WHERE etat_avancement_id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch();

        if ($result['count'] > 0) {
            throw new Exception("Cet état d'avancement est utilisé par des avancements et ne peut pas être supprimé");
        }

        return $this->delete($id);
    }

    /**
     * Obtenir les statistiques
     */
    public function getStats() {
        $sql = "SELECT COUNT(*) as total FROM {$this->table}";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        return $stmt->fetch();
    }

    /**
     * Exporter les états d'avancement (CSV)
     */
    public function exportToCsv() {
        $etats = $this->findAll('libelle ASC');

        if (empty($etats)) {
            return null;
        }

        $csv = "ID,Libellé,Code,Description,Date de création,Date de mise à jour\n";
        foreach ($etats as $e) {
            $csv .= implode(',', [
                $e['id'],
                '"' . addslashes($e['libelle']) . '"',
                '"' . addslashes($e['code']) . '"',
                '"' . addslashes($e['description'] ?? '') . '"',
                $e['created_at'] ?? '',
                $e['updated_at'] ?? ''
            ]) . "\n";
        }

        return $csv;
    }

    /**
     * Obtenir tous les états d'avancement (pour les selects)
     */
    public function getAllEtatAvancement() {
        return $this->findAll('libelle ASC');
    }
}
