<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user = requireRole([1, 2]); // Admin/Dev only
$db   = getDB();

$action = post('action', 'upload');

if ($action === 'delete') {
    $row = $db->query("SELECT setting_value FROM settings WHERE setting_key='company_logo'")->fetch();
    if ($row && $row['setting_value']) {
        $path = __DIR__ . '/../../' . $row['setting_value'];
        if (file_exists($path)) unlink($path);
    }
    $db->prepare("INSERT INTO settings (setting_key, setting_value, setting_group, label, input_type) VALUES ('company_logo',NULL,'general','Company Logo','text') ON DUPLICATE KEY UPDATE setting_value=NULL")->execute();
    apiSuccess([], 'Logo removed.');
}

// Upload
if (empty($_FILES['logo']) || $_FILES['logo']['error'] !== UPLOAD_ERR_OK) {
    apiError('No file uploaded.', 422);
}

$file    = $_FILES['logo'];
$finfo   = finfo_open(FILEINFO_MIME_TYPE);
$mime    = finfo_file($finfo, $file['tmp_name']); finfo_close($finfo);
$allowed = ['image/jpeg','image/png','image/webp','image/svg+xml'];
if (!in_array($mime, $allowed)) apiError('Only JPG, PNG, WebP or SVG allowed.', 422);
if ($file['size'] > 5 * 1024 * 1024) apiError('Max 5MB.', 422);

$dir = __DIR__ . '/../../uploads/settings/';
if (!is_dir($dir)) mkdir($dir, 0755, true);

// Delete old logo if exists
$old = $db->query("SELECT setting_value FROM settings WHERE setting_key='company_logo'")->fetch();
if ($old && $old['setting_value']) {
    $oldPath = __DIR__ . '/../../' . $old['setting_value'];
    if (file_exists($oldPath)) unlink($oldPath);
}

$ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) ?: 'png';
$filename = 'logo_' . uniqid() . '.' . $ext;
if (!move_uploaded_file($file['tmp_name'], $dir . $filename)) apiError('Upload failed.', 500);

$path = 'uploads/settings/' . $filename;
$db->prepare("INSERT INTO settings (setting_key, setting_value, setting_group, label, input_type) VALUES ('company_logo',?,'general','Company Logo','text') ON DUPLICATE KEY UPDATE setting_value=?")->execute([$path, $path]);

apiSuccess(['path' => $path], 'Logo uploaded.');