<?php

namespace App\Http\Controllers;

use App\Models\MaintenanceLog;
use App\Models\MaintenanceSchedule;
use App\Models\MaintenanceRequest;
use App\Models\MaintenanceTeam;
use App\Models\Elevator;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MaintenanceReportController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('maintenance.reports.index');
    }

    /**
     * Generate maintenance performance report
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function performanceReport(Request $request)
    {
        $request->validate([
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'team_id' => 'nullable|exists:maintenance_teams,id',
        ]);

        $startDate = $request->start_date;
        $endDate = $request->end_date;
        $teamId = $request->team_id;

        $query = MaintenanceLog::with(['elevator', 'team'])
            ->whereBetween('maintenance_date', [$startDate, $endDate]);

        if ($teamId) {
            $query->where('team_id', $teamId);
        }

        $logs = $query->get();

        // Calculate performance metrics
        $totalMaintenance = $logs->count();
        $completedOnTime = $logs->where('status', 'completed')->where('is_delayed', false)->count();
        $completedLate = $logs->where('status', 'completed')->where('is_delayed', true)->count();
        $pending = $logs->where('status', 'pending')->count();
        $cancelled = $logs->where('status', 'cancelled')->count();

        // Calculate average time spent
        $averageTimeSpent = $logs->where('status', 'completed')->avg('time_spent');

        // Calculate team performance
        $teamPerformance = $logs->where('status', 'completed')
            ->groupBy('team_id')
            ->map(function ($items, $key) {
                $team = MaintenanceTeam::find($key);
                $teamName = $team ? $team->name : 'غير محدد';
                $totalCount = $items->count();
                $onTimeCount = $items->where('is_delayed', false)->count();
                $onTimePercentage = $totalCount > 0 ? ($onTimeCount / $totalCount) * 100 : 0;

                return [
                    'team_id' => $key,
                    'team_name' => $teamName,
                    'total_count' => $totalCount,
                    'on_time_count' => $onTimeCount,
                    'on_time_percentage' => $onTimePercentage,
                    'average_time_spent' => $items->avg('time_spent'),
                ];
            })->values();

        // Calculate elevator maintenance frequency
        $elevatorMaintenance = $logs->groupBy('elevator_id')
            ->map(function ($items, $key) {
                $elevator = Elevator::with('location')->find($key);
                $elevatorName = $elevator ? $elevator->name : 'غير محدد';
                $locationName = $elevator && $elevator->location ? $elevator->location->name : 'غير محدد';

                return [
                    'elevator_id' => $key,
                    'elevator_name' => $elevatorName,
                    'location' => $locationName,
                    'maintenance_count' => $items->count(),
                    'issues_count' => $items->where('has_issues', true)->count(),
                ];
            })->values();

        $teams = MaintenanceTeam::all();

        return view('maintenance.reports.performance', compact(
            'logs',
            'totalMaintenance',
            'completedOnTime',
            'completedLate',
            'pending',
            'cancelled',
            'averageTimeSpent',
            'teamPerformance',
            'elevatorMaintenance',
            'teams',
            'startDate',
            'endDate',
            'teamId'
        ));
    }

    /**
     * Generate maintenance issues report
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function issuesReport(Request $request)
    {
        $request->validate([
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'elevator_id' => 'nullable|exists:elevators,id',
        ]);

        $startDate = $request->start_date;
        $endDate = $request->end_date;
        $elevatorId = $request->elevator_id;

        $query = MaintenanceLog::with(['elevator', 'team'])
            ->where('has_issues', true)
            ->whereBetween('maintenance_date', [$startDate, $endDate]);

        if ($elevatorId) {
            $query->where('elevator_id', $elevatorId);
        }

        $logs = $query->get();

        // Group issues by type
        $issuesByType = $logs->groupBy('issue_type')
            ->map(function ($items, $key) {
                return [
                    'issue_type' => $key ?: 'غير محدد',
                    'count' => $items->count(),
                    'logs' => $items,
                ];
            })->values();

        // Group issues by elevator
        $issuesByElevator = $logs->groupBy('elevator_id')
            ->map(function ($items, $key) {
                $elevator = Elevator::with('location')->find($key);
                $elevatorName = $elevator ? $elevator->name : 'غير محدد';
                $locationName = $elevator && $elevator->location ? $elevator->location->name : 'غير محدد';

                return [
                    'elevator_id' => $key,
                    'elevator_name' => $elevatorName,
                    'location' => $locationName,
                    'issues_count' => $items->count(),
                    'logs' => $items,
                ];
            })->values();

        $elevators = Elevator::all();

        return view('maintenance.reports.issues', compact(
            'logs',
            'issuesByType',
            'issuesByElevator',
            'elevators',
            'startDate',
            'endDate',
            'elevatorId'
        ));
    }

    /**
     * Generate maintenance financial report
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function financialReport(Request $request)
    {
        $request->validate([
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'customer_id' => 'nullable|exists:customers,id',
        ]);

        $startDate = $request->start_date;
        $endDate = $request->end_date;
        $customerId = $request->customer_id;

        $query = DB::table('maintenance_invoices')
            ->join('customers', 'maintenance_invoices.customer_id', '=', 'customers.id')
            ->join('maintenance_logs', 'maintenance_invoices.maintenance_log_id', '=', 'maintenance_logs.id')
            ->join('elevators', 'maintenance_logs.elevator_id', '=', 'elevators.id')
            ->select(
                'maintenance_invoices.*',
                'customers.name as customer_name',
                'elevators.name as elevator_name'
            )
            ->whereBetween('maintenance_invoices.invoice_date', [$startDate, $endDate]);

        if ($customerId) {
            $query->where('maintenance_invoices.customer_id', $customerId);
        }

        $invoices = $query->get();

        // Calculate financial metrics
        $totalAmount = $invoices->sum('total_amount');
        $totalPaid = $invoices->where('status', 'paid')->sum('total_amount');
        $totalUnpaid = $invoices->whereIn('status', ['draft', 'sent'])->sum('total_amount');
        $totalCancelled = $invoices->where('status', 'cancelled')->sum('total_amount');

        // Group by customer
        $invoicesByCustomer = $invoices->groupBy('customer_id')
            ->map(function ($items, $key) {
                return [
                    'customer_id' => $key,
                    'customer_name' => $items->first()->customer_name,
                    'invoice_count' => $items->count(),
                    'total_amount' => $items->sum('total_amount'),
                    'paid_amount' => $items->where('status', 'paid')->sum('total_amount'),
                    'unpaid_amount' => $items->whereIn('status', ['draft', 'sent'])->sum('total_amount'),
                ];
            })->values();

        // Group by month
        $invoicesByMonth = $invoices->groupBy(function ($item) {
            return date('Y-m', strtotime($item->invoice_date));
        })->map(function ($items, $key) {
            return [
                'month' => $key,
                'month_name' => date('F Y', strtotime($key . '-01')),
                'invoice_count' => $items->count(),
                'total_amount' => $items->sum('total_amount'),
                'paid_amount' => $items->where('status', 'paid')->sum('total_amount'),
                'unpaid_amount' => $items->whereIn('status', ['draft', 'sent'])->sum('total_amount'),
            ];
        })->values();

        $customers = Customer::all();

        return view('maintenance.reports.financial', compact(
            'invoices',
            'totalAmount',
            'totalPaid',
            'totalUnpaid',
            'totalCancelled',
            'invoicesByCustomer',
            'invoicesByMonth',
            'customers',
            'startDate',
            'endDate',
            'customerId'
        ));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return redirect()->route('maintenance-reports.index');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        return redirect()->route('maintenance-reports.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return redirect()->route('maintenance-reports.index');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return redirect()->route('maintenance-reports.index');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        return redirect()->route('maintenance-reports.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return redirect()->route('maintenance-reports.index');
    }

    /**
     * Generate elevator status report
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function elevatorStatusReport(Request $request)
    {
        $request->validate([
            'period' => 'required|in:month,quarter,year,custom',
            'custom_start_date' => 'required_if:period,custom|date',
            'custom_end_date' => 'required_if:period,custom|date|after_or_equal:custom_start_date',
            'customer_id' => 'nullable|exists:customers,id',
        ]);

        // تحديد الفترة الزمنية
        $endDate = now();
        $startDate = null;

        switch ($request->period) {
            case 'month':
                $startDate = now()->startOfMonth();
                break;
            case 'quarter':
                $startDate = now()->startOfQuarter();
                break;
            case 'year':
                $startDate = now()->startOfYear();
                break;
            case 'custom':
                $startDate = $request->custom_start_date;
                $endDate = $request->custom_end_date;
                break;
        }

        $customerId = $request->customer_id;

        // استعلام المصاعد
        $query = Elevator::with(['customer', 'maintenanceLogs' => function ($query) use ($startDate, $endDate) {
            $query->whereBetween('maintenance_date', [$startDate, $endDate]);
        }]);

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

        $elevators = $query->get();

        // تحليل حالة المصاعد
        $elevatorStatus = $elevators->map(function ($elevator) {
            $logs = $elevator->maintenanceLogs;
            $totalMaintenance = $logs->count();
            $issuesCount = $logs->where('has_issues', true)->count();
            $issuePercentage = $totalMaintenance > 0 ? ($issuesCount / $totalMaintenance) * 100 : 0;

            // تصنيف المصاعد حسب تكرار الأعطال
            $status = 'جيد';
            if ($issuePercentage > 30) {
                $status = 'سيء';
            } elseif ($issuePercentage > 10) {
                $status = 'متوسط';
            }

            return [
                'elevator_id' => $elevator->id,
                'elevator_name' => $elevator->name,
                'serial_number' => $elevator->serial_number,
                'building_name' => $elevator->building_name,
                'customer_name' => $elevator->customer ? $elevator->customer->name : 'غير محدد',
                'total_maintenance' => $totalMaintenance,
                'issues_count' => $issuesCount,
                'issue_percentage' => $issuePercentage,
                'status' => $status,
            ];
        });

        // تصنيف أنواع الأعطال
        $issueTypes = MaintenanceLog::whereBetween('maintenance_date', [$startDate, $endDate])
            ->where('has_issues', true)
            ->whereIn('elevator_id', $elevators->pluck('id'))
            ->groupBy('issue_type')
            ->select('issue_type', DB::raw('count(*) as count'))
            ->get();

        $customers = Customer::all();

        return view('maintenance.reports.elevator_status', compact(
            'elevatorStatus',
            'issueTypes',
            'customers',
            'startDate',
            'endDate',
            'customerId',
            'request'
        ));
    }

    /**
     * Generate maintenance cost report
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function costReport(Request $request)
    {
        $request->validate([
            'cost_start_date' => 'required|date',
            'cost_end_date' => 'required|date|after_or_equal:cost_start_date',
            'elevator_id' => 'nullable|exists:elevators,id',
        ]);

        $startDate = $request->cost_start_date;
        $endDate = $request->cost_end_date;
        $elevatorId = $request->elevator_id;

        // استعلام سجلات الصيانة
        $query = MaintenanceLog::with(['elevator', 'team', 'parts'])
            ->whereBetween('maintenance_date', [$startDate, $endDate]);

        if ($elevatorId) {
            $query->where('elevator_id', $elevatorId);
        }

        $logs = $query->get();

        // حساب التكاليف
        $totalPartsCost = 0;
        $totalLaborCost = 0;

        foreach ($logs as $log) {
            $totalPartsCost += $log->parts->sum('pivot.cost');
            $totalLaborCost += $log->labor_cost ?: 0;
        }

        $totalCost = $totalPartsCost + $totalLaborCost;

        // تكاليف حسب المصعد
        $costsByElevator = $logs->groupBy('elevator_id')
            ->map(function ($items, $key) {
                $elevator = Elevator::find($key);
                $elevatorName = $elevator ? $elevator->name : 'غير محدد';
                $buildingName = $elevator ? $elevator->building_name : 'غير محدد';

                $partsCost = 0;
                $laborCost = 0;

                foreach ($items as $log) {
                    $partsCost += $log->parts->sum('pivot.cost');
                    $laborCost += $log->labor_cost ?: 0;
                }

                $totalCost = $partsCost + $laborCost;

                return [
                    'elevator_id' => $key,
                    'elevator_name' => $elevatorName,
                    'building_name' => $buildingName,
                    'maintenance_count' => $items->count(),
                    'parts_cost' => $partsCost,
                    'labor_cost' => $laborCost,
                    'total_cost' => $totalCost,
                ];
            })->values();

        // تكاليف حسب الشهر
        $costsByMonth = $logs->groupBy(function ($item) {
            return date('Y-m', strtotime($item->maintenance_date));
        })->map(function ($items, $key) {
            $partsCost = 0;
            $laborCost = 0;

            foreach ($items as $log) {
                $partsCost += $log->parts->sum('pivot.cost');
                $laborCost += $log->labor_cost ?: 0;
            }

            $totalCost = $partsCost + $laborCost;

            return [
                'month' => $key,
                'month_name' => date('F Y', strtotime($key . '-01')),
                'maintenance_count' => $items->count(),
                'parts_cost' => $partsCost,
                'labor_cost' => $laborCost,
                'total_cost' => $totalCost,
            ];
        })->values();

        $elevators = Elevator::all();

        return view('maintenance.reports.cost', compact(
            'logs',
            'totalPartsCost',
            'totalLaborCost',
            'totalCost',
            'costsByElevator',
            'costsByMonth',
            'elevators',
            'startDate',
            'endDate',
            'elevatorId'
        ));
    }

    /**
     * Generate schedule compliance report
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function scheduleComplianceReport(Request $request)
    {
        $request->validate([
            'compliance_year' => 'required|integer|min:2000|max:2100',
            'compliance_month' => 'nullable|integer|min:1|max:12',
        ]);

        $year = $request->compliance_year;
        $month = $request->compliance_month;

        // تحديد الفترة الزمنية
        if ($month) {
            $startDate = "{$year}-{$month}-01";
            $endDate = date('Y-m-t', strtotime($startDate));
        } else {
            $startDate = "{$year}-01-01";
            $endDate = "{$year}-12-31";
        }

        // استعلام جداول الصيانة
        $schedules = MaintenanceSchedule::with(['elevator', 'maintenanceLogs'])
            ->whereBetween('scheduled_date', [$startDate, $endDate])
            ->get();

        // تحليل الالتزام بالجدول
        $complianceData = $schedules->map(function ($schedule) {
            $isCompleted = false;
            $isOnTime = false;
            $completedDate = null;

            // البحث عن سجل الصيانة المرتبط
            foreach ($schedule->maintenanceLogs as $log) {
                if ($log->status === 'completed') {
                    $isCompleted = true;
                    $completedDate = $log->maintenance_date;

                    // التحقق من الالتزام بالموعد
                    $scheduledDate = date('Y-m-d', strtotime($schedule->scheduled_date));
                    $maintenanceDate = date('Y-m-d', strtotime($log->maintenance_date));

                    if ($maintenanceDate <= $scheduledDate) {
                        $isOnTime = true;
                    }

                    break;
                }
            }

            return [
                'schedule_id' => $schedule->id,
                'elevator_id' => $schedule->elevator_id,
                'elevator_name' => $schedule->elevator ? $schedule->elevator->name : 'غير محدد',
                'building_name' => $schedule->elevator ? $schedule->elevator->building_name : 'غير محدد',
                'scheduled_date' => $schedule->scheduled_date,
                'is_completed' => $isCompleted,
                'is_on_time' => $isOnTime,
                'completed_date' => $completedDate,
                'status' => $isCompleted ? ($isOnTime ? 'في الموعد' : 'متأخر') : 'غير مكتمل',
            ];
        });

        // إحصائيات الالتزام
        $totalSchedules = $complianceData->count();
        $completedSchedules = $complianceData->where('is_completed', true)->count();
        $onTimeSchedules = $complianceData->where('is_on_time', true)->count();
        $lateSchedules = $complianceData->where('is_completed', true)->where('is_on_time', false)->count();
        $incompleteSchedules = $complianceData->where('is_completed', false)->count();

        $complianceRate = $totalSchedules > 0 ? ($completedSchedules / $totalSchedules) * 100 : 0;
        $onTimeRate = $completedSchedules > 0 ? ($onTimeSchedules / $completedSchedules) * 100 : 0;

        // تحليل حسب الشهر
        $complianceByMonth = $schedules->groupBy(function ($item) {
            return date('Y-m', strtotime($item->scheduled_date));
        })->map(function ($items, $key) {
            $totalCount = $items->count();
            $completedCount = 0;
            $onTimeCount = 0;

            foreach ($items as $schedule) {
                $isCompleted = false;
                $isOnTime = false;

                foreach ($schedule->maintenanceLogs as $log) {
                    if ($log->status === 'completed') {
                        $isCompleted = true;

                        $scheduledDate = date('Y-m-d', strtotime($schedule->scheduled_date));
                        $maintenanceDate = date('Y-m-d', strtotime($log->maintenance_date));

                        if ($maintenanceDate <= $scheduledDate) {
                            $isOnTime = true;
                        }

                        break;
                    }
                }

                if ($isCompleted) {
                    $completedCount++;
                    if ($isOnTime) {
                        $onTimeCount++;
                    }
                }
            }

            $complianceRate = $totalCount > 0 ? ($completedCount / $totalCount) * 100 : 0;
            $onTimeRate = $completedCount > 0 ? ($onTimeCount / $completedCount) * 100 : 0;

            return [
                'month' => $key,
                'month_name' => date('F Y', strtotime($key . '-01')),
                'total_count' => $totalCount,
                'completed_count' => $completedCount,
                'on_time_count' => $onTimeCount,
                'compliance_rate' => $complianceRate,
                'on_time_rate' => $onTimeRate,
            ];
        })->values();

        return view('maintenance.reports.schedule_compliance', compact(
            'complianceData',
            'totalSchedules',
            'completedSchedules',
            'onTimeSchedules',
            'lateSchedules',
            'incompleteSchedules',
            'complianceRate',
            'onTimeRate',
            'complianceByMonth',
            'year',
            'month',
            'startDate',
            'endDate'
        ));
    }
}
