<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use App\Models\UserNotification;

class NotificationsController extends Controller
{
    public function __construct()
    {
        //
        $this->middleware('auth:api');

        $api_user = auth()->guard('api')->user();

        if (!$api_user)
        {
            return response()->json(['error' => 'Unauthorized.'], 401);
        }

    }

    public function index() {
        $api_user = auth()->guard('api')->user();
        $company_id = $api_user->company_id;

        $notifications = UserNotification::where([['id', '>', 0],['company_id', $company_id]])->orderBy('created_at', 'DESC')->get();

        return response()->json(['notifications' => $notifications], 200);
    }

    public function markAll(Request $request)
    {

        $api_user = auth()->guard('api')->user();

        $type = $request->type;
        $company_id = $api_user->company_id;

        if ($type == true) {
            // Read all
            $notifications = UserNotification::where([['id', '>', 0],['company_id', $company_id]])->get();

            foreach ($notifications as $key => $notification) {
                
                $notification->read_at = Carbon::now();
                $notification->save();
            }

        }else{
            // Unread all

            $notifications = UserNotification::where([['id', '>', 0],['company_id', $company_id]])->get();

            foreach ($notifications as $key => $notification) {
                
                $notification->read_at = null;
                $notification->save();
            }

        }

        return response()->json(['status' => 'ok'], 200);
    }

    public function markRead($id, Request $request) {
        $notification = UserNotification::find($id);

        if (!$notification) {
            return response()->json(['error' => 'Notification not found'], 404);
        }

        $notification->read_at = Carbon::now();
        $notification->save();

        return response()->json(['success' => 'Notification marked as read'], 200);
    }

    public function markUnread($id, Request $request) {
        $notification = UserNotification::find($id);

        if (!$notification) {
            return response()->json(['error' => 'Notification not found'], 404);
        }

        $notification->read_at = null;
        $notification->save();

        return response()->json(['success' => 'Notification marked as unread'], 200);
    }

    public function delete($id, Request $request) {
        $notification = UserNotification::find($id);

        if ($notification) {
            $notification->delete();
        }

        return response()->json(['success' => 'Product deleted successfully']);
    }
}
