<?php

namespace App\Http\Controllers;

use App\Models\Report;
use App\Models\ReportComment;
use App\Models\FinishedContracts;
use App\Models\Suppliers;
use App\Models\NoHome;
use OneSignal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class ReportCommentController extends Controller
{
    public function index(Request $request, $id)
    {
        $report   = Report::find($id);
        $contract = FinishedContracts::with(['user', 'suppliers.user', 'categories', 'status'])->find($report->contract_id);
        $nohome   = NoHome::where('contract_id', $contract->id)->first();
        $comments = ReportComment::with('user')
                        ->where('report_id', $id)
                        ->orderBy('created_at', 'asc')
                        ->paginate(50);

        return view('reports.comments', compact('comments', 'contract', 'nohome', 'report'));
    }

    public function store(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'comment' => 'required|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }

        $comment            = new ReportComment();
        $comment->report_id = $id;
        $comment->user_id   = Auth::id();
        $comment->comment   = strip_tags($request->comment);
        $comment->save();

        $report   = Report::find($id);
        $contract = FinishedContracts::find($report->contract_id);
        $supplier = Suppliers::find($contract->supplier_id);

        $recipients = array_filter([
            $contract->user_id,
            $supplier->user_id ?? null,
        ]);

        foreach ($recipients as $recipientId) {
            try {
                OneSignal::sendNotificationCustom([
                    'include_external_user_ids' => [(string) $recipientId],
                    'contents' => [
                        'es' => 'Moderador: ' . $comment->comment,
                        'en' => 'Moderator: ' . $comment->comment,
                    ],
                    'headings' => [
                        'es' => 'Nueva actividad en tu reporte',
                        'en' => 'New activity on your report',
                    ],
                ]);
            } catch (\Exception $e) {}
        }

        return redirect()->back();
    }

    public function destroy($id, $comment_id)
    {
        ReportComment::destroy($comment_id);
        return redirect('reports/' . $id . '/comments');
    }
}
