<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Attendance;
use App\Models\Leave;
use App\Models\Presensi;
use Carbon\Carbon;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Log;

class ReportController extends Controller
{
    public function index()
    {
        return view('admin.check');
    }

    public function sheetReport()
    {
        $employees = User::all();  // Ambil semua data karyawan
        return view('admin.sheet-report', compact('employees'));
    }

    public function generatePDF()
    {
        // PDF generation logic here
        return response()->json(['message' => 'PDF generated']);
    }

    public function checkStore(Request $request)
    {
        // Logic untuk menyimpan data check
        return back()->with('success', 'Data berhasil disimpan');
    }

    public function getData(Request $request)
    {
        try {
            $query = Presensi::query()
                ->select([
                    'presensi.*',
                    'users.name' // menggunakan kolom name dari users
                ])
                ->leftJoin('users', 'presensi.user_id', '=', 'users.id')
                ->orderBy('presensi.created_at', 'desc');

            // Debug query
            \Log::info('SQL Query: ' . $query->toSql());
            \Log::info('Query Bindings: ' . json_encode($query->getBindings()));

            return DataTables::of($query)
                ->addIndexColumn()
                ->addColumn('tanggal', function ($row) {
                    return Carbon::parse($row->created_at)->format('d/m/Y');
                })
                ->addColumn('nama', function ($row) {
                    return $row->name ?? '-'; // menggunakan name dari hasil join
                })
                ->addColumn('status', function ($row) {
                    $badges = [
                        'Hadir' => 'success',
                        'Sakit' => 'warning',
                        'Izin' => 'info',
                        'Alpha' => 'danger'
                    ];
                    $color = $badges[$row->status] ?? 'secondary';
                    return "<span class='badge badge-{$color}'>{$row->status}</span>";
                })
                ->addColumn('jam_masuk', function ($row) {
                    return $row->clock_type == 'in' ? Carbon::parse($row->created_at)->format('H:i:s') : '-';
                })
                ->addColumn('jam_keluar', function ($row) {
                    return $row->clock_type == 'out' ? Carbon::parse($row->created_at)->format('H:i:s') : '-';
                })
                ->addColumn('keterangan', function ($row) {
                    return $row->keterangan ?? '-';
                })
                ->addColumn('lokasi', function ($row) {
                    if ($row->latitude && $row->longitude) {
                        return '<button class="btn btn-info btn-sm" onclick="showLocation('.$row->latitude.', '.$row->longitude.')">
                            <i class="fas fa-map-marker-alt"></i> Lihat Lokasi
                        </button>';
                    }
                    return '-';
                })
                ->rawColumns(['status', 'lokasi'])
                ->make(true);
        } catch (\Exception $e) {
            \Log::error('Error in getData: ' . $e->getMessage());
            return response()->json([
                'error' => true,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function getSummary(Request $request)
    {
        try {
            // Ambil tanggal hari ini
            $today = Carbon::today();
            
            $query = Presensi::query()
                ->whereDate('created_at', $today); // Filter untuk hari ini saja

            // Filter berdasarkan status jika ada
            if ($request->status) {
                $query->where('status', $request->status);
            }

            $summary = [
                'hadir' => (clone $query)->where('status', 'Hadir')
                                       ->where('clock_type', 'in')
                                       ->count(),
                'sakit' => (clone $query)->where('status', 'Sakit')->count(),
                'izin' => (clone $query)->where('status', 'Izin')->count(),
                'absen' => (clone $query)->where('status', 'Alpha')->count(),
            ];

            return response()->json($summary);
        } catch (\Exception $e) {
            Log::error('Error in getSummary: ' . $e->getMessage());
            return response()->json([
                'error' => true,
                'message' => $e->getMessage()
            ], 500);
        }
    }
} 