<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Models\Discount;

class PostController extends Controller
{
    public function index(Request $request)
    {

        if ($request->ajax()) {

            $data = Discount::query();

            return Datatables::of($data)
                ->editColumn('expires_at', function ($row) {
                    return $row->created_at->format('d-m-Y H:i:s');
                })
                ->addIndexColumn()
                ->addColumn('action', function ($row) {
                    $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $row->id . '" data-original-title="Edit" class="btn btn-primary btn-xs editData"><i class="fa fa-edit"></i></a>';
                    $btn = $btn . ' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $row->id . '" data-original-title="Delete" class="btn btn-danger btn-xs deleteData"><i class="fa fa-trash"></i></a>';
                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }

        return view('admin.post');
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'name' => 'required',
            'code' => 'required',
            'quota' => 'required',
            'amount' => 'required',
        ]);

        Discount::updateOrCreate(
            [
                'id' => $request->id
            ],
            [
                'name' => $request->name,
                'code' => $request->code,
                'quota' => str_replace(',', '', $request->quota),
                'amount' => str_replace(',', '', $request->amount),
            ]
        );

        $code = 200;
        $message = 'OK';
        return response()->json([
            'response' => null,
            'metadata' => [
                'code' => $code,
                'message' => $message
            ]
        ], $code);
    }

    public function show($id): JsonResponse
    {
        $data = Discount::find($id);
        return response()->json($data);
    }

    public function edit($id): JsonResponse
    {
        $data = Discount::find($id);
        return response()->json($data);
    }

    public function destroy(Request $request): JsonResponse
    {
        $request->validate([
            'id' => 'required|integer|exists:discounts,id',
        ]);
        $updated = Discount::find($request->id)?->delete();
        return response()->json([
            'response' => null,
            'metadata' => [
                'code' => $updated ? 200 : 404,
                'message' => $updated ? 'OK' : 'Record not found or already inactive',
            ]
        ], $updated ? 200 : 404);
    }
}
