<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';

$action = $_GET['action'] ?? '';

if ($action === 'list') {
    try {
        $stmt = db()->query("SELECT * FROM custom_emotes ORDER BY created_at DESC");
        echo json_encode(['success' => true, 'emotes' => $stmt->fetchAll()]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'upload' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['emote'])) {
        echo json_encode(['success' => false, 'error' => 'Aucun fichier reçu (emote)']);
        exit;
    }
    
    if ($_FILES['emote']['error'] !== UPLOAD_ERR_OK) {
        $errorMsg = 'Erreur d\'upload PHP: ' . $_FILES['emote']['error'];
        if ($_FILES['emote']['error'] === 1) $errorMsg = 'Fichier trop volumineux (limit PHP)';
        if ($_FILES['emote']['error'] === 4) $errorMsg = 'Aucun fichier sélectionné';
        echo json_encode(['success' => false, 'error' => $errorMsg]);
        exit;
    }

    $name = preg_replace('/[^a-z0-9_]/', '', strtolower($_POST['name'] ?? 'emote'));
    if (empty($name)) {
        echo json_encode(['success' => false, 'error' => 'Nom invalide']);
        exit;
    }

    $file = $_FILES['emote'];
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    if (!in_array(strtolower($ext), ['png', 'jpg', 'jpeg'])) {
        echo json_encode(['success' => false, 'error' => 'Format non supporté (PNG uniquement recommandé)']);
        exit;
    }

    $uploadDir = __DIR__ . '/../assets/images/custom_emotes/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0775, true);
    }

    $fileName = time() . '_' . $name . '.png';
    $targetPath = $uploadDir . $fileName;

    // Process image: Resize to 48x48
    $srcImage = null;
    if (strtolower($ext) === 'png') $srcImage = imagecreatefrompng($file['tmp_name']);
    else if (in_array(strtolower($ext), ['jpg', 'jpeg'])) $srcImage = imagecreatefromjpeg($file['tmp_name']);

    if (!$srcImage) {
        echo json_encode(['success' => false, 'error' => 'Fichier image corrompu']);
        exit;
    }

    $width = imagesx($srcImage);
    $height = imagesy($srcImage);
    $newSize = 48;
    $dstImage = imagecreatetruecolor($newSize, $newSize);

    // Transparency for PNG
    imagealphablending($dstImage, false);
    imagesavealpha($dstImage, true);
    $transparent = imagecolorallocatealpha($dstImage, 255, 255, 255, 127);
    imagefilledrectangle($dstImage, 0, 0, $newSize, $newSize, $transparent);

    imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $newSize, $newSize, $width, $height);
    imagepng($dstImage, $targetPath);
    
    imagedestroy($srcImage);
    imagedestroy($dstImage);

    $relativePath = 'assets/images/custom_emotes/' . $fileName;
    $code = ':' . $name . ':';

    try {
        $stmt = db()->prepare("INSERT INTO custom_emotes (name, path, code) VALUES (?, ?, ?)");
        $stmt->execute([$name, $relativePath, $code]);
        echo json_encode([
            'success' => true, 
            'emote' => [
                'id' => db()->lastInsertId(),
                'name' => $name,
                'path' => $relativePath,
                'code' => $code
            ]
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'rename' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? 0;
    $newName = preg_replace('/[^a-z0-9_]/', '', strtolower($_POST['name'] ?? ''));
    if (empty($newName)) {
        echo json_encode(['success' => false, 'error' => 'Nom invalide']);
        exit;
    }

    try {
        $code = ':' . $newName . ':';
        $stmt = db()->prepare("UPDATE custom_emotes SET name = ?, code = ? WHERE id = ?");
        $stmt->execute([$newName, $code, $id]);
        echo json_encode(['success' => true, 'name' => $newName, 'code' => $code]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? 0;
    try {
        $stmt = db()->prepare("SELECT path FROM custom_emotes WHERE id = ?");
        $stmt->execute([$id]);
        $emote = $stmt->fetch();
        if ($emote) {
            $filePath = __DIR__ . '/../' . $emote['path'];
            if (file_exists($filePath)) unlink($filePath);
            
            $stmt = db()->prepare("DELETE FROM custom_emotes WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Emote non trouvée']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
