<?php

namespace App\Controllers\admin;

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


class KontakController extends BaseController
{
    public function index()
    {
        $kontakModel = new KontakModel();
        $userModel = new UserModel();

        // Ambil semua data kontak
        $kontakData = $kontakModel->first();

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

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

    public function edit()
    {

        $kontakModel = new KontakModel();
        $userModel = new UserModel();

        // Ambil data kontak berdasarkan ID
        $kontak = $kontakModel->first();

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

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

        $validationRules = [
            'telpon' => 'required',
            'email' => 'required',
            'alamat' => 'required',
        ];

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

        $data = [
            'id_kontak' => 1,
            'id_admin' => session()->get('id_admin'),
            'telpon' => $this->request->getPost('telpon'),
            'alamat' => $this->request->getPost('alamat'),
            'email' => $this->request->getPost('email'),
        ];
        // unset($data['_method']);
        $kontakModel->save($data);

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