<?php

namespace App\Controllers\admin;

use App\Models\UserModel;
use App\Models\ProfileModel;
use App\Controllers\BaseController;


class ProfileController extends BaseController
{
    public function index()
    {
        $profileModel = new ProfileModel();
        $userModel = new UserModel();

        // Ambil semua data profile
        $profileData = $profileModel->first();

        // Ambil semua data user
        $userData = $userModel->findAll();

        // Tampilkan view dengan data profile dan user
        return view('admin/profile/index', [
            'profileData' => $profileData,
            'userData' => $userData,
            'aktif' => 'profile'
        ]);
    }

    public function edit()
    {

        $profileModel = new ProfileModel();
        $userModel = new UserModel();

        // Ambil data profile berdasarkan ID
        $profile = $profileModel->first();

        if (!$profile) {
            session()->setFlashdata('error', 'Data tidak ditemukan');
            return redirect()->to(base_url('profile'))->with('error', 'Profile tidak ditemukan.');
        }

        // Ambil semua data mata pelajaran
        $userData = $userModel->findAll();
        $aktif = 'profile';
        return view('admin/profile/edit', [
            'aktif' => $aktif,
            'profile' => $profile,
            'userData' => $userData
        ]);
    }
    public function update()
    {

        $validationRules = [
            'gambar_organisasi' => 'uploaded[gambar_organisasi]|is_image[gambar_organisasi]|max_size[gambar_organisasi,1024]',
            'sejarah' => 'required',
            'visi_misi' => 'required',
        ];

        if (!$this->validate($validationRules)) {
            session()->setFlashdata('error', 'Data tidak valid');
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $profileModel = new ProfileModel();
        $profile = $profileModel->first();
        $gambar = $this->request->getFile('gambar_organisasi');
        if ($gambar->isValid() && !$gambar->hasMoved()) {

            $newGambarName = $gambar->getRandomName();
            $gambar->move(FCPATH . 'foto_profile', $newGambarName);
            unlink(FCPATH . 'foto_profile/' . $profile->gambar_organisasi); // Hapus gambar lama
        } else {
            $newGambarName = $profile->gambar_organisasi;
        }


        $data = [
            'id_profile' => 1,
            'gambar_organisasi' => $newGambarName,
            'sejarah' => $this->request->getPost('sejarah'),
            'visi_misi' => $this->request->getPost('visi_misi'),
            'id_admin' => session()->get('id_admin'),
        ];
        // unset($data['_method']);
        $profileModel->save($data);

        //tampil pesan 
        session()->setFlashdata('success', 'Berhasil edit data profile');
        return redirect()->to(base_url('profile'));
    }
}