<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Common;
use App\Models\Creator_Package;
use App\Models\Creator_Package_Transaction;
use App\Models\User;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Validator;

class CreatorPackageController extends Controller
{
    private $folder = "creator_package";
    public $common;
    public function __construct()
    {
        $this->common = new Common;
    }

    public function index(Request $request)
    {
        try {
            $params['data'] = [];
            $params['creator'] = User::where('is_creator', 1)->latest()->get();
            if ($request->ajax()) {

                $input_search = $request['input_search'];
                $input_user = $request['input_user'];

                $query = Creator_Package::query();
                if (!empty($input_search)) {
                    $query->where(function ($q) use ($input_search) {
                        $q->where('name', 'LIKE', "%{$input_search}%")->orWhere('price', 'LIKE', "%{$input_search}%");
                    });
                }
                if ($input_user != "all") {
                    $query->where('user_id', $input_user);
                }
                $data = $query->with('creator')->latest()->get();

                $this->common->imageNameToUrl($data, 'image', $this->folder);

                return DataTables()::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function ($row) {
                        $creator_package_delete = __('Label.delete_creator_package');

                        $delete = ' <form onsubmit="return confirm(\'' . $creator_package_delete . '\');" method="POST"  action="' . route('creator_package.destroy', [$row->id]) . '">
                                <input type="hidden" name="_token" value="' . csrf_token() . '">
                                <input type="hidden" name="_method" value="DELETE">
                                <button type="submit" class="edit-delete-btn" style="outline: none;"><i class="fa-solid fa-trash-can fa-xl"></i></button></form>';

                        $btn = '<div class="d-flex justify-content-around">';
                        $btn .= '<a href="' . route('creator_package.edit', [$row->id]) . '" class="edit-delete-btn">';
                        $btn .= '<i class="fa-solid fa-pen-to-square fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= $delete;
                        $btn .= '</a></div>';
                        return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
            }
            return view('admin.creator_package.index', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function create()
    {
        try {
            $params['data'] = [];
            $params['creator'] = User::where('is_creator', 1)->latest()->get();
            return view('admin.creator_package.add', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_id' => 'required',
                'name' => 'required',
                'price' => 'required',
                'time' => 'required',
                'type' => 'required',
                'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            $requestData = $request->all();

            if (isset($requestData['image'])) {
                $files = $requestData['image'];
                $requestData['image'] = $this->common->saveImage($files, $this->folder, "pack_");
            }
            $requestData['android_product_package'] = isset($request->android_product_package) ? $request->android_product_package : "";
            $requestData['ios_product_package'] = isset($request->ios_product_package) ? $request->ios_product_package : "";
            $requestData['web_product_package'] = isset($request->web_product_package) ? $request->web_product_package : "";

            $package_data = Creator_Package::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($package_data->id)) {
                return response()->json(array('status' => 200, 'success' => __('Label.data_add_successfully')));
            } else {
                return response()->json(array('status' => 400, 'errors' => __('Label.data_not_added')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function edit($id)
    {
        try {
            $params['data'] = Creator_Package::where('id', $id)->first();
            if ($params['data'] != null) {

                $this->common->imageNameToUrl(array($params['data']), 'image', $this->folder);
                $params['creator'] = User::where('is_creator', 1)->latest()->get();

                return view('admin.creator_package.edit', $params);
            } else {
                return redirect()->back()->with('error', __('Label.page_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function update(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_id' => 'required',
                'name' => 'required',
                'price' => 'required',
                'image' => 'image|mimes:jpeg,png,jpg|max:2048',
                'type' => 'required',
                'time' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            $requestData = $request->all();

            if (isset($requestData['image'])) {
                $files = $requestData['image'];
                $requestData['image'] = $this->common->saveImage($files, $this->folder, "pack_");

                $this->common->deleteImageToFolder($this->folder, basename($requestData['old_image']));
            }
            unset($requestData['old_image']);

            $requestData['android_product_package'] = isset($request->android_product_package) ? $request->android_product_package : "";
            $requestData['ios_product_package'] = isset($request->ios_product_package) ? $request->ios_product_package : "";
            $requestData['web_product_package'] = isset($request->web_product_package) ? $request->web_product_package : "";

            $package_data = Creator_Package::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($package_data->id)) {
                return response()->json(array('status' => 200, 'success' => __('Label.data_edit_successfully')));
            } else {
                return response()->json(array('status' => 400, 'errors' => __('Label.data_not_updated')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function destroy($id)
    {
        try {
            $data = Creator_Package::where('id', $id)->first();

            if (isset($data)) {
                $this->common->deleteImageToFolder($this->folder, $data['image']);
                
                Creator_Package_Transaction::where('creator_package_id', $data['id'])->update(['status' => 0]);
                $data->delete();
            }

            return redirect()->route('creator_package.index')->with('success', __('Label.data_delete_successfully'));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
}
