<?php

namespace App\Controllers\Admin;

use App\Core\Upload;
use App\Models\IdentitasModel;

class IdentitasController extends AdminController
{
    public function edit(): void
    {
        $this->adminView('identitas/edit', [
            'identitas' => (new IdentitasModel())->getIdentitas(),
        ]);
    }

    public function update(): void
    {
        $this->verifyCsrf();

        $model = new IdentitasModel();
        $existing = $model->getIdentitas();

        $data = [
            'nama_fakultas' => trim($_POST['nama_fakultas'] ?? ''),
            'singkatan'     => trim($_POST['singkatan'] ?? ''),
            'tagline'       => trim($_POST['tagline'] ?? ''),
            'alamat'        => trim($_POST['alamat'] ?? ''),
            'telepon'       => trim($_POST['telepon'] ?? ''),
            'email'         => trim($_POST['email'] ?? ''),
            'facebook'      => trim($_POST['facebook'] ?? ''),
            'instagram'     => trim($_POST['instagram'] ?? ''),
            'youtube'       => trim($_POST['youtube'] ?? ''),
            'twitter'       => trim($_POST['twitter'] ?? ''),
            'hero_judul'    => trim($_POST['hero_judul'] ?? ''),
            'hero_subjudul' => trim($_POST['hero_subjudul'] ?? ''),
        ];

        $uploadErrors = [];

        foreach (['logo', 'favicon', 'hero_image', 'foto_profil'] as $field) {
            $error = null;
            $filename = Upload::image($_FILES[$field] ?? [], 'identitas', $error);

            if ($error) {
                $uploadErrors[] = ucfirst(str_replace('_', ' ', $field)) . ': ' . $error;
                continue;
            }

            if ($filename) {
                // Hapus file lama kalau ada penggantian
                if (!empty($existing[$field])) {
                    Upload::delete('identitas', $existing[$field]);
                }
                $data[$field] = $filename;
            }
        }

        if ($uploadErrors) {
            $this->setFlash('error', implode(' ', $uploadErrors));
            $this->redirect('admin/identitas');
            return;
        }

        $model->save($data);

        $this->setFlash('success', 'Identitas kampus berhasil diperbarui.');
        $this->redirect('admin/identitas');
    }
}
