<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Document;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class DocumentManagementController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->string('status')->toString();

        $documents = Document::query()
            ->with(['user', 'approver'])
            ->when($status, fn ($query) => $query->where('approval_status', $status))
            ->latest()
            ->get();

        return view('admin.documents.index', [
            'documents' => $documents,
            'selectedStatus' => $status,
        ]);
    }

    public function update(Request $request, Document $document)
    {
        $validated = $request->validate([
            'approval_status' => ['required', Rule::in(['pending', 'approved', 'rejected'])],
            'rejection_reason' => ['nullable', 'string', 'max:1000'],
        ]);

        $document->approval_status = $validated['approval_status'];
        $document->approved_at = $validated['approval_status'] === 'approved' ? now() : null;
        $document->approved_by = $validated['approval_status'] === 'approved' ? $request->user()->id : null;
        $document->rejection_reason = $validated['approval_status'] === 'rejected' ? ($validated['rejection_reason'] ?? 'Rejected by admin') : null;
        $document->save();

        return back()->with('status', 'Document approval updated successfully.');
    }
}
