<?php

namespace App\Http\Controllers;

use App\Models\Result;
use App\Models\Student;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ResultsImport;

class ResultController extends Controller
{
    /**
     * Display a listing of the results.
     */
    public function index(Request $request)
    {
        $query = Result::query();

        // Search
        if ($request->filled('search')) {
            $query->search($request->search);
        }

        // Filter by class
        if ($request->filled('class')) {
            $query->filterByClass($request->class);
        }

        // Filter by year
        if ($request->filled('year')) {
            $query->filterByYear($request->year);
        }

        $results = $query->latest()->paginate(15);

        return view('results.index', compact('results'));
    }

    /**
     * Show the form for creating a new result.
     */
    public function create()
    {
        $students = Student::orderBy('name')->get();
        return view('results.create', compact('students'));
    }

    /**
     * Store a newly created result in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'student_id' => 'nullable|exists:students,id',
            'roll' => 'required|string|max:255',
            'class' => 'required|in:11,12',
            'year' => 'required|string|max:255',
            'student_name' => 'required|string|max:255',
            'total_marks' => 'required|numeric|min:0|max:999999.99',
            'grade' => 'required|string|max:10',
            'remarks' => 'nullable|string',
        ]);

        Result::create($validated);

        return redirect()->route('results.index')
            ->with('success', 'Result created successfully.');
    }

    /**
     * Display the specified result.
     */
    public function show(Result $result)
    {
        return view('results.show', compact('result'));
    }

    /**
     * Show the form for editing the specified result.
     */
    public function edit(Result $result)
    {
        $students = Student::orderBy('name')->get();
        return view('results.edit', compact('result', 'students'));
    }

    /**
     * Update the specified result in storage.
     */
    public function update(Request $request, Result $result)
    {
        $validated = $request->validate([
            'student_id' => 'nullable|exists:students,id',
            'roll' => 'required|string|max:255',
            'class' => 'required|in:11,12',
            'year' => 'required|string|max:255',
            'student_name' => 'required|string|max:255',
            'total_marks' => 'required|numeric|min:0|max:999999.99',
            'grade' => 'required|string|max:10',
            'remarks' => 'nullable|string',
        ]);

        $result->update($validated);

        return redirect()->route('results.index')
            ->with('success', 'Result updated successfully.');
    }

    /**
     * Remove the specified result from storage.
     */
    public function destroy(Result $result)
    {
        $result->delete();

        return redirect()->route('results.index')
            ->with('success', 'Result deleted successfully.');
    }

    /**
     * Show the form for importing results.
     */
    public function importForm()
    {
        return view('results.import');
    }

    /**
     * Import results from Excel file.
     */
    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx,xls,csv|max:2048',
        ]);

        try {
            Excel::import(new ResultsImport, $request->file('file'));

            return redirect()->route('results.index')
                ->with('success', 'Results imported successfully.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Error importing results: ' . $e->getMessage());
        }
    }
}

