<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class OpdController extends BaseController
{
    private $db;

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

    public function index()
    {
        $builder = $this->db->table('opd');
        $builder->select('opd.*, bidang.nama_bidang');
        $builder->join('bidang', 'bidang.id = opd.bidang_id', 'left');
        $opd = $builder->get()->getResultArray();

        $data = [
            'title' => 'Daftar OPD',
            'opd' => $opd
        ];
        return view('superadmin/opd/index', $data);
    }

    public function create()
    {
        $data = [
            'title' => 'Tambah OPD',
            'bidang' => $this->db->table('bidang')->get()->getResultArray()
        ];
        return view('superadmin/opd/create', $data);
    }

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

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

        $data = [
            'title' => 'Edit OPD',
            'opd' => $opd,
            'bidang' => $this->db->table('bidang')->get()->getResultArray()
        ];
        return view('superadmin/opd/edit', $data);
    }

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

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