<?php
ob_start();
require_once __DIR__ . '/../core/auth.php';
require_once __DIR__ . '/../core/response.php';
cors();
$user = Auth::requireToken();

// Only admin can upload logo
if ($user['rights'] !== 'admin') json_err('Admin access required', 403);

$db  = DB::get();
$act = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    // Auto-add logo columns if they don't exist yet
    try {
        $db->query("ALTER TABLE `company` ADD COLUMN IF NOT EXISTS `logo_path` VARCHAR(500) DEFAULT NULL");
        $db->query("ALTER TABLE `company` ADD COLUMN IF NOT EXISTS `logo_width` INT(11) DEFAULT 180");
        $db->query("ALTER TABLE `company` ADD COLUMN IF NOT EXISTS `logo_height` INT(11) DEFAULT 80");
    } catch (Exception $e) { /* already exists or not supported — ignore */ }

    if ($act === 'upload_logo') {
        if (!isset($_FILES['logo']) || $_FILES['logo']['error'] !== UPLOAD_ERR_OK) {
            json_err('No file uploaded or upload error');
        }

        $file     = $_FILES['logo'];
        $allowed  = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
        $mimeType = mime_content_type($file['tmp_name']);

        if (!in_array($mimeType, $allowed)) {
            json_err('Only JPG, PNG, GIF, WEBP, SVG files are allowed');
        }

        if ($file['size'] > 2 * 1024 * 1024) {
            json_err('File too large. Maximum size is 2MB');
        }

        // Create uploads directory
        $uploadDir = __DIR__ . '/../uploads/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

        // Delete old logo if exists
        $existing = $db->selectOne("SELECT logo_path FROM company WHERE record_id = 1");
        if ($existing && $existing['logo_path']) {
            $oldFile = __DIR__ . '/../' . ltrim($existing['logo_path'], '/');
            if (file_exists($oldFile)) unlink($oldFile);
        }

        // Save with fixed name so URL is stable
        $ext      = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'company_logo.' . strtolower($ext);
        $dest     = $uploadDir . $filename;

        if (!move_uploaded_file($file['tmp_name'], $dest)) {
            json_err('Failed to save file');
        }

        $logoPath = 'uploads/' . $filename;
        $db->execute("UPDATE company SET logo_path = ? WHERE record_id = 1", 's', $logoPath);

        Auth::log((int)$user['user_id'], 'UPLOADED COMPANY LOGO', 'company', 1);
        json_ok(['logo_path' => $logoPath, 'url' => $logoPath . '?v=' . time()], 'Logo uploaded');

    } elseif ($act === 'update_logo_size') {
        $width  = max(40, min(600, (int)($_POST['logo_width']  ?? 180)));
        $height = max(20, min(400, (int)($_POST['logo_height'] ?? 80)));
        $db->execute(
            "UPDATE company SET logo_width = ?, logo_height = ? WHERE record_id = 1",
            'ii', $width, $height
        );
        json_ok(['logo_width' => $width, 'logo_height' => $height], 'Size updated');

    } elseif ($act === 'delete_logo') {
        $existing = $db->selectOne("SELECT logo_path FROM company WHERE record_id = 1");
        if ($existing && $existing['logo_path']) {
            $file = __DIR__ . '/../' . ltrim($existing['logo_path'], '/');
            if (file_exists($file)) unlink($file);
        }
        $db->execute("UPDATE company SET logo_path = NULL WHERE record_id = 1");
        Auth::log((int)$user['user_id'], 'DELETED COMPANY LOGO', 'company', 1);
        json_ok(null, 'Logo removed');

    } else {
        json_err('Unknown action');
    }

} catch (Exception $e) {
    json_err($e->getMessage(), 500);
}