<?php

namespace App\Controllers;

use App\Models\LinkModel;

class Links extends BaseController
{
    public function index(): string
    {
        $linkModel = new LinkModel();
        return view('links/index', $this->viewData([
            'links'   => $linkModel->getAll(),
            'isAdmin' => $this->isAdmin(),
        ]));
    }

    public function save(): \CodeIgniter\HTTP\ResponseInterface
    {
        $id   = (int) ($this->request->getPost('id') ?? 0);
        $nama = trim($this->request->getPost('nama') ?? '');
        $url  = trim($this->request->getPost('url') ?? '');

        if ($nama === '' || $url === '') {
            return $this->jsonError('Nama dan URL wajib diisi.');
        }

        $linkModel = new LinkModel();
        if ($id > 0) {
            $linkModel->update($id, ['nama' => $nama, 'url' => $url]);
            $this->logActivity('link_update', "Update link: $nama");
        } else {
            $linkModel->insert(['nama' => $nama, 'url' => $url]);
            $this->logActivity('link_create', "Tambah link: $nama");
        }

        return $this->jsonSuccess('Link berhasil disimpan.');
    }

    public function delete(int $id): \CodeIgniter\HTTP\ResponseInterface
    {
        $linkModel = new LinkModel();
        $link = $linkModel->find($id);
        if (! $link) return $this->jsonError('Link tidak ditemukan.', 404);

        $linkModel->delete($id);
        $this->logActivity('link_delete', "Hapus link: {$link['nama']}");

        return $this->jsonSuccess('Link berhasil dihapus.');
    }
}
