<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Certificate;
use App\Models\Course;
use App\Models\CourseOffering;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class CertificateController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'role:admin']);
    }

    /**
     * Display a listing of certificates.
     */
    public function index(Request $request)
    {
        $query = Certificate::with(['student', 'course', 'courseOffering', 'issuedBy']);

        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where('title', 'like', "%{$search}%")
                  ->orWhereHas('student', function($q) use ($search) {
                      $q->where('name', 'like', "%{$search}%");
                  });
        }

        $certificates = $query->orderBy('issued_date', 'desc')->paginate(20);
        return view('admin.certificates.index', compact('certificates'));
    }

    /**
     * Show the form for creating a new certificate.
     */
    public function create()
    {
        $students = User::where('role', 'student')->orderBy('name')->get();
        $courses = Course::where('is_active', true)->orderBy('name')->get();
        $offerings = CourseOffering::where('status', '!=', 'cancelled')->orderBy('start_date', 'desc')->get();
        return view('admin.certificates.create', compact('students', 'courses', 'offerings'));
    }

    /**
     * Store a newly created certificate.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'student_id' => 'required|exists:users,id',
            'course_id' => 'nullable|exists:courses,id',
            'course_offering_id' => 'nullable|exists:course_offerings,id',
            'title' => 'required|string|max:255',
            'certificate_type' => 'nullable|string|max:50',
            'file' => 'required|file|mimes:pdf|max:10240',
            'issued_date' => 'required|date',
            'description' => 'nullable|string',
        ]);

        $file = $request->file('file');
        $fileName = time() . '_' . $file->getClientOriginalName();
        $filePath = $file->storeAs('certificates', $fileName, 'public');

        Certificate::create([
            'student_id' => $validated['student_id'],
            'course_id' => $validated['course_id'] ?? null,
            'course_offering_id' => $validated['course_offering_id'] ?? null,
            'title' => $validated['title'],
            'certificate_type' => $validated['certificate_type'] ?? 'completion',
            'file_path' => $filePath,
            'file_name' => $file->getClientOriginalName(),
            'file_size' => $file->getSize(),
            'issued_date' => $validated['issued_date'],
            'issued_by' => auth()->id(),
            'description' => $validated['description'] ?? null,
        ]);

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

    /**
     * Display the specified certificate.
     */
    public function show($id)
    {
        $certificate = Certificate::with(['student', 'course', 'courseOffering', 'issuedBy'])->findOrFail($id);
        return view('admin.certificates.show', compact('certificate'));
    }

    /**
     * Show the form for editing the specified certificate.
     */
    public function edit($id)
    {
        $certificate = Certificate::findOrFail($id);
        $students = User::where('role', 'student')->orderBy('name')->get();
        $courses = Course::where('is_active', true)->orderBy('name')->get();
        $offerings = CourseOffering::where('status', '!=', 'cancelled')->orderBy('start_date', 'desc')->get();
        return view('admin.certificates.edit', compact('certificate', 'students', 'courses', 'offerings'));
    }

    /**
     * Update the specified certificate.
     */
    public function update(Request $request, $id)
    {
        $certificate = Certificate::findOrFail($id);

        $validated = $request->validate([
            'student_id' => 'required|exists:users,id',
            'course_id' => 'nullable|exists:courses,id',
            'course_offering_id' => 'nullable|exists:course_offerings,id',
            'title' => 'required|string|max:255',
            'certificate_type' => 'nullable|string|max:50',
            'file' => 'nullable|file|mimes:pdf|max:10240',
            'issued_date' => 'required|date',
            'description' => 'nullable|string',
            'is_active' => 'nullable',
        ]);

        if ($request->hasFile('file')) {
            // Delete old file
            if ($certificate->file_path && Storage::disk('public')->exists($certificate->file_path)) {
                Storage::disk('public')->delete($certificate->file_path);
            }

            $file = $request->file('file');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $filePath = $file->storeAs('certificates', $fileName, 'public');

            $validated['file_path'] = $filePath;
            $validated['file_name'] = $file->getClientOriginalName();
            $validated['file_size'] = $file->getSize();
        }

        $updateData = $validated;
        $updateData['is_active'] = $request->has('is_active') && $request->is_active == '1';
        $certificate->update($updateData);

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

    /**
     * Remove the specified certificate.
     */
    public function destroy($id)
    {
        $certificate = Certificate::findOrFail($id);
        
        // Delete file
        if ($certificate->file_path && Storage::disk('public')->exists($certificate->file_path)) {
            Storage::disk('public')->delete($certificate->file_path);
        }

        $certificate->delete();

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

