<?php
require_once __DIR__ . '/../core/AbstractPdo.php';

class TypeAvancementService extends AbstractPdo {
    protected $table      = 'avancement_type';
    protected $primaryKey = 'id';

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

    public function search($searchData, $page = 1, $perPage = 10) {
        $filters = [];
        foreach (['code', 'libelle'] as $field) {
            if (!empty($searchData[$field])) {
                $filters[$field] = ['value' => $searchData[$field], 'like' => true];
            }
        }
        $offset = ($page - 1) * $perPage;
        $types  = $this->findMultiple($filters, 'id DESC', $perPage, $offset);
        $total  = $this->count($filters);
        return [
            'data'       => $types,
            'total'      => $total,
            'page'       => $page,
            'perPage'    => $perPage,
            'totalPages' => max(1, ceil($total / $perPage))
        ];
    }

    public function getTypeAvancement($id) {
        return $this->findOne($id);
    }

    public function createTypeAvancement($data) {
        if (empty($data['code'])) {
            $data['code'] = 'AUT' . date('Y') . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
        }
        unset($data['status']);
        $this->checkDuplicates($data);
        return $this->insert($data);
    }

    public function updateTypeAvancement($id, $data) {
        unset($data['status']);
        $this->checkDuplicates($data, $id);
        return $this->update($id, $data);
    }

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

    private function checkDuplicates($data, $excludeId = null) {
        foreach (['code', 'libelle'] as $field) {
            if (!empty($data[$field])) {
                $existing = $this->findOneBy([$field => $data[$field]]);
                if ($existing && ($excludeId === null || $existing['id'] != $excludeId)) {
                    throw new Exception("Le champ '$field' ({$data[$field]}) existe déjà.");
                }
            }
        }
    }
}
?>