<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Redirect;
use App\Models\Employee;
use App\Models\Attendance;
use App\Models\Leave;
use App\Models\Presensi;
use Carbon\Carbon;
use Yajra\DataTables\Facades\DataTables;
use Flash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CheckController extends Controller
{
    public function index(Request $request)
    {
        try {
            // Ambil parameter filter jika ada
            $month = $request->has('month') ? Carbon::parse($request->month) : Carbon::now();
            $statusFilter = $request->status;
            
            // Log untuk debugging
            Log::info('Filter parameters:', [
                'month' => $month->format('Y-m'),
                'status' => $statusFilter
            ]);
            
            // Query menggunakan model Presensi dengan relasi user
            $query = Presensi::with('user')
                ->select([
                    'id',
                    'created_at',
                    'status',
                    'keterangan',
                    'clock_type',
                    'user_id',
                    'foto',
                    'file_pdf'
                ]);
                
            // Filter berdasarkan bulan
            $query->whereMonth('created_at', $month->month)
                  ->whereYear('created_at', $month->year);
                
            // Filter berdasarkan status jika ada
            if ($statusFilter) {
                switch ($statusFilter) {
                    case 'Hadir':
                        $query->whereIn('status', ['Hadir', 'Masuk']);
                        break;
                    case 'Terlambat':
                        $query->where('status', 'Terlambat');
                        break;
                    case 'Sakit':
                        $query->where('status', 'Sakit');
                        break;
                    case 'Izin':
                        $query->where('status', 'Izin');
                        break;
                    default:
                        $query->where('status', $statusFilter);
                }
            }
            
            // Log query untuk debugging
            Log::info('SQL Query:', [
                'sql' => $query->toSql(),
                'bindings' => $query->getBindings()
            ]);
            
            $presensis = $query->orderBy('created_at', 'desc')->get();
            
            // Log hasil query
            Log::info('Query results count:', ['count' => $presensis->count()]);
            
            // Hitung statistik untuk bulan yang dipilih
            $hadir = Presensi::whereMonth('created_at', $month->month)
                ->whereYear('created_at', $month->year)
                ->whereIn('status', ['Hadir', 'Terlambat'])
                ->where('clock_type', ['in', 'out'])
                ->count();
                
            $sakit = Presensi::whereMonth('created_at', $month->month)
                ->whereYear('created_at', $month->year)
                ->where('status', 'Sakit')
                ->count();
                
            $izin = Presensi::whereMonth('created_at', $month->month)
                ->whereYear('created_at', $month->year)
                ->where('status', 'Izin')
                ->count();
                
            return View::make('admin.check', compact('presensis', 'hadir', 'sakit', 'izin', 'month'));
            
        } catch (\Exception $e) {
            Log::error('Error in index: ' . $e->getMessage());
            Log::error('Stack trace: ' . $e->getTraceAsString());
            return redirect()->back()->with('error', 'Terjadi kesalahan saat memuat data');
        }
    }

    public function getData(Request $request)
    {
        try {
            Log::info('getData called with:', ['request' => $request->all()]);
            
            if (!$request->has('month')) {
                throw new \Exception('Month parameter is required');
            }

            $month = Carbon::parse($request->month);
            $status = $request->status;

            Log::info('Parsed month:', ['month' => $month->format('Y-m')]);

            // Dapatkan semua data presensi untuk bulan yang dipilih
            $query = DB::table('presensi')
                ->join('users', 'presensi.user_id', '=', 'users.id')
                ->select([
                    'presensi.id',
                    'presensi.created_at',
                    'presensi.status',
                    'presensi.keterangan',
                    'presensi.clock_type',
                    'presensi.user_id',
                    'presensi.foto',
                    'presensi.file_pdf',
                    'users.name'
                ])
                ->whereMonth('presensi.created_at', $month->month)
                ->whereYear('presensi.created_at', $month->year);

            if ($status) {
                switch ($status) {
                    case 'Hadir':
                        $query->whereIn('presensi.status', ['Hadir', 'Masuk']);
                        break;
                    case 'Terlambat':
                        $query->where('presensi.status', 'Terlambat');
                        break;
                    case 'Sakit':
                        $query->where('presensi.status', 'Sakit');
                        break;
                    case 'Izin':
                        $query->where('presensi.status', 'Izin');
                        break;
                    default:
                        $query->where('presensi.status', $status);
                }
            }

            // Log the SQL query
            Log::info('SQL Query:', [
                'sql' => $query->toSql(),
                'bindings' => $query->getBindings()
            ]);

            $data = $query->get();

            Log::info('Raw data count:', ['count' => $data->count()]);
            
            // Debug data yang ditemukan
            if ($data->count() > 0) {
                Log::info('Sample data:', ['first_item' => $data->first()]);
            } else {
                Log::warning('No data found for the query');
                return DataTables::of([])->make(true);
            }

            // Kelompokkan data berdasarkan user_id dan tanggal
            $groupedData = [];
            foreach ($data as $row) {
                $date = Carbon::parse($row->created_at)->format('Y-m-d');
                $key = $row->user_id . '_' . $date;
                
                if (!isset($groupedData[$key])) {
                    $groupedData[$key] = [
                        'tanggal' => $date,
                        'nama' => $row->name,
                        'status' => $row->status === 'Masuk' ? 'Hadir' : $row->status,
                        'jam_masuk' => '-',
                        'jam_keluar' => '-',
                        'keterangan' => $row->keterangan,
                        'foto' => $row->foto,
                        'file_pdf' => $row->file_pdf
                    ];
                }
                
                // Simpan jam masuk dan jam keluar
                if ($row->clock_type === 'in') {
                    $groupedData[$key]['jam_masuk'] = Carbon::parse($row->created_at)->format('H:i:s');
                    // Pastikan foto tersimpan
                    if ($row->foto) {
                        $groupedData[$key]['foto'] = $row->foto;
                    }
                } else if ($row->clock_type === 'out') {
                    $groupedData[$key]['jam_keluar'] = Carbon::parse($row->created_at)->format('H:i:s');
                }
                
                // Simpan file_pdf jika ada
                if ($row->file_pdf) {
                    $groupedData[$key]['file_pdf'] = $row->file_pdf;
                }
            }

            // Konversi ke array untuk DataTables
            $result = [];
            $index = 1;
            foreach ($groupedData as $item) {
                $item['DT_RowIndex'] = $index++;
                $result[] = $item;
            }

            Log::info('Result data count:', ['count' => count($result)]);
            if (count($result) > 0) {
                Log::info('Result data sample:', ['first_item' => $result[0]]);
            }

            return DataTables::of($result)
                ->rawColumns(['status'])
                ->make(true);

        } catch (\Exception $e) {
            Log::error('Error in getData: ' . $e->getMessage());
            Log::error('Stack trace: ' . $e->getTraceAsString());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function getSummary(Request $request)
    {
        try {
            if (!$request->has('month')) {
                throw new \Exception('Month parameter is required');
            }

            $month = Carbon::parse($request->month);
            
            // Query untuk menghitung data
            $query = DB::table('presensi')
                ->whereMonth('created_at', $month->month)
                ->whereYear('created_at', $month->year);
            
            // Log query untuk debugging
            Log::info('Summary query:', [
                'month' => $month->format('Y-m'),
                'sql' => $query->toSql(),
                'bindings' => $query->getBindings()
            ]);
            
            // Hitung total hadir (termasuk status 'Masuk')
            $hadir = (clone $query)
                ->whereIn('status', ['Hadir', 'Terlambat'])
                ->where('clock_type', ['in', 'out'])
                ->count();
                
            // Untuk sakit dan izin, tidak perlu memeriksa clock_type
            $sakit = (clone $query)
                ->where('status', 'Sakit')
                ->count();
                
            $izin = (clone $query)
                ->where('status', 'Izin')
                ->count();

            Log::info('Summary data:', [
                'month' => $month->format('Y-m'),
                'hadir' => $hadir,
                'sakit' => $sakit,
                'izin' => $izin
            ]);

            return response()->json([
                'success' => true,
                'data' => [
                    'hadir' => $hadir,
                    'sakit' => $sakit,
                    'izin' => $izin
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Error in getSummary: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function CheckStore(Request $request)
    {
        if (isset($request->attd)) {
            foreach ($request->attd as $keys => $values) {
                foreach ($values as $key => $value) {
                    if ($employee = Employee::where('id', request('emp_id'))->first()) {
                        if (
                            !Attendance::where('attendance_date', $keys)
                                ->where('emp_id', $key)
                                ->where('type', 0)
                                ->first()
                        ) {
                            $data = new Attendance();
                            
                            $data->emp_id = $key;
                            $emp_req = Employee::where('id', $data->emp_id)->first();
                            $data->attendance_time = date('H:i:s', strtotime($emp_req->schedules->first()->time_in));
                            $data->attendance_date = $keys;
                            $data->save();
                        }
                    }
                }
            }
        }
        if (isset($request->leave)) {
            foreach ($request->leave as $keys => $values) {
                foreach ($values as $key => $value) {
                    if ($employee = Employee::where('id', request('emp_id'))->first()) {
                        if (
                            !Leave::where('leave_date', $keys)
                                ->where('emp_id', $key)
                                ->where('type', 1)
                                ->first()
                        ) {
                            $data = new Leave();
                            $data->emp_id = $key;
                            $emp_req = Employee::where('id', $data->emp_id)->first();
                            $data->leave_time = $emp_req->schedules->first()->time_out;
                            $data->leave_date = $keys;
                            $data->save();
                        }
                    }
                }
            }
        }
        Flash::success('Success', 'You have successfully submited the attendance !');
        return Redirect::back();
    }

    public function sheetReport()
    {
        return View::make('admin.sheet-report')->with(['employees' => Employee::all()]);
    }
}
