<?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Models\LspModel;

class Lsp extends BaseController {
    public function index() {
        $model = new LspModel();
        $data = [
            'title' => 'Manajemen LSP P1',
            'lsp'   => $model->first()
        ];
        return view('admin/lsp/index', $data);
    }

    public function update() {
        $model = new LspModel();
        $id = $this->request->getPost('id_lsp');
        $fileGambar = $this->request->getFile('gambar_konstruksi');
        $gambarLama = $this->request->getPost('gambarLama');

        if ($fileGambar->getError() == 4) {
            $namaGambar = $gambarLama;
        } else {
            $namaGambar = $fileGambar->getRandomName();
            $fileGambar->move('assets/img/lsp/', $namaGambar);
            if ($gambarLama != 'default.jpg' && file_exists('assets/img/lsp/' . $gambarLama)) {
                unlink('assets/img/lsp/' . $gambarLama);
            }
        }

        $model->update($id, [
            'judul'             => $this->request->getPost('judul'),
            'sub_judul'         => $this->request->getPost('sub_judul'),
            'konten'            => $this->request->getPost('konten'),
            'gambar_konstruksi' => $namaGambar,
            'updated_at'        => date('Y-m-d H:i:s')
        ]);

        return redirect()->to(base_url('admin/lsp'))->with('success', 'Halaman LSP berhasil diperbarui.');
    }
}