<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Attendance;
use App\Models\Leave;
use App\Models\Announcement;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\View;

class DashboardController extends Controller
{
    public function index()
    {
        try {
            // Get total karyawan (excluding admin)
            $totalKaryawan = DB::table('users')
                ->where('role', '!=', 'admin')
                ->count();

            // Get current month's attendance count (hanya clock in)
            $currentMonth = Carbon::now()->format('F Y');
            $totalPresensi = DB::table('presensi')
                ->where('clock_type', 'in')
                ->count();

            // Get total cuti yang diajukan
            $totalCuti = DB::table('cuti')->count();

            // Get latest announcements
            $announcements = Announcement::orderBy('created_at', 'desc')
                ->take(5)
                ->get();

            // Get recent attendance activities
            $recentAttendance = DB::table('presensi as p')
                ->join('users as u', 'p.user_id', '=', 'u.id')
                ->select(
                    'p.id',
                    'u.name',
                    'p.clock_type',
                    'p.status',
                    'p.created_at'
                )
                ->orderBy('p.created_at', 'desc')
                ->limit(10)
                ->get();

            // Get attendance statistics (hanya clock in)
            $attendanceStats = [
                'hadir' => DB::table('presensi')
                    ->whereIn('status', ['Hadir', 'Terlambat'])
                    ->where('clock_type', 'in')
                    ->whereMonth('created_at', Carbon::now()->month)
                    ->whereYear('created_at', Carbon::now()->year)
                    ->count(),
                'total_karyawan' => $totalKaryawan
            ];

            // Get leave statistics
            $leaveStats = [
                'pending' => DB::table('cuti')->where('status', 'Pending')->count(),
                'approved' => DB::table('cuti')->where('status', 'Approved')->count(),
                'rejected' => DB::table('cuti')->where('status', 'Rejected')->count()
            ];

            return View::make('admin.dashboard', [
                'totalPresensi' => $totalPresensi,
                'totalCuti' => $totalCuti,
                'currentMonth' => $currentMonth,
                'announcements' => $announcements,
                'recentAttendance' => $recentAttendance,
                'attendanceStats' => $attendanceStats,
                'leaveStats' => $leaveStats
            ]);

        } catch (\Exception $e) {
            Log::error('Error in Dashboard:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return View::make('admin.dashboard', [
                'totalPresensi' => 0,
                'totalCuti' => 0,
                'currentMonth' => Carbon::now()->format('F Y'),
                'announcements' => collect([]),
                'recentAttendance' => collect([]),
                'attendanceStats' => [
                    'hadir' => 0,
                    'total_karyawan' => 0
                ],
                'leaveStats' => [
                    'pending' => 0,
                    'approved' => 0,
                    'rejected' => 0
                ]
            ])->with('error', 'Terjadi kesalahan saat memuat data');
        }
    }

    public function getStats()
    {
        try {
            $stats = [
                'total_users' => DB::table('users')->whereNotIn('role', ['admin'])->count(),
                'total_presensi' => DB::table('presensi')
                    ->where('clock_type', 'in')
                    ->count(),
                'total_cuti' => DB::table('cuti')->count()
            ];

            return response()->json([
                'status' => 'success',
                'data' => $stats
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching dashboard stats: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch dashboard statistics'
            ], 500);
        }
    }
} 