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

class User extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        // Cek session login
        if (!$this->session->userdata('logged_in')) {
            $this->session->set_flashdata('error', 'Silakan login dulu.');
            redirect('auth');
        }

        // Cek role user
        if ($this->session->userdata('role') !== 'user') {
            $this->session->set_flashdata('error', 'Akses ditolak, hanya untuk user!');
            redirect('auth');
        }
    }

    public function index()
{
    $this->load->model('Form_model', 'form');
    $user_name = strtoupper($this->session->userdata('name'));

    // Hitung Input Hari Ini (berdasarkan nama petugas)
    $today = date('Y-m-d');
    $this->db->where('petugas', $user_name);
    $this->db->where('DATE(created_at)', $today);
    $input_hari_ini = $this->db->count_all_results('form_gesek');

    // Hitung Total Bulan Ini
    $bulan = date('m');
    $tahun = date('Y');
    $this->db->where('petugas', $user_name);
    $this->db->where('MONTH(created_at)', $bulan);
    $this->db->where('YEAR(created_at)', $tahun);
    $total_bulan_ini = $this->db->count_all_results('form_gesek');

    // Ambil data terbaru (max 10)
    $this->db->where('petugas', $user_name);
    $this->db->order_by('created_at', 'DESC');
    $latest_forms = $this->db->limit(10)->get('form_gesek')->result_array();

    $data = [
        'title' => 'Dashboard User - NOKA NOSIN',
        'content' => 'user/dashboard',
        'input_hari_ini' => $input_hari_ini,
        'total_bulan_ini' => $total_bulan_ini,
        'latest_forms' => $latest_forms
    ];

    $this->load->view('template', $data);
}

}
