<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class BidangController extends BaseController
{
    private $db;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
    }

    public function index()
    {
        $data = [
            'title' => 'Daftar Bidang',
            'bidang' => $this->db->table('bidang')->get()->getResultArray()
        ];
        return view('superadmin/bidang/index', $data);
    }

    public function create()
    {
        $data = [
            'title' => 'Tambah Bidang',
        ];
        return view('superadmin/bidang/create', $data);
    }

    public function store()
    {
        $this->db->table('bidang')->insert([
            'nama_bidang' => $this->request->getPost('nama_bidang'),
            'created_at' => date('Y-m-d H:i:s')
        ]);
        
        return redirect()->to('/bidang')->with('success', 'Data bidang berhasil ditambahkan');
    }

    public function edit($id)
    {
        $bidang = $this->db->table('bidang')->where('id', $id)->get()->getRowArray();
        
        if (!$bidang) {
            return redirect()->to('/bidang')->with('error', 'Data tidak ditemukan');
        }

        $data = [
            'title' => 'Edit Bidang',
            'bidang' => $bidang
        ];
        return view('superadmin/bidang/edit', $data);
    }

    public function update($id)
    {
        $this->db->table('bidang')->where('id', $id)->update([
            'nama_bidang' => $this->request->getPost('nama_bidang'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        
        return redirect()->to('/bidang')->with('success', 'Data bidang berhasil diperbarui');
    }

    public function delete($id)
    {
        $this->db->table('bidang')->where('id', $id)->delete();
        return redirect()->to('/bidang')->with('success', 'Data bidang berhasil dihapus');
    }
}
