<?php

namespace App\Http\Controllers\Customers;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Attendance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class AttendanceReportController extends Controller
{
    /**
     * عرض صفحة تقارير الحضور
     */
    public function index()
    {
        $customers = Customer::active()->orderBy('name')->get();

        return view('attendances.reports.index', compact('customers'));
    }

    /**
     * فلترة تقرير الحضور
     */
    public function filter(Request $request)
    {
        try {
            $query = Attendance::with(['customer', 'subscription.plan', 'checkedInBy', 'checkedOutBy']);

            // فلترة حسب العميل
            if ($request->filled('customer_id')) {
                $query->where('customer_id', $request->customer_id);
            }

            // فلترة حسب التاريخ
            if ($request->filled('from_date')) {
                $query->whereDate('check_in', '>=', $request->from_date);
            }

            if ($request->filled('to_date')) {
                $query->whereDate('check_in', '<=', $request->to_date);
            }

            // فلترة حسب الشهر
            if ($request->filled('month')) {
                $query->whereMonth('check_in', $request->month)
                    ->whereYear('check_in', $request->year ?? now()->year);
            }

            // فلترة حسب نوع الحضور
            if ($request->filled('type')) {
                $query->where('type', $request->type);
            }

            // فلترة حسب الحالة
            if ($request->filled('status')) {
                $query->where('status', $request->status);
            }

            $attendances = $query->latest('check_in')->get();

            // إحصائيات التقرير
            $summary = [
                'total_attendances' => $attendances->count(),
                'total_checked_in' => $attendances->where('status', 'checked_in')->count(),
                'total_checked_out' => $attendances->where('status', 'checked_out')->count(),
                'total_duration' => $attendances->sum('duration'),
                'avg_duration' => $attendances->avg('duration'),
                'by_type' => $attendances->groupBy('type')
                    ->map(function($group) {
                        return [
                            'count' => $group->count(),
                            'duration' => $group->sum('duration')
                        ];
                    }),
                'by_day' => $attendances->groupBy(function($item) {
                    return $item->check_in->format('Y-m-d');
                })->map(function($group) {
                    return [
                        'count' => $group->count(),
                        'duration' => $group->sum('duration')
                    ];
                })
            ];

            // إحصائيات العملاء الأكثر حضوراً
            $topCustomers = Attendance::select('customer_id', DB::raw('count(*) as total'))
                ->whereBetween('check_in', [$request->from_date ?? now()->startOfMonth(), $request->to_date ?? now()])
                ->when($request->filled('customer_id'), function($q) use ($request) {
                    return $q->where('customer_id', $request->customer_id);
                })
                ->groupBy('customer_id')
                ->orderByDesc('total')
                ->limit(10)
                ->with('customer')
                ->get();

            return view('attendances.reports.index', [
                'attendances' => $attendances,
                'summary' => $summary,
                'topCustomers' => $topCustomers,
                'request' => $request->all(),
                'customers' => Customer::active()->orderBy('name')->get()
            ]);

        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * تقرير يومي للحضور
     */
    public function daily(Request $request)
    {
        try {
            $date = $request->get('date', today());

            $attendances = Attendance::with(['customer', 'checkedInBy'])
                ->whereDate('check_in', $date)
                ->orderBy('check_in')
                ->get();

            $summary = [
                'total' => $attendances->count(),
                'checked_in' => $attendances->where('status', 'checked_in')->count(),
                'checked_out' => $attendances->where('status', 'checked_out')->count(),
                'peak_hour' => $attendances->groupBy(function($item) {
                    return $item->check_in->format('H');
                })->sortByDesc(function($group) {
                    return $group->count();
                })->keys()->first()
            ];

            return view('reports.attendance.daily', compact('attendances', 'summary', 'date'));

        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * تقرير شهري للحضور
     */
    public function monthly(Request $request)
    {
        try {
            $month = $request->get('month', now()->month);
            $year = $request->get('year', now()->year);

            $attendances = Attendance::with(['customer'])
                ->whereMonth('check_in', $month)
                ->whereYear('check_in', $year)
                ->get();

            // تجميع حسب اليوم
            $dailyStats = [];
            $daysInMonth = now()->setYear($year)->setMonth($month)->daysInMonth;

            for ($day = 1; $day <= $daysInMonth; $day++) {
                $date = now()->setYear($year)->setMonth($month)->setDay($day)->format('Y-m-d');

                $dayAttendances = $attendances->filter(function($item) use ($date) {
                    return $item->check_in->format('Y-m-d') == $date;
                });

                $dailyStats[] = [
                    'date' => $date,
                    'day' => $day,
                    'count' => $dayAttendances->count(),
                    'duration' => $dayAttendances->sum('duration')
                ];
            }

            // تجميع حسب العميل
            $customerStats = $attendances->groupBy('customer_id')
                ->map(function($group) {
                    $customer = $group->first()->customer;
                    return [
                        'customer_id' => $customer->id,
                        'customer_name' => $customer->name,
                        'total_visits' => $group->count(),
                        'total_duration' => $group->sum('duration'),
                        'avg_duration' => $group->avg('duration')
                    ];
                })->sortByDesc('total_visits')
                ->values();

            $summary = [
                'total_visits' => $attendances->count(),
                'total_duration' => $attendances->sum('duration'),
                'avg_daily' => $attendances->count() / $daysInMonth,
                'unique_customers' => $attendances->unique('customer_id')->count()
            ];

            return view('reports.attendance.monthly', compact(
                'dailyStats',
                'customerStats',
                'summary',
                'month',
                'year'
            ));

        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * تصدير تقرير الحضور
     */
    public function export(Request $request)
    {
        try {
            $type = $request->get('type', 'pdf');
            $query = Attendance::with(['customer', 'subscription.plan']);

            if ($request->filled('from_date')) {
                $query->whereDate('check_in', '>=', $request->from_date);
            }

            if ($request->filled('to_date')) {
                $query->whereDate('check_in', '<=', $request->to_date);
            }

            if ($request->filled('customer_id')) {
                $query->where('customer_id', $request->customer_id);
            }

            $attendances = $query->latest('check_in')->get();

            if ($type == 'excel') {
                return $this->exportToExcel($attendances);
            }

            // تصدير PDF
            $pdf = \PDF::loadView('reports.attendance.pdf', [
                'attendances' => $attendances,
                'request' => $request->all()
            ]);

            return $pdf->download('attendance-report-' . now()->format('Y-m-d') . '.pdf');

        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * تصدير إلى Excel
     */
    private function exportToExcel($attendances)
    {
        // استخدام Laravel Excel إذا كان مثبتاً
        // return \Excel::download(new AttendanceExport($attendances), 'attendance.xlsx');

        // أو تصدير CSV بسيط
        $filename = 'attendance-' . now()->format('Y-m-d') . '.csv';
        $handle = fopen('php://output', 'w');

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        // كتابة الترويسة
        fputcsv($handle, [
            'التاريخ',
            'العميل',
            'وقت الدخول',
            'وقت الخروج',
            'المدة',
            'الحالة',
            'النوع'
        ]);

        // كتابة البيانات
        foreach ($attendances as $attendance) {
            fputcsv($handle, [
                $attendance->check_in->format('Y-m-d'),
                $attendance->customer->name,
                $attendance->check_in->format('h:i A'),
                $attendance->check_out ? $attendance->check_out->format('h:i A') : '-',
                $attendance->duration_formatted,
                $attendance->status_text,
                $attendance->type
            ]);
        }

        fclose($handle);
        exit;
    }
}
