<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->database(); // pastikan ini dipanggil
  }

  public function who_reference() {
    header('Content-Type: application/json');

    $query = $this->db->get('tb_who_reference'); // ganti 'users' dengan tabelmu
    $data = $query->result();

    echo json_encode($data);
  }

  private function generate_zscore_id() {
    $prefix = 'ZSCORE_';
    $unique = strtoupper(bin2hex(random_bytes(3))); // 6 karakter hex acak
    return $prefix . $unique;
}


  public function hitung_zscore2() {
    header('Content-Type: application/json');

        $id_pasien     = $this->input->post('id_pasien');
        $berat_badan   = $this->input->post('berat_badan');
        $tinggi_badan  = $this->input->post('tinggi_badan');

        // Ambil data pasien
        $pasien = $this->db->get_where('tb_pasien', ['pasien_id' => $id_pasien])->row();
        if (!$pasien) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Pasien tidak ditemukan']));
        }

        // Hitung usia dalam bulan
        $birth_date = new DateTime($pasien->tanggal_lahir);
        $today = new DateTime();
        $interval = $birth_date->diff($today);
        $usia_bulan = ($interval->y * 12) + $interval->m;

        // Ambil nilai median dan SD dari tb_nilai_rujuk_zscore
        $nilai_rujuk = $this->db->get_where('tb_nilai_rujuk_zscore', [
            'usia_bulan' => $usia_bulan,
            'jenis_kelamin' => $pasien->jenis_kelamin
        ])->row();

        if (!$nilai_rujuk) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Nilai referensi tidak ditemukan untuk usia/gender ini']));
        }

        // Hitung Z-score
        $z_tb = ($tinggi_badan - $nilai_rujuk->median_tb) / $nilai_rujuk->sd_tb;
        $z_bb = ($berat_badan - $nilai_rujuk->median_bb) / $nilai_rujuk->sd_bb;

        // Kategori BB
        if ($z_bb < -3) {
            $kategori_bb = 'Gizi Buruk';
        } elseif ($z_bb >= -3 && $z_bb < -2) {
            $kategori_bb = 'Gizi Kurang';
        } elseif ($z_bb >= -2 && $z_bb <= 2) {
            $kategori_bb = 'Gizi Normal';
        } elseif ($z_bb > 2 && $z_bb <= 3) {
            $kategori_bb = 'Gizi Lebih';
        } else {
            $kategori_bb = 'Obesitas';
        }

        // Kategori TB
        if ($z_tb < -3) {
            $kategori_tb = 'Sangat Pendek';
        } elseif ($z_tb >= -3 && $z_tb < -2) {
            $kategori_tb = 'Pendek';
        } elseif ($z_tb >= -2 && $z_tb <= 2) {
            $kategori_tb = 'Normal';
        } elseif ($z_tb > 2 && $z_tb <= 3) {
            $kategori_tb = 'Tinggi';
        } else {
            $kategori_tb = 'Sangat Tinggi';
        }

        $zscore_id = $this->generate_zscore_id();

        // Simpan ke database
        $data = [
            'zscore_id'    => $zscore_id,
            'id_pasien'    => $id_pasien,
            'usia'         => $usia_bulan,
            'berat_badan'  => $berat_badan,
            'tinggi_badan' => $tinggi_badan,
            'z_bb'         => round($z_bb, 2),
            'z_tb'         => round($z_tb, 2),
            'kategori_bb'  => $kategori_bb,
            'kategori_tb'  => $kategori_tb
        ];

        $this->db->insert('tb_zscore', $data);

        // Kirim respons
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'usia_bulan'   => $usia_bulan,
                'z_bb'         => round($z_bb, 2),
                'z_tb'         => round($z_tb, 2),
                'kategori_bb'  => $kategori_bb,
                'kategori_tb'  => $kategori_tb,
                'status'       => 'Sukses disimpan'
            ]));
    }

    public function hitung_zscore_versi_lama() { 
    header('Content-Type: application/json');

    $id_pasien     = $this->input->post('id_pasien');
    $berat_badan   = $this->input->post('berat_badan');
    $tinggi_badan  = $this->input->post('tinggi_badan');

    // Ambil data pasien
    $pasien = $this->db->get_where('tb_pasien', ['pasien_id' => $id_pasien])->row();
    if (!$pasien) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'Pasien tidak ditemukan']));
    }

    // Hitung usia dalam bulan
    $birth_date = new DateTime($pasien->tanggal_lahir);
    $today = new DateTime();
    $interval = $birth_date->diff($today);
    $usia_bulan = ($interval->y * 12) + $interval->m;

    // Ambil nilai median dan SD dari tb_nilai_rujuk_zscore
    $nilai_rujuk = $this->db->get_where('tb_nilai_rujuk_zscore', [
        'usia_bulan' => $usia_bulan,
        'jenis_kelamin' => $pasien->jenis_kelamin
    ])->row();

    if (!$nilai_rujuk) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'Nilai referensi tidak ditemukan untuk usia/gender ini']));
    }

    // Validasi SD tidak boleh nol
    if ($nilai_rujuk->sd_tb == 0 || $nilai_rujuk->sd_bb == 0) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'Nilai SD tidak valid (nol)']));
    }

    // Hitung Z-score
    $z_tb = ($tinggi_badan - $nilai_rujuk->median_tb) / $nilai_rujuk->sd_tb;
    $z_bb = ($berat_badan - $nilai_rujuk->median_bb) / $nilai_rujuk->sd_bb;

    // Kategori BB
    if ($z_bb < -3) {
        $kategori_bb = 'Gizi Buruk';
    } elseif ($z_bb >= -3 && $z_bb < -2) {
        $kategori_bb = 'Gizi Kurang';
    } elseif ($z_bb >= -2 && $z_bb <= 2) {
        $kategori_bb = 'Gizi Normal';
    } elseif ($z_bb > 2 && $z_bb <= 3) {
        $kategori_bb = 'Gizi Lebih';
    } else {
        $kategori_bb = 'Obesitas';
    }

    // Kategori TB
    if ($z_tb < -3) {
        $kategori_tb = 'Sangat Pendek';
    } elseif ($z_tb >= -3 && $z_tb < -2) {
        $kategori_tb = 'Pendek';
    } elseif ($z_tb >= -2 && $z_tb <= 2) {
        $kategori_tb = 'Normal';
    } elseif ($z_tb > 2 && $z_tb <= 3) {
        $kategori_tb = 'Tinggi';
    } else {
        $kategori_tb = 'Sangat Tinggi';
    }

    $zscore_id = $this->generate_zscore_id();

    // Simpan ke database
    $data = [
        'zscore_id'    => $zscore_id,
        'id_pasien'    => $id_pasien,
        'usia'         => $usia_bulan,
        'berat_badan'  => $berat_badan,
        'tinggi_badan' => $tinggi_badan,
        'z_bb'         => round($z_bb, 2),
        'z_tb'         => round($z_tb, 2),
        'kategori_bb'  => $kategori_bb,
        'kategori_tb'  => $kategori_tb
    ];

    $this->db->insert('tb_zscore', $data);

    // Kirim respons + TAMBAHAN RUMUS
    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'usia_bulan'   => $usia_bulan,
            'z_bb'         => round($z_bb, 2),
            'z_tb'         => round($z_tb, 2),
            'kategori_bb'  => $kategori_bb,
            'kategori_tb'  => $kategori_tb,
            'rumus_bb'     => "($berat_badan - {$nilai_rujuk->median_bb}) / {$nilai_rujuk->sd_bb}",
            'rumus_tb'     => "($tinggi_badan - {$nilai_rujuk->median_tb}) / {$nilai_rujuk->sd_tb}",
            'median_bb'    => $nilai_rujuk->median_bb,
            'sd_bb'        => $nilai_rujuk->sd_bb,
            'median_tb'    => $nilai_rujuk->median_tb,
            'sd_tb'        => $nilai_rujuk->sd_tb,
            'status'       => 'Sukses disimpan'
        ]));
}


    public function hitung_zscore()
    {
        header('Content-Type: application/json');

        $id_pasien    = $this->input->post('id_pasien');
        $berat_badan  = (float)$this->input->post('berat_badan');
        $tinggi_badan = (float)$this->input->post('tinggi_badan');
        $tanggal      = $this->input->post('tanggal'); // opsional: '2025-08-18'

        if (!$id_pasien || !$berat_badan || !$tinggi_badan) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'id_pasien, berat_badan, dan tinggi_badan wajib diisi']));
        }

        // Pasien
        $pasien = $this->db->get_where('tb_pasien', ['pasien_id' => $id_pasien])->row();
        if (!$pasien) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Pasien tidak ditemukan']));
        }

        // Umur (bulan) pada tanggal pengukuran (default: hari ini)
        $refDate = $tanggal ? new DateTime($tanggal) : new DateTime();
        $birth   = new DateTime($pasien->tanggal_lahir);
        $diff    = $birth->diff($refDate);
        $usia_bulan = ($diff->y * 12) + $diff->m; // cukup untuk referensi bulanan

        // Ambil rujukan median/SD (coba exact match, jika tidak ada ambil usia terdekat)
        $nilai_rujuk = $this->db->get_where('tb_nilai_rujuk_zscore', [
            'usia_bulan'    => $usia_bulan,
            'jenis_kelamin' => $pasien->jenis_kelamin
        ])->row();

        if (!$nilai_rujuk) {
            // Fallback: usia terdekat untuk gender tsb
            $nilai_rujuk = $this->db
                ->where('jenis_kelamin', $pasien->jenis_kelamin)
                ->order_by('ABS(usia_bulan - '.(int)$usia_bulan.')', 'ASC', false)
                ->limit(1)
                ->get('tb_nilai_rujuk_zscore')->row();
        }

        if (!$nilai_rujuk) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Nilai referensi tidak ditemukan untuk usia/gender ini']));
        }

        if ((float)$nilai_rujuk->sd_tb == 0.0 || (float)$nilai_rujuk->sd_bb == 0.0) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Nilai SD tidak valid (nol)']));
        }

        // Z-score sederhana (MSD): (X - median)/SD
        $z_tb = ($tinggi_badan - (float)$nilai_rujuk->median_tb) / (float)$nilai_rujuk->sd_tb;
        $z_bb = ($berat_badan  - (float)$nilai_rujuk->median_bb) / (float)$nilai_rujuk->sd_bb;

        // Kategori BB/U
        if ($z_bb < -3)           $kategori_bb = 'Gizi Buruk';
        elseif ($z_bb < -2)       $kategori_bb = 'Gizi Kurang';
        elseif ($z_bb <= 2)       $kategori_bb = 'Gizi Normal';
        elseif ($z_bb <= 3)       $kategori_bb = 'Gizi Lebih';
        else                      $kategori_bb = 'Obesitas';

        // Kategori TB/U
        if ($z_tb < -3)           $kategori_tb = 'Sangat Pendek';
        elseif ($z_tb < -2)       $kategori_tb = 'Pendek';
        elseif ($z_tb <= 2)       $kategori_tb = 'Normal';
        elseif ($z_tb <= 3)       $kategori_tb = 'Tinggi';
        else                      $kategori_tb = 'Sangat Tinggi';

        // Simpan
        $zscore_id = $this->generate_zscore_id();
        $this->db->insert('tb_zscore', [
            'zscore_id'    => $zscore_id,
            'id_pasien'    => $id_pasien,
            'usia'         => $usia_bulan,
            'berat_badan'  => $berat_badan,
            'tinggi_badan' => $tinggi_badan,
            'z_bb'         => round($z_bb, 2),
            'z_tb'         => round($z_tb, 2),
            'kategori_bb'  => $kategori_bb,
            'kategori_tb'  => $kategori_tb,
            'created_at'   => date('Y-m-d H:i:s')
        ]);

        return $this->output->set_content_type('application/json')->set_output(json_encode([
            'usia_bulan'   => $usia_bulan,
            'z_bb'         => round($z_bb, 2),
            'z_tb'         => round($z_tb, 2),
            'kategori_bb'  => $kategori_bb,
            'kategori_tb'  => $kategori_tb,
            'rumus_bb'     => "($berat_badan - {$nilai_rujuk->median_bb}) / {$nilai_rujuk->sd_bb}",
            'rumus_tb'     => "($tinggi_badan - {$nilai_rujuk->median_tb}) / {$nilai_rujuk->sd_tb}",
            'median_bb'    => (float)$nilai_rujuk->median_bb,
            'sd_bb'        => (float)$nilai_rujuk->sd_bb,
            'median_tb'    => (float)$nilai_rujuk->median_tb,
            'sd_tb'        => (float)$nilai_rujuk->sd_tb,
            'status'       => 'Sukses disimpan'
        ]));
    }



    public function hfa_chart_by_pasien()
    {
        // Terima JSON atau form-data
        $json = json_decode(file_get_contents('php://input'), true);
        $id_pasien = $this->input->post('id_pasien') ?? ($json['id_pasien'] ?? null);
        if (!$id_pasien) return $this->_json(['error' => 'id_pasien wajib diisi']);

        // 1) Pasien
        $pasien = $this->db->get_where('tb_pasien', ['pasien_id' => $id_pasien])->row();
        if (!$pasien) return $this->_json(['error' => 'Pasien tidak ditemukan']);

        // 2) Tanggal & tinggi pengukuran (pakai pengukuran terakhir jika ada)
        $last = $this->db->order_by('created_at','DESC')
                         ->limit(1)->get_where('tb_zscore', ['id_pasien'=>$id_pasien])->row();
        $refDate   = $last ? new DateTime(substr($last->created_at,0,10)) : new DateTime();
        $tinggi_cm = $last ? (float)$last->tinggi_badan : null;

        // 3) Usia (bulan) pada tanggal pengukuran
        $birth  = new DateTime($pasien->tanggal_lahir);
        $diff   = $birth->diff($refDate);
        $usia_bulan = ($diff->y * 12) + $diff->m;
        if ($usia_bulan < 0) $usia_bulan = 0;

        // 4) Tentukan rentang usia sekitar pasien (±18 bln), dibatasi oleh range referensi
        $range = $this->db->select('MIN(usia_bulan) AS minAge, MAX(usia_bulan) AS maxAge')
                          ->get_where('tb_nilai_rujuk_zscore', ['jenis_kelamin'=>$pasien->jenis_kelamin])
                          ->row();
        $minAge = (int)$range->minAge; $maxAge = (int)$range->maxAge;
        $age_start = max($minAge, $usia_bulan - 18);
        $age_end   = min($maxAge, $usia_bulan + 18);

        // 5) Ambil referensi MSD per-bulan untuk kurva
        $rows = $this->db->order_by('usia_bulan','ASC')
            ->get_where('tb_nilai_rujuk_zscore', [
                'jenis_kelamin' => $pasien->jenis_kelamin,
                'usia_bulan >=' => $age_start,
                'usia_bulan <=' => $age_end
            ])->result();
        if (!$rows) return $this->_json(['error' => 'Referensi tidak ditemukan untuk rentang usia/gender ini']);

        // 6) Bangun 5 garis Z (MSD): y = median_tb + z * sd_tb
        $ZLINES = [-3, -2, 0, 2, 3];
        $lines = []; foreach ($ZLINES as $z) $lines[$z] = [];
        $minY = 1e9; $maxY = -1e9;

        foreach ($rows as $r) {
            $age = (int)$r->usia_bulan;
            $M   = (float)$r->median_tb;
            $SD  = (float)$r->sd_tb;
            foreach ($ZLINES as $z) {
                $y = $M + $z * $SD;
                $lines[$z][] = ['x'=>$age, 'y'=>round($y,2)];
                if ($y < $minY) $minY = $y;
                if ($y > $maxY) $maxY = $y;
            }
        }

        // 7) Titik pasien & Z-score (pakai referensi usia terdekat)
        $ref = $this->db->where('jenis_kelamin', $pasien->jenis_kelamin)
                        ->order_by('ABS(usia_bulan - '.$usia_bulan.')','ASC', false)
                        ->limit(1)->get('tb_nilai_rujuk_zscore')->row();
        $child_point = null; $z_tb = null; $kategori_tb = null;

        if ($tinggi_cm !== null && $ref && (float)$ref->sd_tb != 0.0) {
            $z_tb = ($tinggi_cm - (float)$ref->median_tb) / (float)$ref->sd_tb;
            $kategori_tb = ($z_tb < -3) ? 'Sangat Pendek' :
                           (($z_tb < -2) ? 'Pendek' :
                           (($z_tb <= 2) ? 'Normal' : (($z_tb <= 3) ? 'Tinggi' : 'Sangat Tinggi')));
            $child_point = ['x'=>$usia_bulan, 'y'=>$tinggi_cm];
        }

        return $this->_json([
            'status'      => 'ok',
            'pasien'      => ['id'=>$id_pasien, 'nama'=>$pasien->nama ?? null, 'jk'=>$pasien->jenis_kelamin],
            'usia_bulan'  => $usia_bulan,
            'domain'      => ['minX'=>$age_start,'maxX'=>$age_end,'minY'=>floor($minY-2),'maxY'=>ceil($maxY+2)],
            'lines'       => [
                ['z'=>-3,'points'=>$lines[-3]],
                ['z'=>-2,'points'=>$lines[-2]],
                ['z'=> 0,'points'=>$lines[0]],
                ['z'=> 2,'points'=>$lines[2]],
                ['z'=> 3,'points'=>$lines[3]],
            ],
            'child_point' => $child_point,                   // null jika belum ada pengukuran
            'z_tb'        => is_null($z_tb) ? null : round($z_tb,2),
            'kategori_tb' => $kategori_tb
        ]);
    }

    private function _json($arr) {
        return $this->output->set_content_type('application/json')->set_output(json_encode($arr));
    }







//   public function Input_detail_nutrisi () {
//     $data = json_decode(file_get_contents("php://input"), true);

//         $id_pasien   = $data['id_pasien'];
//         $id_nutrisi  = $data['id_nutrisi'];
//         $porsi       = $data['porsi'];
//         $tanggal     = $data['tanggal'];

//         // Ambil data nutrisi dari master_nutrisi
//         $nutrisi = $this->db->get_where('master_nutrisi', ['nutrisi_id' => $id_nutrisi])->row();

//         if (!$nutrisi) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_output(json_encode(['error' => 'Data nutrisi tidak ditemukan']));
//         }

//         // Hitung total energi dan kalori
//         $energi_total = $porsi * $nutrisi->energi;
//         $kalori_total = $porsi * $nutrisi->kalori;

//         // Simpan ke tb_nutrisi_pasien_detail
//         $this->db->insert('tb_nutrisi_pasien_detail', [
//             'id_pasien'         => $id_pasien,
//             'id_nutrisi'        => $id_nutrisi,
//             'id_nutrisi_pasien' => 0, // Belum terhubung, nanti saat rekap
//             'tanggal'           => $tanggal,
//             'porsi'             => $porsi,
//             'energi_total'      => $energi_total,
//             'kalori_total'      => $kalori_total
//         ]);

//         return $this->output
//             ->set_content_type('application/json')
//             ->set_output(json_encode([
//                 'status' => 'Detail nutrisi disimpan',
//                 'energi_total' => $energi_total,
//                 'kalori_total' => $kalori_total
//             ]));
//     }  


public function Input_detail_nutrisi() {
    $data = json_decode(file_get_contents("php://input"), true);

    $id_pasien   = $data['id_pasien'];
    $id_nutrisi  = $data['id_nutrisi'];
    $porsi       = $data['porsi'];
    $tanggal     = $data['tanggal'];

    // Ambil data nutrisi dari master_nutrisi
    $nutrisi = $this->db->get_where('master_nutrisi', ['nutrisi_id' => $id_nutrisi])->row();

    if (!$nutrisi) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'Data nutrisi tidak ditemukan']));
    }

    // Hitung total energi dan kalori
    $energi_total = $porsi * $nutrisi->energi;
    $kalori_total = $porsi * $nutrisi->kalori;

    // Cek apakah sudah ada id_nutrisi_pasien di tanggal itu
    $nutrisi_pasien = $this->db->get_where('tb_nutrisi_pasien', [
        'id_pasien' => $id_pasien,
        'tanggal' => $tanggal
    ])->row();

    if ($nutrisi_pasien) {
        $id_nutrisi_pasien = $nutrisi_pasien->nutrisi_pasien_id;
    } else {
        // Buat data awal 0 ke tb_nutrisi_pasien
        $this->db->insert('tb_nutrisi_pasien', [
            'id_pasien' => $id_pasien,
            'tanggal' => $tanggal,
            // 'total_energi' => 0,
            // 'total_kalori' => 0
        ]);
        $id_nutrisi_pasien = $this->db->insert_id();
    }

    // Simpan ke tb_nutrisi_pasien_detail
    $this->db->insert('tb_nutrisi_pasien_detail', [
        'id_pasien'         => $id_pasien,
        'id_nutrisi'        => $id_nutrisi,
        'id_nutrisi_pasien' => $id_nutrisi_pasien,
        'tanggal'           => $tanggal,
        'porsi'             => $porsi,
        'energi_total'      => $energi_total,
        'kalori_total'      => $kalori_total
    ]);

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'status' => 'Detail nutrisi disimpan',
            'id_nutrisi_pasien' => $id_nutrisi_pasien,
            'energi_total' => $energi_total,
            'kalori_total' => $kalori_total
        ]));
}






        public function hitung_total_nutrisi  () {
        $data = json_decode(file_get_contents("php://input"), true);

        $id_pasien = $data['id_pasien'];
        $tanggal   = $data['tanggal'];

        // Hitung total dari detail
        $this->db->select('SUM(energi_total) as total_energi, SUM(kalori_total) as total_kalori');
        $this->db->where('id_pasien', $id_pasien);
        $this->db->where('tanggal', $tanggal);
        $totals = $this->db->get('tb_nutrisi_pasien_detail')->row();

      // Jika tidak ada data detail atau semua nilai nol/null
        if (
            !$totals ||
            (empty($totals->total_energi) && empty($totals->total_kalori)) ||
            ($totals->total_energi == 0 && $totals->total_kalori == 0)
        ) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode([
                    'error' => 'Data nutrisi belum tersedia atau kosong. Tidak dapat disimpan.'
                ]));
        }

        // Simpan ke tb_nutrisi_pasien
        $this->db->insert('tb_nutrisi_pasien', [
            'id_pasien'     => $id_pasien,
            'tanggal'       => $tanggal,
            'total_energi'  => $totals->total_energi,
            'total_kalori'  => $totals->total_kalori
        ]);

        $id_nutrisi_pasien = $this->db->insert_id();

        // Update relasi id_nutrisi_pasien di detail
        $this->db->where('id_pasien', $id_pasien);
        $this->db->where('tanggal', $tanggal);
        $this->db->update('tb_nutrisi_pasien_detail', ['id_nutrisi_pasien' => $id_nutrisi_pasien]);

        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'status' => 'Total nutrisi harian disimpan',
                'total_energi' => $totals->total_energi,
                'total_kalori' => $totals->total_kalori
            ]));
    } 

    public function input_detail_nutrisi_v2()
    {
        $data = json_decode(file_get_contents("php://input"), true);

        $id_pasien   = $data['id_pasien'];
        $id_nutrisi  = $data['id_nutrisi'];
        $porsi       = $data['porsi'];
        $tanggal     = $data['tanggal'];

        // Ambil data nutrisi dari master_nutrisi
        $nutrisi = $this->db->get_where('master_nutrisi', ['nutrisi_id' => $id_nutrisi])->row();
        if (!$nutrisi) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Data nutrisi tidak ditemukan']));
        }

        // Hitung total nutrisi berdasarkan porsi
        $energi_kal    = $porsi * $nutrisi->energi_kal;
        $protein       = $porsi * $nutrisi->protein;
        $lemak_total   = $porsi * $nutrisi->lemak_total;
        $omega_3       = $porsi * $nutrisi->omega_3;
        $omega_6       = $porsi * $nutrisi->omega_6;
        $karbohidrat   = $porsi * $nutrisi->karbohidrat;
        $serat         = $porsi * $nutrisi->serat;
        $air           = $porsi * $nutrisi->air;

        // Cek atau buat entri tb_nutrisi_pasien
        $nutrisi_pasien = $this->db->get_where('tb_nutrisi_pasien', [
            'id_pasien' => $id_pasien,
            'tanggal' => $tanggal
        ])->row();

        if ($nutrisi_pasien) {
            $id_nutrisi_pasien = $nutrisi_pasien->nutrisi_pasien_id;
        } else {
            $this->db->insert('tb_nutrisi_pasien', [
                'id_pasien' => $id_pasien,
                'tanggal' => $tanggal
            ]);
            $id_nutrisi_pasien = $this->db->insert_id();
        }

        // Simpan ke tb_nutrisi_pasien_detail sesuai struktur tabel
        $this->db->insert('tb_nutrisi_pasien_detail', [
            'id_pasien'               => $id_pasien,
            'id_nutrisi'              => $id_nutrisi,
            'id_nutrisi_pasien'       => $id_nutrisi_pasien,
            'tanggal_nutrisi_harian'  => $tanggal,
            'energi_total_harian'     => $energi_kal,
            'protein_harian'          => $protein,
            'lemak_total_harian'      => $lemak_total,
            'omega_3_harian'          => $omega_3,
            'omega_6_harian'          => $omega_6,
            'karbohidrat_harian'      => $karbohidrat,
            'serat_harian'            => $serat,
            'air_harian'              => $air
        ]);

        return $this->output->set_content_type('application/json')->set_output(json_encode([
            'status' => 'Detail nutrisi disimpan',
            'id_nutrisi_pasien' => $id_nutrisi_pasien
        ]));
    }

    public function edit_user($id) {
        header('Content-Type: application/json');
        $data = $this->input->post();

        // Cek user
        $user = $this->db->get_where('tb_users', ['user_id' => $id])->row();
        if (!$user) {
            echo json_encode(['error' => 'User tidak ditemukan']);
            return;
        }

        // Update user
        $updateUser = [
            'nama_lengkap' => $data['nama_lengkap'],
            'no_hp'        => $data['no_hp'],
            'username'     => $data['username'],
            'level'        => $data['level'],
        ];
        if (!empty($data['password'])) {
            $updateUser['password'] = md5($data['password']);
        }
        $this->db->where('user_id', $id)->update('tb_users', $updateUser);

        // Jika wali → update/insert wali
        if ($data['level'] == 'o') {
            $wali = $this->db->get_where('tb_wali', ['id_user' => $id])->row();

            $waliData = [
                'id_user'   => $id,
                'id_pasien' => $data['id_pasien'],
                'nama'      => $data['nama_lengkap'],
                'nik'       => $data['nik'],
                'telepon'   => $data['telepon'],
                'alamat'    => $data['alamat']
            ];

            if ($wali) {
                $this->db->where('id_user', $id)->update('tb_wali', $waliData);
            } else {
                $this->db->insert('tb_wali', $waliData);
            }
        } else {
            // Jika bukan wali tapi ada record wali → hapus
            $this->db->delete('tb_wali', ['id_user' => $id]);
        }

        echo json_encode(['status' => 'success']);
    }

    public function delete_user($id) {
    header('Content-Type: application/json');

    $user = $this->db->get_where('tb_users', ['user_id' => $id])->row();
    if (!$user) {
        echo json_encode(['error' => 'User tidak ditemukan']);
        return;
    }

    // Hapus wali jika ada
    $this->db->delete('tb_wali', ['id_user' => $id]);

    // Hapus user
    $this->db->delete('tb_users', ['user_id' => $id]);

    echo json_encode(['status' => 'success']);
}


    public function edit_detail_nutrisi_v2()
    {
        $data = json_decode(file_get_contents("php://input"), true);

        $nutrisi_detail_id = $data['nutrisi_detail_id'] ?? null;
        $porsi_input       = isset($data['porsi']) ? (float)$data['porsi'] : null; // optional
        $id_nutrisi_input  = $data['id_nutrisi'] ?? null;                           // optional

        if (!$nutrisi_detail_id || (is_null($porsi_input) && is_null($id_nutrisi_input))) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode([
                    'error' => 'nutrisi_detail_id wajib, dan minimal salah satu dari porsi atau id_nutrisi harus diisi'
                ]));
        }

        // Ambil detail sekarang
        $detail = $this->db->get_where('tb_nutrisi_pasien_detail', [
            'nutrisi_detail_id' => $nutrisi_detail_id
        ])->row();

        if (!$detail) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Detail nutrisi tidak ditemukan']));
        }

        $id_pasien         = $detail->id_pasien;
        $id_header         = $detail->id_nutrisi_pasien;
        $id_nutrisi_lama   = $detail->id_nutrisi;
        $tanggal_fix       = $detail->tanggal_nutrisi_harian; // tidak diubah

        // Tentukan id_nutrisi target
        $id_nutrisi_target = $id_nutrisi_input ?: $id_nutrisi_lama;

        // Ambil master nutrisi: lama & target
        $master_lama = $this->db->get_where('master_nutrisi', ['nutrisi_id' => $id_nutrisi_lama])->row();
        $master_tgt  = $this->db->get_where('master_nutrisi', ['nutrisi_id' => $id_nutrisi_target])->row();

        if (!$master_tgt) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Master nutrisi target tidak ditemukan']));
        }
        if (!$master_lama) {
            // Jarang terjadi, tapi jika data lama tidak ada, asumsi porsi = 1 jika tidak ada input porsi.
            $master_lama = (object)[
                'energi_kal' => 0, 'protein' => 0, 'lemak_total' => 0,
                'omega_3' => 0, 'omega_6' => 0, 'karbohidrat' => 0, 'serat' => 0, 'air' => 0
            ];
        }

        // Tentukan porsi yang dipakai
        $porsi_final = $porsi_input;

        if (is_null($porsi_final)) {
            // User tidak kirim porsi → infer dari detail & master_lama
            // Prioritas pakai energi, kalau 0 coba protein, lalu karbohidrat, terakhir fallback 1.
            $porsi_dari_energi = ($master_lama->energi_kal ?? 0) > 0
                ? ((float)$detail->energi_total_harian / (float)$master_lama->energi_kal) : 0;

            $porsi_dari_protein = ($porsi_dari_energi > 0) ? $porsi_dari_energi :
                ((($master_lama->protein ?? 0) > 0)
                    ? ((float)$detail->protein_harian / (float)$master_lama->protein) : 0);

            $porsi_dari_karbo = ($porsi_dari_protein > 0) ? $porsi_dari_protein :
                ((($master_lama->karbohidrat ?? 0) > 0)
                    ? ((float)$detail->karbohidrat_harian / (float)$master_lama->karbohidrat) : 0);

            $porsi_final = $porsi_dari_karbo > 0 ? $porsi_dari_karbo : 1;
        }

        // Hitung ulang nilai berdasarkan master target & porsi_final
        $energi_kal  = $porsi_final * (float)$master_tgt->energi_kal;
        $protein     = $porsi_final * (float)$master_tgt->protein;
        $lemak_total = $porsi_final * (float)$master_tgt->lemak_total;
        $omega_3     = $porsi_final * (float)$master_tgt->omega_3;
        $omega_6     = $porsi_final * (float)$master_tgt->omega_6;
        $karbohidrat = $porsi_final * (float)$master_tgt->karbohidrat;
        $serat       = $porsi_final * (float)$master_tgt->serat;
        $air         = $porsi_final * (float)$master_tgt->air;

        $this->db->trans_begin();

        // Update detail: tidak mengubah tanggal & id_nutrisi_pasien
        $this->db->where('nutrisi_detail_id', $nutrisi_detail_id)->update('tb_nutrisi_pasien_detail', [
            'id_nutrisi'             => $id_nutrisi_target,
            'energi_total_harian'    => $energi_kal,
            'protein_harian'         => $protein,
            'lemak_total_harian'     => $lemak_total,
            'omega_3_harian'         => $omega_3,
            'omega_6_harian'         => $omega_6,
            'karbohidrat_harian'     => $karbohidrat,
            'serat_harian'           => $serat,
            'air_harian'             => $air,
            // tidak menyentuh: id_nutrisi_pasien, tanggal_nutrisi_harian
        ]);

        // Recalc header yang sama
        $this->_recalc_header_nutrisi($id_header);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Gagal mengubah detail nutrisi']));
        }

        $this->db->trans_commit();

        return $this->output->set_content_type('application/json')->set_output(json_encode([
            'status'             => 'Detail nutrisi diperbarui',
            'nutrisi_detail_id'  => $nutrisi_detail_id,
            'id_nutrisi'         => $id_nutrisi_target,
            'porsi_dipakai'      => (float)$porsi_final,
            'id_nutrisi_pasien'  => $id_header,
            'tanggal'            => $tanggal_fix
        ]));
    }

    public function delete_detail_nutrisi_v2()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $nutrisi_detail_id = $data['nutrisi_detail_id'] ?? null;

        if (!$nutrisi_detail_id) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'nutrisi_detail_id wajib diisi']));
        }

        $detail = $this->db->get_where('tb_nutrisi_pasien_detail', [
            'nutrisi_detail_id' => $nutrisi_detail_id
        ])->row();

        if (!$detail) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Detail nutrisi tidak ditemukan']));
        }

        $id_header = $detail->id_nutrisi_pasien;

        $this->db->trans_begin();

        // Hapus detail
        $this->db->delete('tb_nutrisi_pasien_detail', ['nutrisi_detail_id' => $nutrisi_detail_id]);

        // Recalc header
        $this->_recalc_header_nutrisi($id_header);

        // Jika ingin hapus header jika kosong, buka komentar berikut:
        // $count = $this->db->where('id_nutrisi_pasien', $id_header)->count_all_results('tb_nutrisi_pasien_detail');
        // if ($count == 0) {
        //     $this->db->delete('tb_nutrisi_pasien', ['nutrisi_pasien_id' => $id_header]);
        // }

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Gagal menghapus detail nutrisi']));
        }

        $this->db->trans_commit();

        return $this->output->set_content_type('application/json')->set_output(json_encode([
            'status' => 'Detail nutrisi dihapus',
            'id_nutrisi_pasien' => $id_header
        ]));
    }



    public function hitung_total_nutrisi_v2()
    {
        $data = json_decode(file_get_contents("php://input"), true);

        $id_pasien = $data['id_pasien'];
        $tanggal   = $data['tanggal'];

        // Hitung total dari detail
        $this->db->select('
            SUM(energi_total_harian) as total_energi_kal,
            SUM(protein_harian) as total_protein,
            SUM(lemak_total_harian) as total_lemak_total,
            SUM(omega_3_harian) as total_omega_3,
            SUM(omega_6_harian) as total_omega_6,
            SUM(karbohidrat_harian) as total_karbohidrat,
            SUM(serat_harian) as total_serat,
            SUM(air_harian) as total_air
        ');
        $this->db->where('id_pasien', $id_pasien);
        $this->db->where('tanggal_nutrisi_harian', $tanggal);
        $totals = $this->db->get('tb_nutrisi_pasien_detail')->row();

        if (!$totals) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Data nutrisi kosong']));
        }

        // Ambil umur pasien
        $pasien = $this->db->get_where('tb_pasien', ['pasien_id' => $id_pasien])->row();
        if (!$pasien) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Pasien tidak ditemukan']));
        }

        $umur_bulan = floor((time() - strtotime($pasien->tanggal_lahir)) / (30 * 24 * 60 * 60));
        $umur_tahun = floor($umur_bulan / 12);

        // Ambil nilai rujukan AKG
        $rujukan = $this->db->where('usia_bulan_min <=', $umur_bulan)
            ->where('usia_bulan_max >=', $umur_bulan)
            ->get('tb_nilai_rujuk_nutrisi')->row();

        if (!$rujukan) {
            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Nilai rujukan AKG tidak ditemukan untuk umur ini']));
        }

        // Bandingkan total konsumsi dengan nilai rujukan + buat rumus
        $hasil_perbandingan = [];
        foreach ([
            'energi_kal' => 'total_energi_kal',
            'protein' => 'total_protein',
            'lemak_total' => 'total_lemak_total',
            'omega_3' => 'total_omega_3',
            'omega_6' => 'total_omega_6',
            'karbohidrat' => 'total_karbohidrat',
            'serat' => 'total_serat',
            'air' => 'total_air'
        ] as $nutrisi => $total_field) {

            $total_aktual = (float) $totals->$total_field;
            $nilai_rujukan = (float) $rujukan->$nutrisi;
            $selisih = $total_aktual - $nilai_rujukan;

            if ($total_aktual < $nilai_rujukan) {
                $status = "Kurang";
            } elseif ($total_aktual > $nilai_rujukan) {
                $status = "Berlebih";
            } else {
                $status = "Cukup";
            }

            $rumus = "{$total_aktual} - {$nilai_rujukan} = {$selisih}";

            $hasil_perbandingan[] = [
                'nutrisi' => ucfirst(str_replace('_', ' ', $nutrisi)),
                'total_aktual' => $total_aktual,
                'nilai_rujukan' => $nilai_rujukan,
                'selisih' => $selisih,
                'status' => $status,
                'rumus' => $rumus
            ];
        }

        // Update tb_nutrisi_pasien sesuai struktur tabel
        $this->db->where('id_pasien', $id_pasien);
        $this->db->where('tanggal', $tanggal);
        $this->db->update('tb_nutrisi_pasien', [
            'total_energi_kal'   => $totals->total_energi_kal,
            'total_protein'      => $totals->total_protein,
            'total_lemak_total'  => $totals->total_lemak_total,
            'total_omega_3'      => $totals->total_omega_3,
            'total_omega_6'      => $totals->total_omega_6,
            'total_karbohidrat'  => $totals->total_karbohidrat,
            'total_serat'        => $totals->total_serat,
            'total_air'          => $totals->total_air,
            'keterangan'         => json_encode($hasil_perbandingan)
        ]);

        return $this->output->set_content_type('application/json')->set_output(json_encode([
            'status' => 'Total nutrisi harian dihitung',
            'umur' => [
                'tahun' => $umur_tahun,
                'bulan' => $umur_bulan
            ],
            'rujukan' => $rujukan,
            'total_konsumsi' => $totals,
            'perhitungan' => $hasil_perbandingan
        ]));
    }


    public function laporan_nutrisi_akg()
{
    $data = json_decode(file_get_contents("php://input"), true);

    $id_provinsi  = $data['id_provinsi'] ?? null;
    $id_kabupaten = $data['id_kabupaten'] ?? null;
    $id_kecamatan = $data['id_kecamatan'] ?? null;
    $id_desa      = $data['id_desa'] ?? null;
    $tanggal_awal = $data['tanggal_awal'];
    $tanggal_akhir= $data['tanggal_akhir'];

    // Filter pasien sesuai wilayah
    $this->db->select('p.pasien_id, p.nama, p.tanggal_lahir,
                       SUM(d.energi_total_harian) as total_energi_kal,
                       SUM(d.protein_harian) as total_protein,
                       SUM(d.lemak_total_harian) as total_lemak_total,
                       SUM(d.omega_3_harian) as total_omega_3,
                       SUM(d.omega_6_harian) as total_omega_6,
                       SUM(d.karbohidrat_harian) as total_karbohidrat,
                       SUM(d.serat_harian) as total_serat,
                       SUM(d.air_harian) as total_air');
    $this->db->from('tb_nutrisi_pasien_detail d');
    $this->db->join('tb_pasien p','p.pasien_id = d.id_pasien');
    $this->db->where('d.tanggal_nutrisi_harian >=', $tanggal_awal);
    $this->db->where('d.tanggal_nutrisi_harian <=', $tanggal_akhir);

    if ($id_provinsi)  $this->db->where('p.id_provinsi', $id_provinsi);
    if ($id_kabupaten) $this->db->where('p.id_kabupaten', $id_kabupaten);
    if ($id_kecamatan) $this->db->where('p.id_kecamatan', $id_kecamatan);
    if ($id_desa)      $this->db->where('p.id_desa', $id_desa);

    $this->db->group_by('p.pasien_id');
    $rows = $this->db->get()->result();

    $hasil = [];
    $statistik = ['Kurang'=>0, 'Cukup'=>0, 'Berlebih'=>0];
    $total_pasien = 0;

    foreach ($rows as $row) {
        $umur_bulan = floor((time() - strtotime($row->tanggal_lahir)) / (30*24*60*60));

        $rujukan = $this->db->where('usia_bulan_min <=', $umur_bulan)
            ->where('usia_bulan_max >=', $umur_bulan)
            ->get('tb_nilai_rujuk_nutrisi')->row();

        if (!$rujukan) continue;

        // Cek status gizi
        $status_pasien = "Cukup"; // default
        foreach ([
            'energi_kal' => $row->total_energi_kal,
            'protein' => $row->total_protein,
            'lemak_total' => $row->total_lemak_total,
            'omega_3' => $row->total_omega_3,
            'omega_6' => $row->total_omega_6,
            'karbohidrat' => $row->total_karbohidrat,
            'serat' => $row->total_serat,
            'air' => $row->total_air
        ] as $nutrisi => $total_aktual) {

            $nilai_rujukan = (float) $rujukan->$nutrisi;
            if ($total_aktual < $nilai_rujukan * 0.9) {
                $status_pasien = "Kurang"; break;
            }
            if ($total_aktual > $nilai_rujukan * 1.2) {
                $status_pasien = "Berlebih"; break;
            }
        }

        $hasil[] = [
            'pasien_id' => $row->pasien_id,
            'nama' => $row->nama,
            'umur_bulan' => $umur_bulan,
            'total_nutrisi' => $row,
            'status_gizi' => $status_pasien
        ];

        $statistik[$status_pasien]++;
        $total_pasien++;
    }

    $output = [
        'status' => 'ok',
        'filter' => [
            'provinsi' => $id_provinsi,
            'kabupaten'=> $id_kabupaten,
            'kecamatan'=> $id_kecamatan,
            'desa'     => $id_desa,
            'tanggal_awal' => $tanggal_awal,
            'tanggal_akhir'=> $tanggal_akhir
        ],
        'jumlah_pasien' => $total_pasien,
        'statistik' => $statistik,
        'data' => $hasil
    ];

    return $this->output->set_content_type('application/json')
        ->set_output(json_encode($output));
}



public function tambah_pasien () {
    $data = json_decode(file_get_contents("php://input"), true);

    if (!$data['nama'] || !$data['jenis_kelamin'] || !$data['tanggal_lahir'] || !$data['nama_ortu'] || !$data['alamat']) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'Lengkapi semua data']));
    }

    $insert = [
        'nama'          => $data['nama'],
        'jenis_kelamin' => $data['jenis_kelamin'],
        'tanggal_lahir' => $data['tanggal_lahir'],
        'nama_ortu'     => $data['nama_ortu'],
        'alamat'        => $data['alamat'],
        'id_provinsi'   => $data['id_provinsi'] ?? null,
        'id_kota'       => $data['id_kota'] ?? null,
        'id_kecamatan'  => $data['id_kecamatan'] ?? null,
        'id_desa'       => $data['id_desa'] ?? null,
    ];

    $this->db->insert('tb_pasien', $insert);
    $id = $this->db->insert_id();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'status'     => 'Pasien berhasil ditambahkan',
            'pasien_id'  => $id
        ]));
}

public function edit_pasien () {
    $data = json_decode(file_get_contents("php://input"), true);

    if (!isset($data['pasien_id'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'ID pasien wajib diisi']));
    }

    $update = [];

    if (!empty($data['nama'])) {
        $update['nama'] = $data['nama'];
    }
    if (!empty($data['jenis_kelamin'])) {
        $update['jenis_kelamin'] = $data['jenis_kelamin'];
    }
    if (!empty($data['tanggal_lahir'])) {
        $update['tanggal_lahir'] = $data['tanggal_lahir'];
    }
    if (!empty($data['nama_ortu'])) {
        $update['nama_ortu'] = $data['nama_ortu'];
    }
    if (!empty($data['alamat'])) {
        $update['alamat'] = $data['alamat'];
    }
    if (!empty($data['id_provinsi'])) {
        $update['id_provinsi'] = $data['id_provinsi'];
    }
    if (!empty($data['id_kota'])) {
        $update['id_kota'] = $data['id_kota'];
    }
    if (!empty($data['id_kecamatan'])) {
        $update['id_kecamatan'] = $data['id_kecamatan'];
    }
    if (!empty($data['id_desa'])) {
        $update['id_desa'] = $data['id_desa'];
    }

    // jika tidak ada data yang diupdate
    if (empty($update)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'Tidak ada data yang diupdate']));
    }

    $this->db->where('pasien_id', $data['pasien_id']);
    $this->db->update('tb_pasien', $update);

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(['status' => 'Data pasien berhasil diperbarui']));
}


public function tambah_nutrisi() {
    $data = json_decode(file_get_contents("php://input"), true);

    // Validasi minimal
    if (empty($data['nama_nutrisi']) || empty($data['satuan'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'Nama nutrisi dan satuan wajib diisi']));
    }

    // Persiapan data insert hanya jika ada nilainya
    $insert = [
        'nama_nutrisi' => $data['nama_nutrisi'],
        'satuan'       => $data['satuan'],
        'jumlah'       => !empty($data['jumlah']) ? $data['jumlah'] : 0,
    ];

    if (!empty($data['energi_kal']))   $insert['energi_kal']   = $data['energi_kal'];
    if (!empty($data['protein']))      $insert['protein']      = $data['protein'];
    if (!empty($data['lemak_total']))  $insert['lemak_total']  = $data['lemak_total'];
    if (!empty($data['omega_3']))      $insert['omega_3']      = $data['omega_3'];
    if (!empty($data['omega_6']))      $insert['omega_6']      = $data['omega_6'];
    if (!empty($data['karbohidrat']))  $insert['karbohidrat']  = $data['karbohidrat'];
    if (!empty($data['serat']))        $insert['serat']        = $data['serat'];
    if (!empty($data['air']))          $insert['air']          = $data['air'];

    $this->db->insert('master_nutrisi', $insert);
    $id = $this->db->insert_id();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'status' => 'Data nutrisi berhasil ditambahkan',
            'nutrisi_id' => $id
        ]));
}



public function edit_nutrisi() {
    $data = json_decode(file_get_contents("php://input"), true);

    if (empty($data['nutrisi_id'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'nutrisi_id wajib diisi']));
    }

    $update = [];

    if (!empty($data['nama_nutrisi']))  $update['nama_nutrisi'] = $data['nama_nutrisi'];
    if (!empty($data['satuan']))       $update['satuan']       = $data['satuan'];
    if (!empty($data['jumlah']))       $update['jumlah']       = $data['jumlah'];
    if (!empty($data['energi_kal']))   $update['energi_kal']   = $data['energi_kal'];
    if (!empty($data['protein']))      $update['protein']      = $data['protein'];
    if (!empty($data['lemak_total']))  $update['lemak_total']  = $data['lemak_total'];
    if (!empty($data['omega_3']))      $update['omega_3']      = $data['omega_3'];
    if (!empty($data['omega_6']))      $update['omega_6']      = $data['omega_6'];
    if (!empty($data['karbohidrat']))  $update['karbohidrat']  = $data['karbohidrat'];
    if (!empty($data['serat']))        $update['serat']        = $data['serat'];
    if (!empty($data['air']))          $update['air']          = $data['air'];

    // Jika tidak ada data yang mau diupdate
    if (empty($update)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'Tidak ada data yang diperbarui']));
    }

    $this->db->where('nutrisi_id', $data['nutrisi_id']);
    $this->db->update('master_nutrisi', $update);

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(['status' => 'Data nutrisi berhasil diperbarui']));
}


    // public function list_nutrisi() {
    //     $nutrisi = $this->db->get('master_nutrisi')->result();

    //     return $this->output
    //         ->set_content_type('application/json')
    //         ->set_output(json_encode(['data' => $nutrisi]));
    // }

    public function list_nutrisi() {
    $nama = $this->input->post('cari'); // opsional

    if (!empty($nama)) {
        $this->db->like('nama_nutrisi', $nama);
    }

    $nutrisi = $this->db->get('master_nutrisi')->result();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(['data' => $nutrisi]));
}


    public function tambah_wali() {
        // Ambil input dari JSON body
        $data = json_decode(file_get_contents("php://input"), true);

        // Validasi input
        if (empty($data['id_user']) || empty($data['id_pasien']) || empty($data['nama'])) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode([
                    'error' => 'id_user, id_pasien, dan nama wajib diisi'
                ]));
        }

        // Cek apakah pasien valid
        $pasien = $this->db->get_where('tb_pasien', ['pasien_id' => $data['id_pasien']])->row();
        if (!$pasien) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Pasien tidak ditemukan']));
        }

        // Simpan ke tb_wali
        $this->db->insert('tb_wali', [
            'id_user'   => $data['id_user'],
            'id_pasien' => $data['id_pasien'],
            'nama'      => $data['nama'],
            'nik'       => $data['nik'],
            'telepon'   => $data['telepon'],
            'alamat'    => $data['alamat']
        ]);

        $wali_id = $this->db->insert_id();

        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'status'   => 'Data wali berhasil disimpan',
                'wali_id'  => $wali_id
            ]));
    }


     public function login() {

        $username = $this->input->post('username');
        $password = $this->input->post('password');


        if (empty($username) || empty($password)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status'    => 'error',
                'message'    => 'Username atau Password Kosong']));
        }

        // Hash password pakai MD5
        $hashed_password = md5($password);

        // Cek user
        $user = $this->db->get_where('tb_users', [
            'username' => $username,
            'password' => $hashed_password
        ])->row();

        if (!$user) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode([
                'status'    => 'error',
                'message'    => 'User belum terdaftar']));
        }

        // Login sukses
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'status'    => 'success',
                'message'    => 'Berhasil Login',
                'user_id'   => $user->user_id,
                'username'  => $user->username,
                'level'     => $user->level,
                'nama'      => $user->nama_lengkap
            ]));
    }

public function user_profil() {
    $user_id = $this->input->post('user_id');

    if (!$user_id) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'status'  => 'error',
                'message' => 'user_id wajib diisi'
            ]));
    }

    $user = $this->db->get_where('tb_users', [
        'user_id' => $user_id
    ])->row_array();

    if (!$user) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'status'  => 'error',
                'message' => 'User belum terdaftar'
            ]));
    }

    // jika user level 'o' → tidak ada join
    if ($user['level'] !== 'o') {
        $profil = $user;
    } else {
        // JOIN ke tabel wali & pasien
        $this->db->select('
            u.*,
            w.*,
            p.pasien_id, p.nama as nama_pasien, p.jenis_kelamin, p.tanggal_lahir, p.nama_ortu, p.alamat as alamat_pasien
        ');
        $this->db->from('tb_users u');
        $this->db->join('tb_wali w', 'w.id_user = u.user_id', 'left');
        $this->db->join('tb_pasien p', 'p.pasien_id = w.id_pasien', 'left');
        $this->db->where('u.user_id', $user_id);

        $profil = $this->db->get()->row_array();
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'status'  => 'success',
            'message' => 'Data profil berhasil diambil',
            'data'    => $profil
        ]));
}

    public function update_profil()
    {
        header('Content-Type: application/json');

        $user_id = $this->input->post('user_id');
        if (!$user_id) {
            echo json_encode(['status' => 'error', 'message' => 'user_id wajib dikirim']);
            return;
        }

        // ambil data lama
        $user = $this->db->get_where('tb_users', ['user_id' => $user_id])->row_array();
        if (!$user) {
            echo json_encode(['status' => 'error', 'message' => 'User tidak ditemukan']);
            return;
        }

        // ambil input baru
        $nama_lengkap = $this->input->post('nama_lengkap');
        $no_hp        = $this->input->post('no_hp');
        $username     = $this->input->post('username');
        $password     = $this->input->post('password'); // opsional

        $update_data = [];

        // hanya update jika ada perubahan
        if ($nama_lengkap && $nama_lengkap !== $user['nama_lengkap']) {
            $update_data['nama_lengkap'] = $nama_lengkap;
        }
        if ($no_hp && $no_hp !== $user['no_hp']) {
            $update_data['no_hp'] = $no_hp;
        }
        if ($username && $username !== $user['username']) {
            $update_data['username'] = $username;
        }
        if ($password) {
            // hanya update jika user isi password baru
            $update_data['password'] = md5($password);
        }

        if (empty($update_data)) {
            echo json_encode(['status' => 'warning', 'message' => 'Tidak ada perubahan data']);
            return;
        }

        $this->db->where('user_id', $user_id)->update('tb_users', $update_data);

        echo json_encode(['status' => 'success', 'message' => 'Profil berhasil diperbarui']);
    }


    public function wali_pasien() {
        $data = json_decode(file_get_contents("php://input"), true);
        $id_user = $data['id_user'];

        if (empty($id_user)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'id_user wajib diisi']));
        }

        // Join tb_wali dan tb_pasien
        $this->db->select('
            tb_wali.wali_id,
            tb_wali.id_user,
            tb_wali.nama AS nama_wali,
            tb_wali.nik,
            tb_wali.telepon,
            tb_wali.alamat,
            tb_pasien.pasien_id,
            tb_pasien.nama AS nama_pasien,
            tb_pasien.jenis_kelamin,
            tb_pasien.tanggal_lahir,
            tb_pasien.alamat AS alamat_pasien
        ');
        $this->db->from('tb_wali');
        $this->db->join('tb_pasien', 'tb_pasien.pasien_id = tb_wali.id_pasien', 'left');
        $this->db->where('tb_wali.id_user', $id_user);

        $result = $this->db->get()->result();

        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'status' => 'success',
                'data' => $result
            ]));
    }

     public function list_pasien() {
        // Ambil parameter POST langsung
        $nama = $this->input->post('nama');

        $this->db->select('pasien_id, nama, jenis_kelamin, tanggal_lahir, nama_ortu, alamat, created_at');
        $this->db->from('tb_pasien');

        if (!empty($nama)) {
            $this->db->like('nama', $nama);
        }

        $result = $this->db->get()->result();

        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'status' => 'success',
                'total' => count($result),
                'data' => $result
            ]));
    }




    public function list_nutrisi_detail() {
    $id_pasien = $this->input->post('id_pasien');
    $tanggal   = $this->input->post('tanggal');

    if (!$id_pasien || !$tanggal) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['error' => 'id_pasien dan tanggal wajib diisi']));
    }

    $this->db->select('
        d.*,
        m.nama_nutrisi
       
    ');
    $this->db->from('tb_nutrisi_pasien_detail d');
    $this->db->join('master_nutrisi m', 'm.nutrisi_id = d.id_nutrisi', 'left');
    $this->db->where('d.id_pasien', $id_pasien);
    $this->db->where('d.tanggal_nutrisi_harian', $tanggal);
    $this->db->order_by('d.nutrisi_detail_id', 'asc');

    $result = $this->db->get()->result();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'status' => 'success',
            'data' => $result
        ]));
}



    public function tambah_user2() {
        header('Content-Type: application/json');

        $username      = $this->input->post('username');
        $password      = $this->input->post('password');
        $nama_lengkap  = $this->input->post('nama_lengkap');
        $no_hp         = $this->input->post('no_hp');
        $level         = $this->input->post('level');

        // Validasi dasar
        if (empty($username) || empty($password) || empty($nama_lengkap) || empty($no_hp)) {
            echo json_encode(['error' => 'Data wajib diisi: username, password, nama lengkap, No HP']);
            return;
        }

        // Cek username sudah digunakan atau belum
        $cek = $this->db->get_where('tb_users', ['username' => $username])->row();
        if ($cek) {
            echo json_encode(['error' => 'Username sudah digunakan']);
            return;
        }

        // Insert ke database
        $insert = [
            'username'      => $username,
            'password'      => md5($password),
            'nama_lengkap'  => $nama_lengkap,
            'no_hp'         => $no_hp ?? '',
            'level'         => $level,
            'created_at'    => date('Y-m-d H:i:s')
        ];

        $this->db->insert('tb_users', $insert);
        $id = $this->db->insert_id();

        echo json_encode([
            'status'   => 'User berhasil ditambahkan',
            'user_id'  => $id
        ]);
    }

        public function tambah_user() {
        header('Content-Type: application/json');

        $username      = $this->input->post('username');
        $password      = $this->input->post('password');
        $nama_lengkap  = $this->input->post('nama_lengkap');
        $no_hp         = $this->input->post('no_hp');
        $level         = $this->input->post('level');

        // Validasi dasar
        if (empty($username) || empty($password) || empty($nama_lengkap) || empty($no_hp)) {
            echo json_encode(['error' => 'Data wajib diisi: username, password, nama lengkap, No HP']);
            return;
        }

        // Cek username sudah digunakan atau belum
        $cek = $this->db->get_where('tb_users', ['username' => $username])->row();
        if ($cek) {
            echo json_encode(['error' => 'Username sudah digunakan']);
            return;
        }

        // Insert ke tb_users
        $insertUser = [
            'username'      => $username,
            'password'      => md5($password),
            'nama_lengkap'  => $nama_lengkap,
            'no_hp'         => $no_hp ?? '',
            'level'         => $level,
            'created_at'    => date('Y-m-d H:i:s')
        ];
        $this->db->insert('tb_users', $insertUser);
        $idUser = $this->db->insert_id();

        // Jika level = wali → simpan juga ke tb_wali
        if ($level == "o") {
            $id_pasien = $this->input->post('id_pasien');
            $nik       = $this->input->post('nik');
            $telepon   = $this->input->post('telepon');
            $alamat    = $this->input->post('alamat');

            // Validasi pasien
            $pasien = $this->db->get_where('tb_pasien', ['pasien_id' => $id_pasien])->row();
            if ($pasien) {
                $this->db->insert('tb_wali', [
                    'id_user'   => $idUser,
                    'id_pasien' => $id_pasien,
                    'nama'      => $nama_lengkap,
                    'nik'       => $nik,
                    'telepon'   => $telepon ?? $no_hp,
                    'alamat'    => $alamat
                ]);
            }
        }

        echo json_encode([
            'status'   => 'success',
            'user_id'  => $idUser
        ]);
    }


    public function list_user() {
    header('Content-Type: application/json');

    $nama  = $this->input->post('nama');   // keyword pencarian nama
    $level = $this->input->post('level');  // filter level user: 'a', 'o', 'p'

    $this->db->from('tb_users');

    // Filter berdasarkan nama (LIKE)
    if (!empty($nama)) {
        $this->db->like('nama_lengkap', $nama);
    }

    // Filter level
    if (!empty($level)) {
        $this->db->where('level', $level);
    }

    $this->db->order_by('created_at', 'DESC');
    $query = $this->db->get();
    $users = $query->result();

    echo json_encode([
        'status' => 'success',
        'total'  => count($users),
        'data'   => $users
    ]);
}

public function riwayat_pasien() {
    header('Content-Type: application/json');

    $id_pasien = $this->input->post('id_pasien');
    $tanggal   = $this->input->post('tanggal'); // format: YYYY-MM-DD (opsional)

    if (!$id_pasien) {
        echo json_encode(['error' => 'id_pasien wajib dikirim']);
        return;
    }

    // Ambil data zscore
    $this->db->where('id_pasien', $id_pasien);
    if (!empty($tanggal)) {
        $this->db->where('DATE(created_at)', $tanggal);
    }
    $this->db->order_by('created_at', 'DESC');
    $zscore = $this->db->get('tb_zscore')->result();

    // Ambil data nutrisi harian
    $this->db->where('id_pasien', $id_pasien);
    if (!empty($tanggal)) {
        $this->db->where('tanggal', $tanggal);
    }
    $this->db->order_by('tanggal', 'DESC');
    $nutrisi_harian = $this->db->get('tb_nutrisi_pasien')->result();

    // Ambil detail makanan per hari
    $detail_data = [];
    foreach ($nutrisi_harian as $hari) {
        $detail = $this->db
            ->select('d.*, m.nama_nutrisi, m.satuan')
            ->from('tb_nutrisi_pasien_detail d')
            ->join('master_nutrisi m', 'm.nutrisi_id = d.id_nutrisi')
            ->where('d.id_nutrisi_pasien', $hari->nutrisi_pasien_id)
            ->get()
            ->result();

        $detail_data[] = [
            'tanggal' => $hari->tanggal,
            // 'total_energi' => $hari->total_energi,
            // 'nutrisi_harian' => $hari->total_kalori,
            'detail_makanan' => $detail
        ];
    }

    echo json_encode([
        'status' => 'success',
        'filter_tanggal' => $tanggal ?: 'semua',
        'zscore' => $zscore,
        'nutrisi_harian' => $detail_data,
        'nutrisi_total' => $nutrisi_harian
    ]);
}


    public function list_nilai_rujuk() {
        $result = $this->db->get('tb_nilai_rujuk_zscore')->result();
        echo json_encode([
            'status' => 'success',
            'data' => $result
        ]);
    }

    // 2. Tambah data (insert)
    public function insert_nilai_rujuk() {
        $data = [];

        if ($this->input->post('usia_bulan') !== null) {
            $data['usia_bulan'] = $this->input->post('usia_bulan');
        }
        if ($this->input->post('jenis_kelamin') !== null) {
            $data['jenis_kelamin'] = $this->input->post('jenis_kelamin');
        }
        if ($this->input->post('median_tb') !== null) {
            $data['median_tb'] = $this->input->post('median_tb');
        }
        if ($this->input->post('sd_tb') !== null) {
            $data['sd_tb'] = $this->input->post('sd_tb');
        }
        if ($this->input->post('median_bb') !== null) {
            $data['median_bb'] = $this->input->post('median_bb');
        }
        if ($this->input->post('sd_bb') !== null) {
            $data['sd_bb'] = $this->input->post('sd_bb');
        }

        if (empty($data['usia_bulan']) || empty($data['jenis_kelamin'])) {
            echo json_encode([
                'status' => 'error',
                'message' => 'Usia dan Jenis Kelamin wajib diisi'
            ]);
            return;
        }

        $success = $this->db->insert('tb_nilai_rujuk_zscore', $data);
        echo json_encode([
            'status' => $success ? 'success' : 'error',
            'message' => $success ? 'Data berhasil ditambahkan' : 'Gagal menambahkan data',
            'id_inserted' => $success ? $this->db->insert_id() : null
        ]);
    }

    // 3. Update data berdasarkan ID
    public function update_nilai_rujuk() {
        $id = $this->input->post('nilai_rujuk_id');

        // Cek data dulu
        $existing = $this->db->get_where('tb_nilai_rujuk_zscore', ['nilai_rujuk_zscore_id' => $id])->row();
        if (!$existing) {
            echo json_encode([
                'status' => 'error',
                'message' => 'Data tidak ditemukan'
            ]);
            return;
        }

        $data = [];
        if ($this->input->post('usia_bulan') !== null) {
            $data['usia_bulan'] = $this->input->post('usia_bulan');
        }
        if ($this->input->post('jenis_kelamin') !== null) {
            $data['jenis_kelamin'] = $this->input->post('jenis_kelamin');
        }
        if ($this->input->post('median_tb') !== null) {
            $data['median_tb'] = $this->input->post('median_tb');
        }
        if ($this->input->post('sd_tb') !== null) {
            $data['sd_tb'] = $this->input->post('sd_tb');
        }
        if ($this->input->post('median_bb') !== null) {
            $data['median_bb'] = $this->input->post('median_bb');
        }
        if ($this->input->post('sd_bb') !== null) {
            $data['sd_bb'] = $this->input->post('sd_bb');
        }

        if (empty($data)) {
            echo json_encode([
                'status' => 'error',
                'message' => 'Tidak ada field yang diubah'
            ]);
            return;
        }

        $this->db->where('nilai_rujuk_zscore_id', $id);
        $success = $this->db->update('tb_nilai_rujuk_zscore', $data);

        echo json_encode([
            'status' => $success ? 'success' : 'error',
            'message' => $success ? 'Data berhasil diperbarui' : 'Gagal memperbarui data'
        ]);
    }

    // 4. Hapus data berdasarkan ID
    public function delete_nilai_rujuk() {
        $id = $this->input->post('nilai_rujuk_id');

        $check = $this->db->get_where('tb_nilai_rujuk_zscore', ['nilai_rujuk_id' => $id])->row();
        if (!$check) {
            echo json_encode([
                'status' => 'error',
                'message' => 'Data tidak ditemukan'
            ]);
            return;
        }

        $this->db->where('nilai_rujuk_id', $id);
        $success = $this->db->delete('tb_nilai_rujuk_zscore');

        echo json_encode([
            'status' => $success ? 'success' : 'error',
            'message' => $success ? 'Data berhasil dihapus' : 'Gagal menghapus data'
        ]);
    }

    public function get_provinsi() {
        $provinsi = $this->db->get('reg_provinsi')->result();
        echo json_encode(['status' => 'success', 'data' => $provinsi]);
    }

    // 2. List kota berdasarkan id_provinsi
    public function get_kota() {
        $provinsi_id = $this->input->post('id_provinsi');
        if (!$provinsi_id) {
            echo json_encode(['status' => 'error', 'message' => 'id_provinsi wajib diisi']);
            return;
        }

        $kota = $this->db->get_where('reg_kota', ['id_provinsi' => $provinsi_id])->result();
        echo json_encode(['status' => 'success', 'data' => $kota]);
    }

    // 3. List kecamatan berdasarkan id_kota
    public function get_kecamatan() {
        $kota_id = $this->input->post('id_kota');
        if (!$kota_id) {
            echo json_encode(['status' => 'error', 'message' => 'id_kota wajib diisi']);
            return;
        }

        $kecamatan = $this->db->get_where('reg_kecamatan', ['id_kota' => $kota_id])->result();
        echo json_encode(['status' => 'success', 'data' => $kecamatan]);
    }

    // 4. List desa berdasarkan id_kecamatan
    public function get_desa() {
        $kecamatan_id = $this->input->post('id_kecamatan');
        if (!$kecamatan_id) {
            echo json_encode(['status' => 'error', 'message' => 'id_kecamatan wajib diisi']);
            return;
        }

        $desa = $this->db->get_where('reg_desa', ['id_kecamatan' => $kecamatan_id])->result();
        echo json_encode(['status' => 'success', 'data' => $desa]);
    }



public function laporan_gizi_list()
{
    $data = json_decode(file_get_contents("php://input"), true);

    $id_provinsi   = $data['id_provinsi'] ?? null;
    $id_kabupaten  = $data['id_kabupaten'] ?? null;
    $id_kecamatan  = $data['id_kecamatan'] ?? null;
    $desa_id       = $data['desa_id'] ?? null;
    $tanggal_mulai = $data['tanggal_mulai'] ?? null;
    $tanggal_selesai = $data['tanggal_selesai'] ?? null;

    // kalau tanggal kosong → pakai default bulan ini
    if (!$tanggal_mulai || !$tanggal_selesai) {
        $tanggal_mulai = date("Y-m-01"); // awal bulan
        $tanggal_selesai = date("Y-m-t"); // akhir bulan
    }

    $this->db->select('
        p.pasien_id,
        p.nama,
        p.tanggal_lahir,
        d.nama_desa,
        d.id_kecamatan,
        SUM(n.total_energi_kal) as total_energi,
        SUM(n.total_protein) as total_protein,
        SUM(n.total_lemak_total) as total_lemak,
        SUM(n.total_karbohidrat) as total_karbohidrat,
        SUM(n.total_serat) as total_serat,
        SUM(n.total_air) as total_air
    ');
    $this->db->from('tb_nutrisi_pasien n');
    $this->db->join('tb_pasien p', 'p.pasien_id = n.id_pasien');
    $this->db->join('reg_desa d', 'd.desa_id = p.id_desa');
    $this->db->where('n.tanggal >=', $tanggal_mulai);
    $this->db->where('n.tanggal <=', $tanggal_selesai);

    // filter wilayah kalau ada
    if ($desa_id) {
        $this->db->where('p.id_desa', $desa_id);
    } elseif ($id_kecamatan) {
        $this->db->where('d.id_kecamatan', $id_kecamatan);
    } elseif ($id_kabupaten) {
        $this->db->where('LEFT(d.id_kecamatan,4)=', $id_kabupaten);
    } elseif ($id_provinsi) {
        $this->db->where('LEFT(d.id_kecamatan,2)=', $id_provinsi);
    }
    // kalau semua kosong → tidak ada filter wilayah → ambil semua

    $this->db->group_by('p.pasien_id');
    $rows = $this->db->get()->result();

    $list_anak = [];
    $rekap = ['Kurang'=>0,'Cukup'=>0,'Berlebih'=>0];

    foreach ($rows as $row) {
        $umur_bulan = floor((time() - strtotime($row->tanggal_lahir)) / (30*24*60*60));
        $umur_tahun = floor($umur_bulan / 12);
        $umur_sisa_bulan = $umur_bulan % 12;

        $rujukan = $this->db->where('usia_bulan_min <=', $umur_bulan)
                            ->where('usia_bulan_max >=', $umur_bulan)
                            ->get('tb_nilai_rujuk_nutrisi')->row();

        $status_gizi = "Cukup";
        if ($rujukan) {
            if ($row->total_energi < $rujukan->energi_kal) {
                $status_gizi = "Kurang";
            } elseif ($row->total_energi > $rujukan->energi_kal*1.2) {
                $status_gizi = "Berlebih";
            }
        }

        $rekap[$status_gizi]++;

        $list_anak[] = [
            'pasien_id' => $row->pasien_id,
            'nama'      => $row->nama,
            'umur'      => "{$umur_tahun} th {$umur_sisa_bulan} bln",
            'desa'      => $row->nama_desa,
            'status_gizi' => $status_gizi,
            'total_konsumsi' => [
                'energi'      => (float)$row->total_energi,
                'protein'     => (float)$row->total_protein,
                'lemak'       => (float)$row->total_lemak,
                'karbohidrat' => (float)$row->total_karbohidrat,
                'serat'       => (float)$row->total_serat,
                'air'         => (float)$row->total_air
            ]
        ];
    }

    return $this->output->set_content_type('application/json')
        ->set_output(json_encode([
            'status' => 'ok',
            'filter' => [
                'provinsi' => $id_provinsi,
                'kabupaten' => $id_kabupaten,
                'kecamatan' => $id_kecamatan,
                'desa' => $desa_id,
                'periode' => [$tanggal_mulai, $tanggal_selesai]
            ],
            'rekapitulasi' => $rekap,
            'list_anak' => $list_anak
        ]));
}

public function laporan_zscore_list()
{
    $data = json_decode(file_get_contents("php://input"), true) ?? [];

    $id_provinsi     = $data['id_provinsi']   ?? null;
    $id_kabupaten    = $data['id_kabupaten']  ?? null;
    $id_kecamatan    = $data['id_kecamatan']  ?? null;
    $desa_id         = $data['desa_id']       ?? null;
    $tanggal_mulai   = $data['tanggal_mulai'] ?? null;
    $tanggal_selesai = $data['tanggal_selesai'] ?? null;

    // --- Normalisasi tanggal ke Y-m-d (terima 'YYYY-MM-DD' atau 'YYYYMMDD')
    $normalize = function($s) {
        if (!$s) return null;
        $s = trim($s);
        if (preg_match('/^\d{8}$/', $s)) {
            // YYYYMMDD -> YYYY-MM-DD
            return substr($s,0,4) . '-' . substr($s,4,2) . '-' . substr($s,6,2);
        }
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $s)) return $s;
        // fallback coba strtotime
        $ts = strtotime($s);
        return $ts ? date('Y-m-d', $ts) : null;
    };

    $tanggal_mulai   = $normalize($tanggal_mulai);
    $tanggal_selesai = $normalize($tanggal_selesai);

    // Default: bulan berjalan jika tidak dikirim
    if (!$tanggal_mulai || !$tanggal_selesai) {
        $tanggal_mulai   = date("Y-m-01");
        $tanggal_selesai = date("Y-m-t");
    }

    // --- Subquery: ambil ZScore terbaru per pasien DALAM periode yang dipilih
    // Filter tanggal pakai kolom created_at (ganti jika kolom tanggal pengukuran berbeda)
    $sub = $this->db->select('id_pasien, MAX(created_at) AS max_created', false)
                    ->from('tb_zscore')
                    ->where('DATE(created_at) >=', $tanggal_mulai)
                    ->where('DATE(created_at) <=', $tanggal_selesai)
                    ->group_by('id_pasien')
                    ->get_compiled_select();

    // Join ke baris ZScore-nya dan ke tb_pasien + reg_desa untuk filter wilayah
    $this->db->select('z.id_pasien, z.usia, z.berat_badan, z.tinggi_badan, z.z_bb, z.z_tb,
                       z.kategori_bb, z.kategori_tb, z.created_at,
                       p.nama, p.jenis_kelamin, p.tanggal_lahir,
                       p.id_provinsi, p.id_kota, p.id_kecamatan, p.id_desa,
                       d.nama_desa', false);
    $this->db->from("($sub) t");
    $this->db->join('tb_zscore z', 'z.id_pasien = t.id_pasien AND z.created_at = t.max_created');
    $this->db->join('tb_pasien p', 'p.pasien_id = z.id_pasien', 'left');
    $this->db->join('reg_desa d', 'd.desa_id = p.id_desa', 'left');

    // --- Filter wilayah (ikuti pola laporan gizi)
    if (!empty($desa_id)) {
        $this->db->where('p.id_desa', $desa_id);
    } elseif (!empty($id_kecamatan)) {
        $this->db->where('d.id_kecamatan', $id_kecamatan);
    } elseif (!empty($id_kabupaten)) {
        // id_kecamatan 6 digit, kabupaten = 4 digit prefix
        $this->db->where('LEFT(d.id_kecamatan,4)=', $id_kabupaten);
    } elseif (!empty($id_provinsi)) {
        // provinsi = 2 digit prefix
        $this->db->where('LEFT(d.id_kecamatan,2)=', $id_provinsi);
    }

    $rows = $this->db->order_by('z.id_pasien','asc')->get()->result();

    // --- Susun output
    $rekap_bb = [];
    $rekap_tb = [];
    $list     = [];

    foreach ($rows as $r) {
        $rekap_bb[$r->kategori_bb] = ($rekap_bb[$r->kategori_bb] ?? 0) + 1;
        $rekap_tb[$r->kategori_tb] = ($rekap_tb[$r->kategori_tb] ?? 0) + 1;

        $umur_bulan_approx = null;
        if (!empty($r->tanggal_lahir) && !empty($r->created_at)) {
            $umur_bulan_approx = floor( (strtotime($r->created_at) - strtotime($r->tanggal_lahir)) / (30*24*60*60) );
        }

        $list[] = [
            'pasien_id'       => (int)$r->id_pasien,
            'nama'            => $r->nama,
            'jenis_kelamin'   => $r->jenis_kelamin,
            'usia'            => (int)$r->usia,           // usia dari catatan zscore
            'usia_bulan_approx'=> $umur_bulan_approx,     // kalkulasi dari tgl lahir
            'berat_badan'     => (float)$r->berat_badan,
            'tinggi_badan'    => (float)$r->tinggi_badan,
            'z_bb'            => (float)$r->z_bb,
            'z_tb'            => (float)$r->z_tb,
            'kategori_bb'     => $r->kategori_bb,
            'kategori_tb'     => $r->kategori_tb,
            'created_at'      => $r->created_at,
            // lokasi (buat referensi UI / export)
            'id_provinsi'     => $r->id_provinsi,
            'id_kota'         => $r->id_kota,
            'id_kecamatan'    => $r->id_kecamatan,
            'id_desa'         => $r->id_desa,
            'nama_desa'       => $r->nama_desa,
        ];
    }

    return $this->output->set_content_type('application/json')
        ->set_output(json_encode([
            'status'           => 'ok',
            'filter' => [
                'provinsi' => $id_provinsi,
                'kabupaten'=> $id_kabupaten,
                'kecamatan'=> $id_kecamatan,
                'desa'     => $desa_id,
                'periode'  => [$tanggal_mulai, $tanggal_selesai],
            ],
            'rekapitulasi_bb'  => $rekap_bb,
            'rekapitulasi_tb'  => $rekap_tb,
            'list_pasien'      => $list,
        ]));
}











}
