<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Certificate;
use App\Models\CertificateTemplate;
use App\Services\CertificateGenerationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class ModernCertificateController extends Controller
{
    protected $certificateService;

    public function __construct(CertificateGenerationService $certificateService)
    {
        $this->certificateService = $certificateService;
    }

    public function index()
    {
        $templates = CertificateTemplate::active()->with('creator')->get();
        $recentCertificates = Certificate::with('template')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        return view('admin.modern-certificates.index', compact('templates', 'recentCertificates'));
    }

    public function create()
    {
        $templates = CertificateTemplate::active()->get();

        return view('admin.modern-certificates.create', compact('templates'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'template_id' => 'required|exists:modern_certificate_templates,id',
            'student_name' => 'required|string|max:255',
            'student_email' => 'nullable|email|max:255',
            'student_id' => 'nullable|string|max:100',
            'course_name' => 'nullable|string|max:255',
            'graduation_date' => 'required|date',
            'instructor_name' => 'nullable|string|max:255',
            'organization_name' => 'nullable|string|max:255',
            'custom_data' => 'nullable|array',
        ]);

        try {
            $template = CertificateTemplate::findOrFail($request->template_id);

            $studentData = [
                'student_name' => $request->student_name,
                'student_email' => $request->student_email,
                'student_id' => $request->student_id,
                'course_name' => $request->course_name,
                'graduation_date' => $request->graduation_date,
                'instructor_name' => $request->instructor_name,
                'organization_name' => $request->organization_name,
                'serial_number' => 'CERT-' . Str::random(8),
                'current_date' => now()->format('F j, Y'),
                'current_time' => now()->format('g:i A'),
            ];

            // Generate certificate image
            $imagePath = $this->certificateService->generateCertificateFromTemplate($template, $studentData);

            // Create certificate record
            $certificate = Certificate::create([
                'template_id' => $template->id,
                'student_name' => $request->student_name,
                'student_email' => $request->student_email,
                'student_id' => $request->student_id,
                'course_name' => $request->course_name,
                'graduation_date' => $request->graduation_date,
                'instructor_name' => $request->instructor_name,
                'organization_name' => $request->organization_name,
                'serial_number' => $studentData['serial_number'],
                'custom_data' => $request->custom_data,
                'generated_image_path' => $imagePath,
                'status' => 'generated',
                'generated_by' => Auth::id(),
                'generated_at' => now(),
            ]);

            return redirect()->route('admin.modern-certificates.show', $certificate)
                ->with('success', 'Certificate generated successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to generate certificate: ' . $e->getMessage()]);
        }
    }

    public function show(Certificate $certificate)
    {
        $certificate->load('template', 'generator');
        return view('admin.modern-certificates.show', compact('certificate'));
    }

    public function bulkCreate()
    {
        $templates = CertificateTemplate::active()->get();
        return view('admin.modern-certificates.bulk-create', compact('templates'));
    }

    public function bulkStore(Request $request)
    {
        $request->validate([
            'template_id' => 'required|exists:modern_certificate_templates,id',
            'csv_file' => 'required|file|mimes:csv,txt|max:5120',
        ]);

        try {
            $template = CertificateTemplate::findOrFail($request->template_id);
            $csvData = $this->parseCSV($request->file('csv_file'));

            $generatedCount = 0;
            $errors = [];

            foreach ($csvData as $index => $row) {
                try {
                    $studentData = [
                        'student_name' => $row['student_name'] ?? '',
                        'student_email' => $row['student_email'] ?? '',
                        'student_id' => $row['student_id'] ?? '',
                        'course_name' => $row['course_name'] ?? '',
                        'graduation_date' => $row['graduation_date'] ?? now()->format('Y-m-d'),
                        'instructor_name' => $row['instructor_name'] ?? '',
                        'organization_name' => $row['organization_name'] ?? '',
                        'serial_number' => 'CERT-' . Str::random(8),
                        'current_date' => now()->format('F j, Y'),
                        'current_time' => now()->format('g:i A'),
                    ];

                    // Generate certificate image
                    $imagePath = $this->certificateService->generateCertificateFromTemplate($template, $studentData);

                    // Create certificate record
                    Certificate::create([
                        'template_id' => $template->id,
                        'student_name' => $studentData['student_name'],
                        'student_email' => $studentData['student_email'],
                        'student_id' => $studentData['student_id'],
                        'course_name' => $studentData['course_name'],
                        'graduation_date' => $studentData['graduation_date'],
                        'instructor_name' => $studentData['instructor_name'],
                        'organization_name' => $studentData['organization_name'],
                        'serial_number' => $studentData['serial_number'],
                        'custom_data' => $row,
                        'generated_image_path' => $imagePath,
                        'status' => 'generated',
                        'generated_by' => Auth::id(),
                        'generated_at' => now(),
                    ]);

                    $generatedCount++;

                } catch (\Exception $e) {
                    $errors[] = "Row " . ($index + 1) . ": " . $e->getMessage();
                }
            }

            $message = "Successfully generated {$generatedCount} certificates.";
            if (!empty($errors)) {
                $message .= " Errors: " . implode(', ', $errors);
            }

            return redirect()->route('admin.modern-certificates.index')
                ->with('success', $message);

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to process bulk upload: ' . $e->getMessage()]);
        }
    }

    public function download(Certificate $certificate)
    {
        if (!$certificate->generated_image_path) {
            abort(404, 'Certificate image not found');
        }

        $fullPath = storage_path('app/public/' . $certificate->generated_image_path);

        if (!file_exists($fullPath)) {
            abort(404, 'Certificate file not found');
        }

        return response()->download($fullPath, "certificate_{$certificate->student_name}.jpg");
    }

    public function destroy(Certificate $certificate)
    {
        try {
            // Delete generated image
            if ($certificate->generated_image_path) {
                \Storage::disk('public')->delete($certificate->generated_image_path);
            }

            $certificate->delete();

            return redirect()->route('admin.modern-certificates.index')
                ->with('success', 'Certificate deleted successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to delete certificate: ' . $e->getMessage()]);
        }
    }

    public function searchStudents(Request $request)
    {
        $query = $request->get('q');

        // Search in students table (adjust table name based on your system)
        $students = \DB::table('students')
            ->where('name', 'LIKE', "%{$query}%")
            ->orWhere('email', 'LIKE', "%{$query}%")
            ->orWhere('student_id', 'LIKE', "%{$query}%")
            ->limit(10)
            ->get(['id', 'name', 'email', 'student_id', 'course_name']);

        return response()->json($students);
    }

    public function getStudentData($id)
    {
        // Get student data by ID
        $student = \DB::table('students')->find($id);

        if (!$student) {
            return response()->json(['error' => 'Student not found'], 404);
        }

        return response()->json([
            'student_name' => $student->name,
            'student_email' => $student->email,
            'student_id' => $student->student_id,
            'course_name' => $student->course_name ?? '',
        ]);
    }

    private function parseCSV($file)
    {
        $data = [];
        $handle = fopen($file->getPathname(), 'r');

        if ($handle !== false) {
            $headers = fgetcsv($handle);

            while (($row = fgetcsv($handle)) !== false) {
                if (count($row) === count($headers)) {
                    $data[] = array_combine($headers, $row);
                }
            }

            fclose($handle);
        }

        return $data;
    }
}
