<?php

namespace App\Controllers;

use App\Models\AlokasiModel;
use App\Models\PetaniModel;
use App\Models\PupukModel;

class Alokasi extends BaseController
{
    protected $alokasiM;
    protected $db;

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

    public function index()
    {
        // Query Builder untuk Join Tabel Alokasi, Petani, dan Pupuk
        $builder = $this->db->table('alokasi_kuota');
        $builder->select('alokasi_kuota.*, petani.nama_petani, petani.nik, pupuk.nama_pupuk');
        $builder->join('petani', 'petani.id_petani = alokasi_kuota.id_petani');
        $builder->join('pupuk', 'pupuk.id_pupuk = alokasi_kuota.id_pupuk');
        $builder->orderBy('alokasi_kuota.tahun_tanam', 'DESC');
        $alokasi = $builder->get()->getResultArray();

        // Ambil data untuk dropdown di Modal Tambah
        $petaniM = new PetaniModel();
        $pupukM = new PupukModel();

        $data = [
            'title'   => 'Data Alokasi Kuota e-RDKK',
            'alokasi' => $alokasi,
            'petani'  => $petaniM->findAll(),
            'pupuk'   => $pupukM->findAll()
        ];

        return view('alokasi/index', $data);
    }

    public function simpan()
    {
        $this->alokasiM->save([
            'id_petani'   => $this->request->getPost('id_petani'),
            'id_pupuk'    => $this->request->getPost('id_pupuk'),
            'tahun_tanam' => $this->request->getPost('tahun_tanam'),
            'jatah_kg'    => $this->request->getPost('jatah_kg'),
            'terpakai_kg' => 0 // Awal kuota terpakai pasti 0
        ]);

        return redirect()->to('/alokasi')->with('success', 'Kuota alokasi petani <b>berhasil ditambahkan</b>.');
    }

    public function hapus($id)
    {
        $this->alokasiM->delete($id);
        return redirect()->to('/alokasi')->with('success', 'Data kuota <b>berhasil dihapus</b>.');
    }

    // Tambahkan di dalam class Alokasi
    public function generate_otomatis()
    {
        $id_pupuk = $this->request->getPost('id_pupuk');
        $jatah_per_ha = $this->request->getPost('jatah_per_ha');
        $tahun = date('Y');

        $petaniM = new \App\Models\PetaniModel();
        $semuaPetani = $petaniM->where('status_aktif', 'aktif')->findAll();

        $berhasil = 0;
        foreach ($semuaPetani as $p) {
            $jatah_diterima = $p['luas_lahan'] * $jatah_per_ha;

            // Cek apakah petani sudah punya alokasi pupuk ini di tahun yang sama
            $cek = $this->alokasiM->where(['id_petani' => $p['id_petani'], 'id_pupuk' => $id_pupuk, 'tahun_tanam' => $tahun])->first();

            if (!$cek) {
                $this->alokasiM->insert([
                    'id_petani'   => $p['id_petani'],
                    'id_pupuk'    => $id_pupuk,
                    'tahun_tanam' => $tahun,
                    'jatah_kg'    => $jatah_diterima,
                    'terpakai_kg' => 0
                ]);
                $berhasil++;
            }
        }

        return redirect()->to('/alokasi')->with('success', "Generate otomatis selesai. <b>$berhasil petani</b> berhasil diberikan alokasi.");
    }

    public function cetak()
    {
        $builder = $this->db->table('alokasi_kuota');
        $builder->select('alokasi_kuota.*, petani.nama_petani, petani.nik, pupuk.nama_pupuk');
        $builder->join('petani', 'petani.id_petani = alokasi_kuota.id_petani');
        $builder->join('pupuk', 'pupuk.id_pupuk = alokasi_kuota.id_pupuk');
        $builder->orderBy('alokasi_kuota.tahun_tanam', 'DESC');
        $builder->orderBy('petani.nama_petani', 'ASC');

        $data = [
            'title'   => 'Laporan Alokasi Kuota e-RDKK',
            'alokasi' => $builder->get()->getResultArray()
        ];

        return view('alokasi/cetak', $data);
    }
}
