<?php

namespace App\Http\Controllers;

use App\Models\Announcement;
use App\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class AnnouncementController extends Controller
{
    public function index()
    {
        $user  = Auth::user();
        $query = Announcement::with(['company', 'creator'])->latest();

        if ($user->role === 'company_hr') {
            $query->where(fn ($q) => $q->where('company_id', $user->company_id)->orWhereNull('company_id'));
        }

        $companies = $user->role === 'super_admin'
            ? Company::orderBy('name')->get(['id', 'name'])
            : collect();

        return Inertia::render('Announcements/Index', [
            'announcements' => $query->get(),
            'companies'     => $companies,
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'           => 'required|string|max:255',
            'content'         => 'required|string',
            'type'            => 'nullable|string',
            'priority'        => 'nullable|string',
            'is_pinned'       => 'boolean',
            'publish_date'    => 'nullable|date',
            'expiry_date'     => 'nullable|date',
            'target_audience' => 'nullable|string',
            'company_id'      => 'nullable|integer|exists:companies,id',
        ]);

        $data['created_by'] = Auth::id();
        if (Auth::user()->role === 'company_hr') {
            $data['company_id'] = Auth::user()->company_id;
        }

        Announcement::create($data);
        return back()->with('success', 'Announcement published.');
    }

    public function update(Request $request, Announcement $announcement)
    {
        $data = $request->validate([
            'title'           => 'required|string|max:255',
            'content'         => 'required|string',
            'type'            => 'nullable|string',
            'priority'        => 'nullable|string',
            'is_pinned'       => 'boolean',
            'publish_date'    => 'nullable|date',
            'expiry_date'     => 'nullable|date',
            'target_audience' => 'nullable|string',
            'company_id'      => 'nullable|integer|exists:companies,id',
        ]);

        $announcement->update($data);
        return back()->with('success', 'Announcement updated.');
    }

    public function destroy(Announcement $announcement)
    {
        $announcement->delete();
        return back()->with('success', 'Announcement deleted.');
    }
}
