<?php

namespace App\Http\Controllers\Mobile;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class RiwayatController extends Controller
{
    public function index($userId)
    {
        // ========================
        // DATA ABSENSI
        // ========================
        $absensi = DB::table('attendances')
            ->where('user_id', $userId)
            ->select(
                DB::raw("
                    CASE 
                        WHEN check_in IS NOT NULL THEN 'Hadir'
                        ELSE 'Tidak Hadir'
                    END as jenis
                "),
                DB::raw("DATE_FORMAT(date, '%d %b %Y') as tanggal"),
                DB::raw("
                    CONCAT(
                        IFNULL(TIME_FORMAT(check_in, '%H:%i'), '-'),
                        ' - ',
                        IFNULL(TIME_FORMAT(check_out, '%H:%i'), '-')
                    ) as jam
                "),
                DB::raw("'hadir' as icon"),
                DB::raw("status as status_validasi"),
                'date as sort_date'
            );

        // ========================
        // DATA PENGAJUAN (IZIN / SAKIT / DLL)
        // ========================
        $pengajuan = DB::table('pengajuan')
            ->where('id_user', $userId)
            ->select(
                'jenis',
                DB::raw("DATE_FORMAT(date, '%d %b %Y') as tanggal"),
                DB::raw("'-' as jam"),
                DB::raw("'izin' as icon"),
                'status as status_validasi',
                'date as sort_date'
            );

        // ========================
        // UNION DATA
        // ========================
        $riwayat = $absensi
            ->unionAll($pengajuan)
            ->orderBy('sort_date', 'desc')
            ->get();

        return response()->json([
            'ok' => true,
            'data' => $riwayat
        ]);
    }
}