<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

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

class SubscriptionRenewalController extends Controller
{

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        //
        $keyword = $request->input('keyword', null);
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', 'expiration');
        if($keyword) $keyword = str_replace(" ", "%", $keyword);
        $sortType = $request->input('sortType', '');
        $data = SubscriptionRenewal::when($keyword, fn($q) => $q->where('name', 'like', '%' . $keyword . '%')
        ->orWhereHas('company', fn($qc) => $qc->where('name', 'like', '%' . $keyword . '%'))
        )
        ->when($sortBy, fn($q) => $q->orderBy($sortBy, $sortType))
        ->paginate($perPage);

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

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'subscription_id' => 'required',
            'company_id' => 'required',
        ]);

        /** 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
            ], 422);
        }

        DB::beginTransaction();

        try {

            $data = SubscriptionRenewal::create($request->all());

            DB::commit();

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

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

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

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

        $validator = Validator::make($request->all(),
            [
                'subscription_id' => 'required',
                'company_id' => 'required',
            ]
        );

        /** 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
            ], 422);
        }

        DB::beginTransaction();

        try {

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

            $data->touch();

            DB::commit();

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

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

    public function destroy(int $id)
    {
        $data = SubscriptionRenewal::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],422);
        }
        DB::beginTransaction();
        try {
            $data->delete();
            DB::commit();
            return response()->json(['message' => "Record successfully deleted!"],201);
        }
        catch(Throwable $e) {
            DB::rollback();
            return response()->json(['message' => "Unable to process request. Please contact system administrator.",
            'data' => $e->getMessage()
        ],422);
        }
    }
}
