<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\ReportService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Carbon\Carbon;

class ReportController extends Controller
{
    protected $reportService;

    public function __construct(ReportService $reportService)
    {
        $this->reportService = $reportService;
    }

    /**
     * Get report summary statistics
     */
    public function getSummary(Request $request): JsonResponse
    {
        try {
            $dateRange = $this->getDateRange($request);
            
            $summary = $this->reportService->getSummary(
                $dateRange['start'],
                $dateRange['end']
            );

            return response()->json([
                'success' => true,
                'data' => $summary
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to load summary: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Generate specific report
     */
    public function generateReport(Request $request): JsonResponse
    {
        $request->validate([
            'type' => 'required|string'
        ]);

        try {
            $dateRange = $this->getDateRange($request);
            $reportType = $request->input('type');

            $reportData = $this->reportService->generateReport(
                $reportType,
                $dateRange['start'],
                $dateRange['end']
            );

            return response()->json([
                'success' => true,
                'data' => $reportData
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to generate report: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Export report to specified format
     */
    public function exportReport(Request $request)
    {
        $request->validate([
            'type' => 'required|string',
            'format' => 'required|in:pdf,excel,csv'
        ]);

        try {
            $dateRange = $this->getDateRange($request);
            $reportType = $request->input('type');
            $format = $request->input('format');

            $file = $this->reportService->exportReport(
                $reportType,
                $format,
                $dateRange['start'],
                $dateRange['end']
            );

            return response()->download($file)->deleteFileAfterSend(true);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to export report: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Export all reports as ZIP
     */
    public function exportAll(Request $request)
    {
        $request->validate([
            'format' => 'required|in:pdf,excel,csv'
        ]);

        try {
            $dateRange = $this->getDateRange($request);
            $format = $request->input('format');

            $zipFile = $this->reportService->exportAllReports(
                $format,
                $dateRange['start'],
                $dateRange['end']
            );

            return response()->download($zipFile)->deleteFileAfterSend(true);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to export all reports: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Email specific report
     */
    public function emailReport(Request $request): JsonResponse
    {
        $request->validate([
            'email' => 'required|email',
            'type' => 'required|string'
        ]);

        try {
            $dateRange = $this->getDateRange($request);
            
            $this->reportService->emailReport(
                $request->input('email'),
                $request->input('type'),
                $dateRange['start'],
                $dateRange['end']
            );

            return response()->json([
                'success' => true,
                'message' => 'Report sent successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to send report: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Email all reports
     */
    public function emailAllReports(Request $request): JsonResponse
    {
        $request->validate([
            'email' => 'required|email'
        ]);

        try {
            $dateRange = $this->getDateRange($request);
            
            $this->reportService->emailAllReports(
                $request->input('email'),
                $dateRange['start'],
                $dateRange['end']
            );

            return response()->json([
                'success' => true,
                'message' => 'All reports sent successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to send reports: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get scheduled reports
     */
    public function getScheduledReports(): JsonResponse
    {
        try {
            $schedules = $this->reportService->getScheduledReports();

            return response()->json([
                'success' => true,
                'data' => $schedules
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to load schedules: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Create scheduled report
     */
    public function createSchedule(Request $request): JsonResponse
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|string',
            'frequency' => 'required|in:daily,weekly,monthly',
            'format' => 'required|in:pdf,excel,csv',
            'recipients' => 'required|email'
        ]);

        try {
            $schedule = $this->reportService->createSchedule($request->all());

            return response()->json([
                'success' => true,
                'data' => $schedule,
                'message' => 'Report scheduled successfully'
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create schedule: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update scheduled report
     */
    public function updateSchedule(Request $request, $id): JsonResponse
    {
        $request->validate([
            'name' => 'sometimes|string|max:255',
            'frequency' => 'sometimes|in:daily,weekly,monthly',
            'format' => 'sometimes|in:pdf,excel,csv',
            'recipients' => 'sometimes|email'
        ]);

        try {
            $schedule = $this->reportService->updateSchedule($id, $request->all());

            return response()->json([
                'success' => true,
                'data' => $schedule,
                'message' => 'Schedule updated successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update schedule: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete scheduled report
     */
    public function deleteSchedule($id): JsonResponse
    {
        try {
            $this->reportService->deleteSchedule($id);

            return response()->json([
                'success' => true,
                'message' => 'Schedule deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete schedule: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Parse date range from request
     */
    private function getDateRange(Request $request): array
    {
        $range = $request->input('range', 'month');
        
        if ($range === 'custom') {
            return [
                'start' => Carbon::parse($request->input('start_date')),
                'end' => Carbon::parse($request->input('end_date'))
            ];
        }

        $end = Carbon::now();
        
        switch ($range) {
            case 'today':
                $start = Carbon::today();
                break;
            case 'week':
                $start = Carbon::now()->startOfWeek();
                break;
            case 'month':
                $start = Carbon::now()->startOfMonth();
                break;
            case 'year':
                $start = Carbon::now()->startOfYear();
                break;
            default:
                $start = Carbon::now()->startOfMonth();
        }

        return [
            'start' => $start,
            'end' => $end
        ];
    }
}