<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Services\AttendanceService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

class AttendanceExportController extends Controller
{
    public function __construct(
        private readonly AttendanceService $attendanceService
    ) {}

    public function export(Request $request): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        $format = $request->get('format', 'csv'); // csv, excel, pdf
        $startDate = $request->get('start_date');
        $endDate = $request->get('end_date');
        $date = $request->get('date');
        $departmentId = $request->get('department_id');
        $userId = $request->get('user_id');
        $search = $request->get('search');
        $status = $request->get('status');

        // Build query
        $user = $request->user();
        $query = Attendance::with(['user'])
            ->orderBy('date', 'desc')
            ->orderBy('clock_in', 'desc');

        if (! $user->isAdmin() && ! $user->isSuperAdmin()) {
            $query->where('user_id', $user->id);
        }

        if ($startDate) {
            $query->where('date', '>=', $startDate);
        }
        if ($endDate) {
            $query->where('date', '<=', $endDate);
        }
        if ($date) {
            $query->whereDate('date', $date);
        }
        if ($userId) {
            $query->where('user_id', $userId);
        }
        if ($departmentId) {
            $query->whereHas('user.employeeProfile', function ($q) use ($departmentId) {
                $q->where('department_id', $departmentId);
            });
        }
        if ($search) {
            $query->whereHas('user', function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }
        if ($status) {
            $query->where('status', $status);
        }

        $attendances = $query->get();

        return match ($format) {
            'csv' => $this->exportCsv($attendances),
            'pdf' => $this->exportPdf($attendances),
            default => $this->exportCsv($attendances),
        };
    }

    private function exportCsv($attendances): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        $filename = 'attendance_export_'.now()->format('Y-m-d_His').'.csv';

        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
            'Pragma' => 'no-cache',
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
            'Expires' => '0',
        ];

        $callback = function () use ($attendances) {
            $file = fopen('php://output', 'w');

            // Headers
            fputcsv($file, [
                'Employee Name',
                'Email',
                'Date',
                'Clock In',
                'Clock Out',
                'Total Hours',
                'Break Time (min)',
                'Work Mode',
                'Status',
                'In Type',
                'Out Type',
                'Notes',
            ]);

            // Data
            foreach ($attendances as $attendance) {
                $totalHours = 0;
                if ($attendance->clock_in && $attendance->clock_out) {
                    $clockIn = Carbon::parse($attendance->clock_in);
                    $clockOut = Carbon::parse($attendance->clock_out);
                    $totalSeconds = $clockOut->diffInSeconds($clockIn);
                    $totalSeconds -= ($attendance->total_break_seconds ?? 0);
                    $totalHours = round($totalSeconds / 3600, 2);
                }

                fputcsv($file, [
                    $attendance->user->name ?? 'N/A',
                    $attendance->user->email ?? 'N/A',
                    $attendance->date,
                    $attendance->clock_in ? Carbon::parse($attendance->clock_in)->format('h:i A') : '-',
                    $attendance->clock_out ? Carbon::parse($attendance->clock_out)->format('h:i A') : '-',
                    $totalHours,
                    round(($attendance->total_break_seconds ?? 0) / 60),
                    $attendance->work_mode ?? 'office',
                    $attendance->status ?? 'pending',
                    $attendance->in_type ?? 'auto',
                    $attendance->out_type ?? 'auto',
                    $attendance->in_note ?? '',
                ]);
            }

            fclose($file);
        };

        return Response::stream($callback, 200, $headers);
    }

    private function exportPdf($attendances): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        // For now, return CSV. PDF export would require DomPDF or similar
        // TODO: Implement PDF export using DomPDF
        return $this->exportCsv($attendances);
    }
}
