<?php
// app/Http/Controllers/AdminController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash; // Add this import
use App\Models\Registration;
use App\Models\Setting;
use App\Models\Holiday;
use App\Exports\RegistrationsExport;
use Maatwebsite\Excel\Facades\Excel;
use Carbon\Carbon; // Tambahkan ini

class AdminController extends Controller
{
    public function dashboard(Request $request)
    {
        $search = $request->input('search', '');
        
        // Get registrations count
        $registrationsToday = Registration::whereDate('visit_date', Carbon::today())->count();
        $totalRegistrationsThisMonth = Registration::whereBetween('visit_date', [
            Carbon::now()->startOfMonth(),
            Carbon::now()->endOfMonth()
        ])->count();

        // Get today's registrations with search and pagination
        $todayRegistrations = Registration::whereDate('visit_date', Carbon::today())
            ->when($search, function($query) use ($search) {
                $query->where(function($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('nik', 'like', "%{$search}%")
                      ->orWhere('booking_code', 'like', "%{$search}%");
                });
            })
            ->orderBy('visit_time')
            ->paginate(10);

        return view('admin.dashboard', compact(
            'search',
            'registrationsToday', 
            'totalRegistrationsThisMonth',
            'todayRegistrations'
        ));
    }

    public function settings()
    {
        $settings = Setting::pluck('value', 'key')->all();
        $holidays = Holiday::orderBy('date')->get();
        return view('admin.settings', compact('settings', 'holidays'));
    }

    public function updateSettings(Request $request)
    {
        $request->validate([
            'max_daily_queue' => 'required|numeric|min:1',
            'old_password' => 'nullable',
            'new_password' => 'nullable|min:6|confirmed|required_with:old_password'
        ]);

        // Update max queue setting
        Setting::updateOrCreate(
            ['key' => 'max_daily_queue'],
            ['value' => $request->max_daily_queue]
        );

        // Update password if provided
        if ($request->filled('old_password')) {
            if (!Hash::check($request->old_password, Auth::guard('admin')->user()->password)) {
                return back()->withErrors(['old_password' => 'Password lama tidak sesuai']);
            }

            $admin = Auth::guard('admin')->user();
            $admin->password = Hash::make($request->new_password);
            $admin->save();
        }

        return back()->with('success', 'Pengaturan berhasil diperbarui');
    }

    public function storeHoliday(Request $request)
    {
        $request->validate([
            'date' => 'required|date|after_or_equal:today',
            'description' => 'required'
        ]);

        Holiday::create($request->all());
        return back()->with('success', 'Hari libur berhasil ditambahkan');
    }

    public function deleteHoliday($id)
    {
        Holiday::destroy($id);
        return back()->with('success', 'Hari libur berhasil dihapus');
    }

    public function reports(Request $request)
    {
        $query = Registration::query();

        // Date range filter
        if ($request->filled('start_date')) {
            $query->whereDate('visit_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('visit_date', '<=', $request->end_date);
        }

        // Search filter
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('nik', 'like', "%{$search}%")
                  ->orWhere('booking_code', 'like', "%{$search}%");
            });
        }

        $registrations = $query->orderBy('visit_date', 'desc')
                              ->orderBy('visit_time', 'asc')
                              ->paginate(15);

        return view('admin.reports', compact('registrations'));
    }

    public function exportReport(Request $request)
    {
        $startDate = $request->start_date;
        $endDate = $request->end_date;
        $search = $request->search;

        return Excel::download(
            new RegistrationsExport($startDate, $endDate, $search),
            'registrations.xlsx'
        );
    }

    public function checkQuota($date)
    {
        // Set timezone explicitly
        date_default_timezone_set('Asia/Jakarta');
        
        // Convert date to Jakarta timezone for comparison
        $jakartaDate = Carbon::parse($date)
            ->timezone('Asia/Jakarta')
            ->startOfDay();

        // Check holiday using Jakarta date
        if(Holiday::whereDate('date', $jakartaDate->format('Y-m-d'))->exists()) {
            return response()->json(['available' => false, 'message' => 'Hari Libur']);
        }

        $maxDaily = Setting::where('key', 'max_daily_queue')->first()->value ?? 50;
        $count = Registration::whereDate('visit_date', $jakartaDate->format('Y-m-d'))->count();
        
        return response()->json([
            'available' => $count < $maxDaily,
            'date' => $jakartaDate->format('Y-m-d'), // Debug info
            'count' => $count,
            'maxDaily' => $maxDaily
        ]);
    }

    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        
        return redirect('/'); // Redirect to home page
    }

    public function loginForm()
    {
        if (Auth::guard('admin')->check()) {
            return redirect()->route('admin.dashboard');
        }
        return view('admin.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'username' => 'required',
            'password' => 'required'
        ]);

        if (Auth::guard('admin')->attempt($credentials)) {
            $request->session()->regenerate();
            return redirect()->intended(route('admin.dashboard'));
        }

        return back()->withErrors([
            'username' => 'Username atau password salah.',
        ]);
    }

    public function serveKtpImage(Registration $registration)
    {
    if (!Auth::guard('admin')->check()) {
        return redirect()->route('admin.login');
    }

    if (!$registration->ktp_image) {
        abort(404);
    }

    // Fix path construction
    $path = storage_path('app/private/' . $registration->ktp_image);

    \Log::info('Serving KTP Image:', [
        'path' => $path,
        'exists' => file_exists($path),
        'registration_path' => $registration->ktp_image
    ]);

    if (!file_exists($path)) {
        abort(404);
    }

    return response()->file($path);
}

public function downloadKtp(Registration $registration)
{
    if (!Auth::guard('admin')->check()) {
        return redirect()->route('admin.login');
    }

    if (!$registration->ktp_image) {
        return back()->with('error', 'File KTP tidak ditemukan');
    }

    // Fix path construction
    $path = storage_path('app/private/' . $registration->ktp_image);

    if (!file_exists($path)) {
        return back()->with('error', 'File KTP tidak ditemukan');
    }

    return response()->download($path, basename($registration->ktp_image));
}
}