<?php

namespace App\Http\Controllers\SelfPaced\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\SelfPaced\Course;
use App\Models\SelfPaced\ExamResult;
use App\Services\ExamService;
use App\Services\SelfPacedCertificateService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

class ResultController extends Controller
{
    public function __construct(
        protected ExamService $examService,
        protected SelfPacedCertificateService $certificateService
    ) {
        //
    }

    public function index(Request $request)
    {
        $query = ExamResult::with(['user', 'course', 'attempt', 'certificate']);

        // Search by trainee name or course title
        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->whereHas('user', fn ($u) => $u->where('name', 'like', "%{$search}%"))
                  ->orWhereHas('course', fn ($c) => $c->where('title', 'like', "%{$search}%"));
            });
        }

        // Filter by course
        if ($courseId = $request->get('course_id')) {
            $query->where('course_id', $courseId);
        }

        // Filter by pass/fail
        if ($request->has('passed') && $request->get('passed') !== '') {
            $query->where('passed', (bool) $request->get('passed'));
        }

        // Filter by date range
        if ($from = $request->get('date_from')) {
            $query->whereDate('created_at', '>=', $from);
        }
        if ($to = $request->get('date_to')) {
            $query->whereDate('created_at', '<=', $to);
        }

        $results = $query->latest()->paginate(20)->withQueryString();
        $courses  = Course::orderBy('title')->get(['id', 'title']);

        if ($request->ajax()) {
            return response()->json([
                'html' => view('self-paced.dashboard.results.partials.table', compact('results'))->render(),
            ]);
        }

        return view('self-paced.dashboard.results.index', compact('results', 'courses'));
    }

    public function show(ExamResult $result)
    {
        $result->load(['user', 'course', 'attempt', 'enrollment', 'certificate']);
        $incorrectAnswers = $this->examService->getIncorrectAnswers($result->attempt);

        return view('self-paced.dashboard.results.show', compact('result', 'incorrectAnswers'));
    }

    /**
     * Export results to CSV.
     * Requirement 10.7
     */
    public function export(Request $request)
    {
        $query = ExamResult::with(['user', 'course']);

        if ($courseId = $request->get('course_id')) {
            $query->where('course_id', $courseId);
        }

        if ($request->has('passed') && $request->get('passed') !== '') {
            $query->where('passed', (bool) $request->get('passed'));
        }

        if ($from = $request->get('date_from')) {
            $query->whereDate('created_at', '>=', $from);
        }
        if ($to = $request->get('date_to')) {
            $query->whereDate('created_at', '<=', $to);
        }

        $results = $query->latest()->get();

        $filename = 'exam-results-' . now()->format('Y-m-d') . '.csv';

        $headers = [
            'Content-Type'        => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

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

            // CSV header row
            fputcsv($handle, [
                'ID', 'Trainee Name', 'Trainee Email', 'Course', 'Total Questions',
                'Correct Answers', 'Score (%)', 'Passed', 'Passing Threshold (%)',
                'Attempt ID', 'Date',
            ]);

            foreach ($results as $result) {
                fputcsv($handle, [
                    $result->id,
                    $result->user->name ?? 'N/A',
                    $result->user->email ?? 'N/A',
                    $result->course->title ?? 'N/A',
                    $result->total_questions,
                    $result->correct_answers,
                    number_format((float) $result->score_percentage, 2),
                    $result->passed ? 'Yes' : 'No',
                    $result->passing_threshold,
                    $result->attempt_id,
                    $result->created_at->format('Y-m-d H:i:s'),
                ]);
            }

            fclose($handle);
        };

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

    /**
     * Download result slip PDF for a specific result.
     */
    public function downloadResultSlip(ExamResult $result)
    {
        $pdfContent = $this->certificateService->streamResultSlip($result);

        return Response::make($pdfContent, 200, [
            'Content-Type'        => 'application/pdf',
            'Content-Disposition' => 'attachment; filename="result-slip-' . $result->id . '.pdf"',
        ]);
    }
}
