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

class Dashboard extends MY_Controller    {

  public function __construct(){
    parent::__construct();
    $this->load->model('Dashboard_model');
    $this->load->library('session');
    $this->load->helper(['url','html']);

    // guard login
    if(!$this->session->userdata('logged_in')){
			//  $this->load->disable_layout();   
      redirect('welcome');
    }

    // timezone
    date_default_timezone_set('Asia/Jakarta');
  }

  public function index(){
    // KPI
    $total_pasien              = $this->Dashboard_model->total_pasien();
    $total_pendaftaran         = $this->Dashboard_model->total_pendaftaran();
    $total_pendaftaran_poli    = $this->Dashboard_model->total_pendaftaran_poli();

    // --- Registrasi 7 hari terakhir: normalisasi ke tiap hari agar tidak bolong
    $raw7 = $this->Dashboard_model->registrasi_last_7_days();
    $map7 = [];
    foreach ($raw7 as $r) { $map7[$r['tgl']] = (int)$r['jml']; }
    $labels7 = [];
    $values7 = [];
    for ($i=6; $i>=0; $i--) {
      $d = date('Y-m-d', strtotime("-$i days"));
      $labels7[] = date('d/m', strtotime($d));
      $values7[] = isset($map7[$d]) ? (int)$map7[$d] : 0;
    }

    // --- Pasien per bulan 12 bulan terakhir: normalisasi tiap bulan
    $raw12 = $this->Dashboard_model->pasien_last_12_months();
    $map12 = [];
    foreach ($raw12 as $r) { $map12[$r['ym']] = (int)$r['jml']; }
    $labels12 = [];
    $values12 = [];
    for ($m=11; $m>=0; $m--) {
      $ym = date('Y-m', strtotime("-$m months"));
      $labels12[] = date('M Y', strtotime($ym.'-01'));
      $values12[] = isset($map12[$ym]) ? (int)$map12[$ym] : 0;
    }

    $data = [
      'nama'                    => $this->session->userdata('nama_lengkap'),
      'total_pasien'            => $total_pasien,
      'total_pendaftaran'       => $total_pendaftaran,
      'total_pendaftaran_poli'  => $total_pendaftaran_poli,
      'labels7'                 => $labels7,
      'values7'                 => $values7,
      'labels12'                => $labels12,
      'values12'                => $values12,
			'title'										=>'Dashboard',
    ];
    // $this->load->view('dashboard', $data);
		 $this->render('dashboard', $data); 
  }
}
