<?php

namespace App\Controllers;


use App\Models\ModelTindakan;
use App\Models\ModelMasterTindakan;
use App\Models\ModelKunjungan;

class Tindakan extends BaseController
{
    protected $modelTindakan;
    protected $modelMasterTindakan;
    protected $modelKunjungan;

    public function __construct()
    {
        // Cek apakah pengguna sudah login
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/login'); // Arahkan ke halaman login jika belum login
        }
        $this->modelTindakan = new ModelTindakan();
        $this->modelMasterTindakan = new ModelMasterTindakan();
        $this->modelKunjungan = new ModelKunjungan();
    }

    public function index()
    {
        $data = [
            'Breadcumb' => 'Tindakan',
            'tindakan' => $this->modelTindakan->getAllData(),
            'masterTindakan' => $this->modelMasterTindakan->findAll(),
            'kunjungan' => $this->modelKunjungan->getAllData()
        ];

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



    public function tambahData()
    {
        if ($this->request->getHeaderLine('Content-Type') === 'application/json') {

            $json = $this->request->getJSON();

            $id_kunjungan = $json->id_kunjungan ?? null;
            $tindakanList = $json->tindakan ?? [];

            if (!$id_kunjungan || empty($tindakanList)) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Kunjungan dan tindakan tidak boleh kosong'
                ]);
            }

            $dataInsert = [];

            foreach ($tindakanList as $t) {
                // Validasi minimal
                if (empty($t->id_tindakan)) continue;

                $dataInsert[] = [
                    'id_kunjungan' => $id_kunjungan,
                    'id_tindakan'  => $t->id_tindakan,
                    'keterangan'   => $t->keterangan ?? null,
                    'created_at'   => date('Y-m-d H:i:s'),
                ];
            }

            if (empty($dataInsert)) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Tidak ada tindakan valid untuk disimpan'
                ]);
            }

            if ($this->modelTindakan->tambahData($dataInsert)) {
                return $this->response->setJSON([
                    'status' => 'success',
                    'message' => 'Data Tindakan berhasil ditambahkan'
                ]);
            } else {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Gagal menyimpan data ke database'
                ]);
            }

            // fallback jika request bukan JSON
            return $this->response->setStatusCode(400)->setJSON([
                'status' => 'error',
                'message' => 'Invalid request'
            ]);
        }
    }

    public function updateDetail()
    {
        if ($this->request->getMethod() === 'post') {
            $id_kunjungan = $this->request->getPost('id_kunjungan');
            $detailList = $this->request->getPost('detail');

            if (!$id_kunjungan || empty($detailList)) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Kunjungan dan detail tindakan tidak boleh kosong'
                ]);
            }

            foreach ($detailList as $detail) {
                $id = $detail['id_detail'] ?? null; // 'id_detail' = kolom 'id' pada tabel tindakan
                $id_tindakan = $detail['id_tindakan'] ?? null;
                $keterangan = $detail['keterangan'] ?? null;

                if (!$id || !$id_tindakan) continue;

                $this->modelTindakan->update($id, [
                    'id_tindakan' => $id_tindakan,
                    'keterangan'  => $keterangan,
                    'updated_at'  => date('Y-m-d H:i:s'),
                ]);
            }

            return $this->response->setJSON([
                'status' => 'ok',
                'message' => 'Data tindakan berhasil diperbarui'
            ]);
        }

        return $this->response->setStatusCode(400)->setJSON([
            'status' => 'error',
            'message' => 'Permintaan tidak valid'
        ]);
    }


    public function deleteData()
    {
        if ($this->request->isAJAX()) {
            // Ambil data dari request
            $id_tindakan = $this->request->getVar('id_tindakan');

            // Validasi apakah ID ada
            if (!$id_tindakan) {
                return $this->response->setJSON(['status' => 'error', 'message' => 'ID Tindakan tidak ditemukan dalam permintaan']);
            }

            // Cari data berdasarkan ID
            $data = $this->ModelTindakan->find($id_tindakan);
            if (!$data) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => "Data Tindakan dengan ID $id_tindakan tidak ditemukan"
                ]);
            }

            // Ambil nama untuk pesan
            $nama = $data['nama_tindakan'] ?? 'Tidak diketahui';


            // Proses penghapusan data
            if ($this->ModelTindakan->delete($id_tindakan)) {
                return $this->response->setJSON([
                    'status' => 'success',
                    'message' => "Data Tindakan \"$nama\" berhasil dihapus"
                ]);
            } else {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => "Terjadi kesalahan saat menghapus data Tindakan"
                ]);
            }
        }

        // Jika bukan request AJAX
        return $this->response->setJSON([
            'status' => 'error',
            'message' => "Akses tidak valid"
        ]);
    }

    public function changeStatus()
    {
        $id_Tindakan = $this->request->getPost('id_Tindakan');
        $is_active = $this->request->getPost('is_active');


        if ($this->ModelTindakan->update($id_Tindakan, ['is_active' => $is_active])) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Status Tindakan berhasil diubah.'
            ]);
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Gagal mengubah status Produk.'
            ]);
        }
    }

    public function getTindakanBySiswa($id_siswa)
    {
        $Tindakan = $this->ModelTindakan
            ->where('id_siswa', $id_siswa)
            ->where('is_active', 1)
            ->first();

        if ($Tindakan) {
            echo json_encode($Tindakan);
        } else {
            echo json_encode(null);
        }
    }

    public function importData()
    {
        $file = $this->request->getFile('fileImport');

        if ($file->isValid() && !$file->hasMoved()) {
            $ext = $file->getClientExtension();
            $validExtensions = ['xls', 'xlsx', 'csv'];

            if (in_array($ext, $validExtensions)) {
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader(ucfirst($ext));
                $spreadsheet = $reader->load($file->getTempName());
                $data = $spreadsheet->getActiveSheet()->toArray();

                // Validasi dan simpan data
                $TindakanModel = new ModelTindakan();
                $rows = [];
                $duplicates = [];
                $errors = [];

                foreach ($data as $index => $row) {
                    if ($index === 0) continue; // Lewati header

                    // Pengecekan duplikasi berdasarkan NIK
                    $existing = $TindakanModel->where('nik', $row[1])->first();
                    if ($existing) {
                        $duplicates[] = $row[1]; // Simpan NIK yang duplikat
                        continue; // Skip data ini
                    }

                    $rows[] = [
                        'nama' => $row[0],
                        'nik' => $row[1],
                        'tanggal_lahir' => $row[2],
                        'jenis_kelamin' => $row[3],
                        'alamat' => $row[4],
                        'nama_ibu' => $row[5],
                        'nama_ayah' => $row[6],
                        'status_imunisasi' => $row[7],
                        'berat_badan' => $row[8],
                        'tinggi_badan' => $row[9],
                    ];
                }

                if (!empty($rows)) {
                    $TindakanModel->insertBatch($rows);
                    $message = 'Data berhasil diimport.';
                }

                // Jika ada duplikasi, tambahkan pesan
                if (!empty($duplicates)) {
                    $message = 'Data dengan NIK berikut sudah ada: ' . implode(', ', $duplicates) . '. ';
                }

                // Jika tidak ada data untuk diimport
                if (empty($rows) && empty($duplicates)) {
                    $message = 'Tidak ada data yang diimport.';
                }

                // Mengembalikan response
                if ($message) {
                    return $this->response->setJSON(['status' => 'success', 'message' => $message]);
                }
            }

            return $this->response->setJSON(['status' => 'error', 'message' => 'Format file tidak valid.']);
        }

        return $this->response->setJSON(['status' => 'error', 'message' => 'File tidak valid.']);
    }
}
