<?php

namespace App\Controllers;

use App\Models\RegionModel;

class RegionController extends BaseController
{
    public function index()
    {
        $regionModel = new RegionModel();
        $data = $regionModel->orderBy('id', 'DESC')->findAll();

        return $this->response->setJSON([
            'status' => 'success',
            'data' => $data
        ]);
    }

    public function create()
    {
        $regionModel = new RegionModel();

        $rules = [
            'nama_wilayah' => 'required|is_unique[regions.nama_wilayah]',
            'provinsi' => 'required',
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Validasi gagal',
                'errors' => $this->validator->getErrors()
            ])->setStatusCode(400);
        }

        $data = [
            'nama_wilayah' => $this->request->getVar('nama_wilayah'),
            'provinsi' => $this->request->getVar('provinsi'),
            'deskripsi' => $this->request->getVar('deskripsi') ?: '',
            'created_at' => date('Y-m-d H:i:s'),
        ];

        $regionId = $regionModel->insert($data);

        // Add audit log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Penambahan Wilayah Baru',
            'notes' => 'Menambahkan wilayah pengawasan baru "' . $data['nama_wilayah'] . '".',
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Wilayah baru berhasil ditambahkan.',
            'region_id' => $regionId
        ]);
    }

    public function update($id)
    {
        $regionModel = new RegionModel();
        $region = $regionModel->find($id);

        if (!$region) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Wilayah tidak ditemukan'
            ])->setStatusCode(404);
        }

        $rules = [
            'nama_wilayah' => 'required|is_unique[regions.nama_wilayah,id,' . $id . ']',
            'provinsi' => 'required',
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Validasi gagal',
                'errors' => $this->validator->getErrors()
            ])->setStatusCode(400);
        }

        $data = [
            'nama_wilayah' => $this->request->getVar('nama_wilayah'),
            'provinsi' => $this->request->getVar('provinsi'),
            'deskripsi' => $this->request->getVar('deskripsi') ?: '',
        ];

        $regionModel->update($id, $data);

        // Add audit log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Update Wilayah Koperasi',
            'notes' => 'Memperbarui informasi wilayah "' . $region['nama_wilayah'] . '" menjadi "' . $data['nama_wilayah'] . '".',
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Wilayah berhasil diperbarui!'
        ]);
    }

    public function delete($id)
    {
        $regionModel = new RegionModel();
        $region = $regionModel->find($id);

        if (!$region) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Wilayah tidak ditemukan'
            ])->setStatusCode(404);
        }

        $regionModel->delete($id);

        // Add audit log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Hapus Wilayah Koperasi',
            'notes' => 'Menghapus wilayah pengawasan "' . $region['nama_wilayah'] . '".',
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Wilayah "' . $region['nama_wilayah'] . '" berhasil dihapus!'
        ]);
    }
}
