<?php

namespace App\Http\Controllers\KetentuanUmum;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Storage;
use Log;
use DB;
use Exception;
use Carbon\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Validator;

use App\Models\KetentuanUmum\KetentuanUmum;

class KetentuanUmumController extends Controller
{
    public function __construct()
    {
        
    }

    public function index(Request $request)
    {
        try {

            $KetentuanUmum = KetentuanUmum::whereNull('deleted_at')->first();

            return response()->json([
                'status' => true,
                'message' => 'Berhasil mengambil data',
                'data' => $KetentuanUmum
            ], 200);

        } catch (Exception $e) {
            Log::error('KetentuanUmumController - index : '. $e->getMessage());
            return response()->json([
                'status' => false,
                'message' => 'Gagal menghubungkan ke server'
            ], 500);
        }
    }

    public function update(Request $request)
    {

        try {
            validation($request, [
                'konten' => 'required|regex:/^[a-zA-Z0-9\s\/\;,+-_:=]+$/'
            ]);
        } catch (ValidationException $e) {
            Log::error('KetentuanUmumController - update - validasi : '. json_encode($e->validator->errors()));
            return response()->json([
                'status' => false,
                'message' => 'Failed validation',
                'errors' => $e->validator->errors()
            ], 422);
        }

        try {

            if (base64_encode(base64_decode($request->konten, true)) !== $request->konten) {
                return response()->json([
                    'status' => false,
                    'data' => [],
                    'message' => 'Isian Konten tidak valid'
                ], 422);
            }
            
            $KetentuanUmum = KetentuanUmum::first();

            if (empty($KetentuanUmum)) {
                $KetentuanUmum = new KetentuanUmum;
                $KetentuanUmum->create([
                    'konten' => $request->konten
                ]);
            } else {
                $KetentuanUmum->update([
                    'konten' => $request->konten
                ]);
            }

            $KetentuanUmum = KetentuanUmum::first();

            return response()->json([
                'status' => true,
                'data' => $KetentuanUmum,
                'message' => 'Berhasil menyimpan data'
            ], 200);

        } catch (Exception $e) {
            Log::error('KetentuanUmumController - update : '. $e->getMessage());
            return response()->json([
                'status' => false,
                'data' => [],
                'message' => 'Gagal menghubungkan ke server'
            ], 500);
        }
    }

}
