<?php
namespace Models;
require_once '/home/advanck/salaires/models/Database.php';
use Models\Database;
use PDO;

class Setting {
    public static function all() {
        $pdo = Database::getInstance()->getConnection();
        $stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC");
        return $stmt->fetchAll();
    }

    public static function find($id) {
        $pdo = Database::getInstance()->getConnection();
        $stmt = $pdo->prepare("SELECT * FROM settings WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC); // Important: FETCH_ASSOC
    }

    public static function create($data) {
        $pdo = Database::getInstance()->getConnection();
        $stmt = $pdo->prepare("INSERT INTO settings (keyname, label, value) VALUES (?, ?, ?)");
        return $stmt->execute([$data['keyname'], $data['label'], $data['value']]);
    }

    public static function update($id, $data) {
        if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            die("Token CSRF invalide");
        }
        $pdo = Database::getInstance()->getConnection();
        $stmt = $pdo->prepare("UPDATE settings SET keyname = ?, label = ?, value = ? WHERE id = ?");
        return $stmt->execute([$data['keyname'], $data['label'], $data['value'], $id]);
    }

    public static function delete($id) {
        $pdo = Database::getInstance()->getConnection();
        $stmt = $pdo->prepare("DELETE FROM settings WHERE id = ?");
        return $stmt->execute([$id]);
    }
    function db_log($message, $context = null) {
        $pdo = Database::getInstance()->getConnection();
        $stmt = $pdo->prepare("INSERT INTO debug_logs (message, context) VALUES (?, ?)");
        $stmt->execute([$message, json_encode($context)]);
    }
}