<?php

namespace App\Http\Controllers\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\Pengajuan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PengajuanController extends Controller
{
    // show pengajuan
    public function showPengajuan()
    {
        // Logic to show pengajuan
        $data = Pengajuan::with('user', 'attendance')->get();
        return view('admin.features.pengajuan.pengajuan', compact('data'));
    }

    // Detail Pengajuan
    public function detailPengajuan($id)
    {
        // Logic to show detail pengajuan
        $data = Pengajuan::with('user', 'attendance')->findOrFail($id);
        return view('admin.features.pengajuan.detail-pengajuan', compact('data'));
    }

    // Update status pengajuan (disetujui/ditolak)
    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'aksi' => 'required|in:disetujui,ditolak',
            'alasan' => 'nullable|string|max:500',
            'jenis_pengajuan' => 'required_if:aksi,disetujui|in:izin,sakit',
        ]);

        $pengajuan = Pengajuan::with('user')->findOrFail($id);

        return DB::transaction(function () use ($request, $pengajuan) {
            $isApproval = $request->input('aksi') === 'disetujui';

            // Jika disetujui: status mengikuti input admin (izin/sakit)
            // Jika ditolak: status menjadi alpha
            $attendanceStatus = $isApproval ? $request->input('jenis_pengajuan') : 'alpha';

            $attendance = $pengajuan->attendance;

            if (!$attendance) {
                $attendance = Attendance::query()->create([
                    'user_id' => $pengajuan->id_user,
                    'date' => $pengajuan->date,
                    'check_in' => null,
                    'check_out' => null,
                    'status' => 'alpha',
                    'notes' => null,
                    'device_info' => null,
                    'location' => null,
                ]);
            }

            $attendance->update([
                'status' => $attendanceStatus,
                'notes' => $isApproval ? ($pengajuan->keterangan ?? null) : ($request->input('alasan') ?? 'Ditolak oleh admin'),
            ]);

            // Hubungkan attendance ke pengajuan
            $pengajuan->id_attendance = $attendance->id;
            $pengajuan->status = $isApproval ? 'disetujui' : 'ditolak';
            $pengajuan->save();

            return redirect()
                ->route('admin.pengajuan')
                ->with('success', 'Status pengajuan ' . ($isApproval ? 'disetujui' : 'ditolak') . '.');
        });
    }
}
