<?php

namespace App\Http\Controllers;

use App\Models\Notice;
use App\Models\NoticeCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class NoticeController extends Controller
{
    /**
     * Display a listing of the notices.
     */
    public function index(Request $request)
    {
        $query = Notice::with('category');

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

        // Filter by category
        if ($request->filled('category_id')) {
            $query->byCategory($request->category_id);
        }

        // Filter by priority: priority column exists? Migration didn't show priority column. 
        // Wait, 'notices' migration 2025_01_01_000005_create_content_management_table.php had:
        // title, category(enum), content, attachment_type, attachment_path, published_at, is_active.
        // It DOES NOT have priority, is_instant, is_pinned, department, expires_at, target_audience.
        // The Controller seems to be for a different schema version!
        // I must ensure I store only what exists or add columns.
        // User said "notice create hocce na".
        // The Schema only has: title, notice_category_id, content, attachment_type, attachment_path, published_at, is_active, created_by.
        // I should stick to these columns for now to succeed.

        $notices = $query->latest()->paginate(15);
        $categories = NoticeCategory::active()->ordered()->get();

        return view('notices.index', compact('notices', 'categories'));
    }

    public function create()
    {
        $categories = NoticeCategory::active()->ordered()->get();
        return view('notices.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:notice_categories,id',
            'file' => 'nullable|file|mimes:pdf,doc,docx,jpg,png|max:10240',
            'is_published' => 'boolean',
        ]);

        $data = [
            'title' => $validated['title'],
            'notice_category_id' => $validated['category_id'],
            'is_active' => $request->has('is_published'), // Mapping published checkbox to is_active/published_at?
            'published_at' => $request->has('is_published') ? now() : null,
            'created_by' => auth()->id(),
        ];

        // Handle file upload
        if ($request->hasFile('file')) {
            $path = $request->file('file')->store('notices', 'public');
            $data['attachment_path'] = $path;
            $data['attachment_type'] = $this->determineAttachmentType($request->file('file'));
        }

        Notice::create($data);

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

    public function show(Notice $notice)
    {
        return view('notices.show', compact('notice'));
    }

    public function edit(Notice $notice)
    {
        $categories = NoticeCategory::active()->ordered()->get();
        return view('notices.edit', compact('notice', 'categories'));
    }

    public function update(Request $request, Notice $notice)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:notice_categories,id',
            'file' => 'nullable|file|mimes:pdf,doc,docx,jpg,png|max:10240',
            'is_published' => 'boolean',
        ]);

        $data = [
            'title' => $validated['title'],
            'notice_category_id' => $validated['category_id'],
            'is_active' => $request->has('is_published'),
            'published_at' => $request->has('is_published') ? ($notice->published_at ?? now()) : null,
        ];

        if ($request->hasFile('file')) {
            if ($notice->attachment_path) {
                Storage::disk('public')->delete($notice->attachment_path);
            }
            $path = $request->file('file')->store('notices', 'public');
            $data['attachment_path'] = $path;
            $data['attachment_type'] = $this->determineAttachmentType($request->file('file'));
        }

        $notice->update($data);

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

    public function destroy(Notice $notice)
    {
        if ($notice->attachment_path) {
            Storage::disk('public')->delete($notice->attachment_path);
        }

        $notice->delete();

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

    private function determineAttachmentType($file)
    {
        $mime = $file->getMimeType();
        if (str_contains($mime, 'pdf')) {
            return 'pdf';
        }
        return 'link';
    }
}

