<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Cuti;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class CutiController extends Controller
{
    public function getUserLeaves($userId)
    {
        try {
            // Pastikan user hanya bisa melihat data cutinya sendiri
            if (Auth::id() != $userId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses untuk melihat data ini'
                ], 403);
            }

            $leaves = Cuti::where('user_id', $userId)
                        ->orderBy('created_at', 'desc')
                        ->get();

            return response()->json([
                'success' => true,
                'data' => $leaves->map(function ($cuti) {
                    return [
                        'id' => $cuti->id,
                        'user_id' => $cuti->user_id,
                        'tanggal_mulai' => $cuti->tanggal_mulai,
                        'tanggal_selesai' => $cuti->tanggal_selesai,
                        'jenis_cuti' => $cuti->jenis_cuti,
                        'keterangan' => $cuti->keterangan,
                        'status' => $cuti->status,
                        'file_pdf' => $cuti->file_pdf,
                        'approved_by' => $cuti->approved_by,
                        'approved_at' => $cuti->approved_at,
                        'rejected_by' => $cuti->rejected_by,
                        'rejected_at' => $cuti->rejected_at,
                        'created_at' => $cuti->created_at,
                        'updated_at' => $cuti->updated_at,
                    ];
                })
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil data cuti: ' . $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
    {
        try {
            $request->validate([
                'tanggal_mulai' => 'required|date',
                'tanggal_selesai' => 'required|date|after_or_equal:tanggal_mulai',
                'jenis_cuti' => 'required|string',
                'keterangan' => 'required|string',
                'file_pdf' => 'nullable|mimes:pdf|max:2048'
            ]);

            $cuti = new Cuti();
            $cuti->user_id = Auth::id();
            $cuti->tanggal_mulai = $request->tanggal_mulai;
            $cuti->tanggal_selesai = $request->tanggal_selesai;
            $cuti->jenis_cuti = $request->jenis_cuti;
            $cuti->keterangan = $request->keterangan;
            $cuti->status = 'Pending';

            if ($request->hasFile('file_pdf')) {
                $file = $request->file('file_pdf');
                $filename = time() . '_' . $file->getClientOriginalName();
                $file->storeAs('public/cuti_files', $filename);
                $cuti->file_pdf = 'cuti_files/' . $filename;
            }

            $cuti->save();

            return response()->json([
                'success' => true,
                'message' => 'Pengajuan cuti berhasil disimpan',
                'data' => $cuti
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menyimpan pengajuan cuti: ' . $e->getMessage()
            ], 500);
        }
    }

    public function show($id)
    {
        try {
            $cuti = Cuti::findOrFail($id);
            
            // Pastikan user hanya bisa melihat data cutinya sendiri
            if (Auth::id() != $cuti->user_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses untuk melihat data ini'
                ], 403);
            }

            return response()->json([
                'success' => true,
                'data' => $cuti
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil detail cuti: ' . $e->getMessage()
            ], 500);
        }
    }

    public function index(Request $request)
    {
        $userId = $request->input('user_id');
        
        // Debug logs
        Log::info('CutiController::index', [
            'Auth::id()' => Auth::id(),
            'requested_user_id' => $userId,
            'headers' => $request->header(),
        ]);
        
        // Pastikan user hanya bisa melihat data cutinya sendiri
        if (Auth::id() != $userId) {
            Log::warning('Unauthorized access attempt', [
                'Auth::id()' => Auth::id(), 
                'requested_user_id' => $userId
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Anda Belum Mengajukan Cuti'
            ], 403);
        }
        
        // Pastikan userId digunakan dalam query
        $cutiList = Cuti::where('user_id', $userId)->get();
        
        Log::info('Returning cuti list', ['count' => $cutiList->count()]);
        
        return response()->json(['data' => $cutiList]);
    }

    public function getAllCuti()
    {
        try {
            // Ambil ID user yang sedang login
            $userId = Auth::id();
            
            // Log untuk debugging
            Log::info('getAllCuti called', ['user_id' => $userId]);
            
            // Filter cuti berdasarkan user_id
            $cuti = Cuti::where('user_id', $userId)
                       ->orderBy('created_at', 'desc')
                       ->get();

            return response()->json([
                'success' => true,
                'message' => 'Data cuti berhasil diambil',
                'data' => $cuti
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching all cuti: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil data cuti'
            ], 500);
        }
    }

    public function updateStatus(Request $request, $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'status' => 'required|in:Approved,Rejected,Pending'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Status tidak valid',
                    'errors' => $validator->errors()
                ], 422);
            }

            $cuti = Cuti::find($id);
            if (!$cuti) {
                return response()->json([
                    'success' => false,
                    'message' => 'Data cuti tidak ditemukan'
                ], 404);
            }

            $cuti->status = $request->status;
            $cuti->save();

            return response()->json([
                'success' => true,
                'message' => 'Status cuti berhasil diperbarui',
                'data' => $cuti
            ]);
        } catch (\Exception $e) {
            Log::error('Error updating cuti status: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal memperbarui status cuti'
            ], 500);
        }
    }

    public function getStats()
    {
        try {
            $user = auth()->user();
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized'
                ], 401);
            }

            // Hitung total pengajuan cuti untuk user yang login
            $totalCuti = Cuti::where('user_id', $user->id)->count();

            Log::info('Cuti stats for user ' . $user->id . ':', ['total' => $totalCuti]);

            return response()->json([
                'success' => true,
                'message' => 'Data statistik cuti berhasil diambil',
                'data' => [
                    'total_cuti' => $totalCuti
                ]
            ], 200);

        } catch (\Exception $e) {
            Log::error('Error getting cuti stats: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ], 500);
        }
    }
}