<?php
declare(strict_types=1);
require __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../app/helpers/rbac.php';
require_once __DIR__ . '/../app/helpers/api_security.php';
require_once __DIR__ . '/../app/helpers/uploads.php';

header('Content-Type: application/json; charset=utf-8');

requireApiLogin();
enforceCsrfForUnsafeRequest();

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

function respond(array $payload, int $code = 200): void { apiRespond($payload, $code); }

try {
    if ($action === 'get') {
        $stmt = $pdo->query("SELECT * FROM company_settings ORDER BY id LIMIT 1");
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        respond(['status' => 'success', 'data' => $row ?: null]);
    }

    if ($action === 'save') {
        requireApiPermission('user.manage');
        // Accept multipart form-data
        $name = trim((string)($_POST['name'] ?? '')) ?: null;
        $email = trim((string)($_POST['email'] ?? '')) ?: null;
        $phone = trim((string)($_POST['phone'] ?? '')) ?: null;

        // ensure folder
        $uploadDir = __DIR__ . '/../uploads/company';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

        $pdo->beginTransaction();
        // either update existing or insert
        $stmt = $pdo->query("SELECT id, logo_path FROM company_settings ORDER BY id LIMIT 1");
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        $logoPath = $existing['logo_path'] ?? null;
        if (!empty($_FILES['logo']['tmp_name'])) {
            $f = $_FILES['logo'];
            if ($f['error'] === UPLOAD_ERR_OK) {
                $ext = validateUploadedFile($f, [
                    'image/jpeg' => 'jpg',
                    'image/png' => 'png',
                    'image/gif' => 'gif',
                    'image/webp' => 'webp',
                ], 2 * 1024 * 1024);
                $filename = randomUploadName('company_logo', $ext);
                $dest = $uploadDir . '/' . $filename;
                if (!move_uploaded_file($f['tmp_name'], $dest)) {
                    $pdo->rollBack();
                    respond(['status'=>'error','message'=>'Unable to move uploaded file']);
                }
                // store relative path
                $logoPath = 'uploads/company/' . $filename;
            }
        }

        if ($existing) {
            $stmt = $pdo->prepare("UPDATE company_settings SET name = ?, email = ?, phone = ?, logo_path = ? WHERE id = ?");
            $stmt->execute([$name, $email, $phone, $logoPath, $existing['id']]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO company_settings (name,email,phone,logo_path) VALUES (?,?,?,?)");
            $stmt->execute([$name, $email, $phone, $logoPath]);
        }

        $pdo->commit();
        respond(['status' => 'success', 'message' => 'Company settings saved']);
    }

    respond(['status'=>'error','message'=>'Unknown action']);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    respond(['status'=>'error','message'=>$e->getMessage()]);
}
