<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use App\Models\HeroSlide;
use App\Models\Notice;
use App\Models\Teacher;
use App\Models\Setting;


class FrontendController extends Controller
{
    public function __construct()
    {
        // Fetch and share global settings with all views
        $defaults = [
            'college_name' => 'Sheikh Abdul Wohab Model College',
            'site_logo' => 'frontend/assets/img/logo.png',
            'site_favicon' => 'frontend/assets/img/favicon.png',
            'footer_about' => 'We are committed to providing quality education.',
            'social_facebook' => '#',
            'social_youtube' => '#',
            'social_twitter' => '#',
            'social_instagram' => '#',
            'contact_full_address' => 'College Road, BD',
            'contact_office_phone' => '+8801...',
            'contact_general_email' => 'info@example.com',
        ];

        try {
            $db_settings = \App\Models\Setting::pluck('value', 'key')->toArray();
            
            // Clean image paths
            if (!empty($db_settings['site_logo'])) {
                $path = str_replace('\\', '/', $db_settings['site_logo']);
                if (strpos($path, 'storage/') !== false) {
                    $db_settings['site_logo'] = substr($path, strpos($path, 'storage/'));
                }
            }
            if (!empty($db_settings['site_favicon'])) {
                $path = str_replace('\\', '/', $db_settings['site_favicon']);
                if (strpos($path, 'storage/') !== false) {
                    $db_settings['site_favicon'] = substr($path, strpos($path, 'storage/'));
                }
            }
        } catch (\Exception $e) {
            $db_settings = [];
        }

        $global_settings = array_merge($defaults, $db_settings);
        view()->share('global_settings', $global_settings);
    }
    public function index()
    {
        $hero_slides = Cache::remember('home_hero_slides', 600, function () {
            return HeroSlide::where('is_active', true)->orderBy('sort_order')->get();
        });

        $pinned_notices = Cache::remember('home_pinned_notices', 600, function () {
            return Notice::where('is_active', true)->where('is_pinned', true)->latest('published_at')->take(3)->get();
        });

        $latest_notices = Cache::remember('home_latest_notices', 600, function () {
            return Notice::where('is_active', true)->where('is_pinned', false)->latest('published_at')->take(5)->get();
        });

        $website_settings = Cache::remember('website_settings', 3600, function () {
            return Setting::where('group', 'website')->pluck('value', 'key');
        });

        // Use cached slides if available, otherwise fetch. (Line 58 handles it, but line 74 re-fetches. Let's stick to using the variable)
        // Oops, the original code fetched $hero_slides TWICE. I will fix that too.
        
        $teachers = \App\Models\Teacher::where('is_active', true)
                    ->orderBy('is_principal', 'desc')
                    ->orderBy('display_order')
                    ->take(4)
                    ->get();
        
        return view('frontend.index', compact('hero_slides', 'teachers', 'website_settings', 'pinned_notices', 'latest_notices'));
    }

    public function about()
    {
        return view('frontend.about');
    }

    public function contact()
    {
        $contact_info = Cache::remember('contact_info', 3600, function () {
            return Setting::where('group', 'contact')->get()->pluck('value', 'key');
        });
        return view('frontend.contact', compact('contact_info'));
    }

    public function notice(Request $request)
    {
        $page = request()->get('page', 1);
        $search = request()->get('search');

        if ($search) {
            $notices = Notice::where('is_active', true)
                ->search($search)
                ->latest('published_at')
                ->paginate(12)
                ->withQueryString();
        } else {
            $notices = Cache::remember('notice_list_page_' . $page, 300, function () {
                return Notice::where('is_active', true)
                    ->latest('published_at')
                    ->paginate(12);
            });
        }

        if ($request->ajax()) {
            return view('frontend.partials.notice-content', compact('notices'))->render();
        }

        return view('frontend.notice', compact('notices'));
    }

    public function downloadNotice($id)
    {
        $notice = Notice::findOrFail($id);
        
        if (!$notice->attachment_path || !Storage::disk('public')->exists($notice->attachment_path)) {
            abort(404, 'File not found');
        }

        return response()->download(
            Storage::disk('public')->path($notice->attachment_path),
            $notice->title . '.pdf'
        );
    }

    public function streamNotice($id)
    {
        $notice = Notice::findOrFail($id);
        
        if (!$notice->attachment_path || !Storage::disk('public')->exists($notice->attachment_path)) {
            abort(404, 'File not found');
        }

        return response()->file(
            Storage::disk('public')->path($notice->attachment_path)
        );
    }

    public function viewNotice($id)
    {
        $notice = Notice::findOrFail($id);
        
        if (!$notice->attachment_path || !Storage::disk('public')->exists($notice->attachment_path)) {
            abort(404, 'File not found');
        }

        return view('frontend.notice-view', compact('notice'));
    }

    public function noticeDetails($id)
    {
        $notice = Notice::findOrFail($id);
        
        // Similar to the download check
        if (!$notice->is_active) {
            abort(404, 'Notice not available');
        }

        return view('frontend.notice-details', compact('notice'));
    }

    public function result()
    {
        $batches = Cache::remember('all_batches', 3600, function () {
            return \App\Models\Batch::orderBy('name', 'desc')->get();
        });
        
        $classes = Cache::remember('all_classes_unique', 3600, function () {
           // Providing static classes XI and XII as per typical college structure
           return ['XI' => 'Class XI', 'XII' => 'Class XII'];
        });

        // Still pass latest exams for fallback or initial view if needed, but primarily reliance is on AJAX
        $exams = \App\Models\Exam::where('status', 'published')->latest('start_date')->get();

        return view('frontend.result', compact('batches', 'classes', 'exams'));
    }

    public function getExams(Request $request)
    {
        $request->validate([
            'batch_id' => 'required|exists:batches,id',
            'class_year' => 'required|in:XI,XII',
        ]);

        // Convert class_year (XI/XII) to database format (11/12)
        $classValue = $request->class_year === 'XI' ? '11' : '12';

        $exams = \App\Models\Exam::where('status', 'published')
            ->where('batch_id', $request->batch_id)
            ->where('class', $classValue)
            ->latest('start_date')
            ->get(['id', 'name']);

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

    public function resultSearch(Request $request)
    {
        $request->validate([
            'batch_id' => 'required',
            'class_year' => 'required', // Renamed from 'class' to avoid keyword conflict
            'roll_no' => 'required',
            // 'reg_no' => 'required', // Optional based on user prompt "select class roll class and reg number"
            'exam_id' => 'required|exists:exams,id',
        ]);

        // Get selected batch to extract year if possible (for backward compatibility where batch_id might be null in students)
    $batch = \App\Models\Batch::find($request->batch_id);
    $batchYear = $batch ? preg_replace('/[^0-9]/', '', $batch->name) : null;
    $isValidYear = $batchYear && strlen($batchYear) == 4;

    $query = \App\Models\Student::where('class_roll', $request->roll_no)
                ->where(function($q) use ($request, $batchYear, $isValidYear) {
                    $q->where('batch_id', $request->batch_id);
                    
                    if ($isValidYear) {
                         $q->orWhere('hsc_batch', $batchYear)
                           ->orWhere('ssc_batch', $batchYear);
                    }
                });
        
        if ($request->filled('reg_no')) {
            $query->where('ssc_reg_no', $request->reg_no);
        }

        $student = $query->first();

        if (!$student) {
            return back()->with('error', 'Student not found with this Roll or Reg No.');
        }

        $final_result = \App\Models\FinalResult::where('student_id', $student->id)
            ->where('exam_id', $request->exam_id)
            ->first();

        if (!$final_result) {
            return back()->with('error', 'Result not published or not found for this student.');
        }

        $marks = \App\Models\ResultMark::with('subject')
            ->where('student_id', $student->id)
            ->where('exam_id', $request->exam_id)
            ->get();
            
        $exam = \App\Models\Exam::with('subjectRules')->find($request->exam_id);

        return view('frontend.result-sheet', compact('student', 'exam', 'final_result', 'marks'));
    }

    public function teachers()
    {
        // Fetch all active teachers, Principals first
        $teachers = Teacher::where('is_active', true)
                    ->orderBy('is_principal', 'desc')
                    ->orderBy('display_order')
                    ->paginate(20); // Using pagination for better performance on large lists
                    
        return view('frontend.teachers', compact('teachers'));
    }

    public function privacyPolicy()
    {
        return view('frontend.privacy-policy');
    }

    public function termsOfUse()
    {
        return view('frontend.terms-of-use');
    }
}
