<?php

namespace App\Controllers\User;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\PengajuanModel;

class Dashboard extends BaseController
{
    public function index()
    {
        $pengajuanModel = new PengajuanModel();
        $userId = session()->get('id');

        // Combined history with joined employee names based on target_nip
        $history = $pengajuanModel->select('pengajuan.*, pegawai.nama as target_nama, pegawai.nip_baru as target_nip')
                                 ->join('pegawai', 'pegawai.nip_baru = pengajuan.target_nip', 'left')
                                 ->groupStart()
                                    ->where('pengajuan.user_id', $userId)
                                    ->orWhere('pengajuan.created_by', $userId)
                                 ->groupEnd()
                                 ->orderBy('pengajuan.created_at', 'DESC')
                                 ->findAll();

        $data = [
            'total_pengajuan' => count($history),
            'pending_pengajuan' => array_reduce($history, function($carry, $item) {
                return $carry + ($item['status'] == 'PENDING' ? 1 : 0);
            }, 0),
            'waiting_sk' => array_reduce($history, function($carry, $item) {
                return $carry + ($item['status'] == 'WAITING_SK' ? 1 : 0);
            }, 0),
            'sk_finish' => array_reduce($history, function($carry, $item) {
                return $carry + ($item['status'] == 'SK_FINISH' ? 1 : 0);
            }, 0),
            'history_pengajuan' => $history,
        ];

        return view('user/dashboard', $data);
    }
}
