<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Announcement;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;

class AnnouncementController extends Controller
{
    public function index(Request $request)
    {
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');

        // Generate a unique cache key based on request parameters
        $cacheKey = 'announcements_' . md5(json_encode([
            'keyword' => $keyword,
            'perPage' => $perPage,
            'sortBy' => $sortBy,
            'sortType' => $sortType,
        ]));

        // Check if data exists in cache, otherwise execute the query and cache the result
        $data = Cache::remember($cacheKey, 60, function () use ($keyword, $perPage, $sortBy, $sortType) {
            return Announcement::with('company')->where(function ($query) use ($keyword) {
                    $keyword = str_replace(" ", "%", $keyword);
                    $query->where('description', 'like', '%' . $keyword . '%');
                })
                ->when(!empty($sortBy) && !empty($sortType), function ($query) use ($sortBy, $sortType) {
                    $query->orderBy($sortBy, $sortType);
                })
                ->paginate($perPage);
        });

        return response()->json($data);
    }

    public function show(Request $request)
    {
        $user = Auth::user();

        $data = Announcement::where('expired_at', '>', now())->where('company_id', $user->default_company_id)->first();

        return response()->json($data);
    }

    public function store(Request $request)
    {
        $user = Auth::user();

        $request['created_by'] = $user->id;

        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'title' => [
                'required',
                'min:2',
                Rule::unique('announcements')->whereNull('deleted_at')
            ]
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {
            $data = Announcement::create($request->all());

            DB::connection()->commit();

            Cache::forget('announcements_');

            return response()->json([
                'message' => 'Record Successfully added!',
                'status' => 'success',
            ], 201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }


    public function update(Request $request, int $id)
    {
        $data = Announcement::where('id', $id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

        $validator = Validator::make($request->all(),
            [
                'description' => [
                    'required',
                    'min:2',
                    Rule::unique('announcements')->ignore($id)->whereNull('deleted_at')
                ]
            ]
        );

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {

            $data->fill($request->all());
            $data->save();

            $data->touch();

            DB::connection()->commit();

            // Invalidate cache for 'announcements_' key when a Announcement is updated
            Cache::forget('announcements_'); // Adjust cache key if necessary

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function destroy(int $id)
    {
        $data = Announcement::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],204);
        }
        DB::connection()->beginTransaction();
        $data->delete();
        DB::connection()->commit();
        return response()->json(['message' => "Record successfully deleted!"],201);
    }
}
