/home/kueuepay/www/app/Http/Controllers/Frontend/AnnouncementController.php
<?php

namespace App\Http\Controllers\Frontend;

use Exception;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Constants\GlobalConst;
use App\Http\Helpers\Response;
use App\Models\Admin\Language;
use App\Constants\LanguageConst;
use App\Http\Controllers\Controller;
use App\Models\Frontend\Announcement;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Validator;
use App\Models\Frontend\AnnouncementCategory;

class AnnouncementController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function categoryIndex()
    {
        $page_title = "Announcement Category";
        $categories = AnnouncementCategory::orderByDesc("id")->get();
        $languages = Language::get();
        return view('admin.sections.setup-sections.announcement.category.index',compact('page_title','categories','languages'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function categoryStore(Request $request)
    {
        $basic_field_name = [
            'name'          => "required|string|max:150",
        ];

        $data['language']  = $this->contentValidate($request,$basic_field_name);

        try{
            AnnouncementCategory::create([
                'name'          => $data,
                'created_at'    => now(),
                'status'        => true,
            ]);
        }catch(Exception $e) {
            return back()->with(['error' => ['Something went wrong! Please try again']]);
        }

        return back()->with(['success' => ['Category added successfully!']]);
    }

    public function categoryUpdate(Request $request) {
        $validated = $request->validate([
            'target'    => "required|numeric|exists:announcement_categories,id",
        ]);

        $basic_field_name = [
            'name_edit'          => "required|string",
        ];

        $category = AnnouncementCategory::find($validated['target']);

        $language_wise_data = $this->contentValidate($request,$basic_field_name,"category-update");
        if($language_wise_data instanceof RedirectResponse) return $language_wise_data;

        $language_wise_data = array_map(function($language) {
            return replace_array_key($language,"_edit");
        },$language_wise_data);

        $data['language']  = $language_wise_data;

        try{
            $category->update([
                'name'      => $data,
            ]);
        }catch(Exception $e) {
            return back()->with(['error' => ['Something went wrong! Please try again']]);
        }

        return back()->with(['success' => ['Category updated successfully!']]);
    }


    public function categoryStatusUpdate(Request $request) {
        $validator = Validator::make($request->all(), [
            'status'                    => 'required|boolean',
            'input_name'                => 'required|string',
            'data_target'               => 'required|integer|exists:announcement_categories,id',
        ]);

        if ($validator->stopOnFirstFailure()->fails()) {
            $error = ['error' => $validator->errors()];
            return Response::error($error, null, 400);
        }
        $validated = $validator->validate();

        
        try {
            $category = AnnouncementCategory::find($validated['data_target']);
            if($category) {
                $category->update([
                    'status'    => ($validated['status'] == true) ? false : true,
                ]);
            }
        } catch (Exception $e) {
            $error = ['error' => ['Something went wrong!. Please try again.']];
            return Response::error($error, null, 500);
        }

        $success = ['success' => [__('Category status updated successfully!')]];
        return Response::success($success, null, 200);
    }

    /**
     * Remove the specified resource from record.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function categoryDelete(Request $request)
    {
        $request->validate([
            'target'    => "required|integer|exists:announcement_categories,id",
        ]);

        try{
            $category = AnnouncementCategory::find($request->target);
            if($category) $category->delete();
        }catch(Exception $e) {
            return back()->with(['error' => ['Something went wrong! Please try again']]);
        } 

        return back()->with(['success' => ['Category deleted successfully!']]);
    }

    public function announcementIndex() {
        $page_title = "Announcements";
        $announcements = Announcement::orderByDesc("id")->get();

        return view('admin.sections.setup-sections.announcement.index',compact('page_title','announcements'));
    }

    public function announcementCreate() {
        $page_title = "Create New Announcement";
        $categories = AnnouncementCategory::orderByDesc("id")->where("status",GlobalConst::ACTIVE)->get();
        $languages = Language::get();

        return view('admin.sections.setup-sections.announcement.create',compact("page_title","categories","languages"));
    }

    public function announcementStore(Request $request) {
        $basic_field_name = [
            'title'         => "required|string|max:255",
            'description'   => "required|string|max:5000000",
            'tags'          => "required|array",
        ];

        $data['language']  = $this->contentValidate($request,$basic_field_name);

        $validated = Validator::make($request->all(),[
            'category'  => "required|integer|exists:announcement_categories,id",
        ])->validate();

        // make slug
        $not_removable_lang = LanguageConst::NOT_REMOVABLE;
        $slug_text = $data['language'][$not_removable_lang]['title'] ?? "";
        if($slug_text == "") {
            $slug_text = $data['language'][get_default_language_code()]['title'] ?? "";
            if($slug_text == "") {
                $slug_text = Str::uuid();
            }
        }
        $slug = Str::slug(Str::lower($slug_text));

        if(Announcement::where('slug',$slug)->exists()) return back()->with(['error' => ['Announcement title is similar. Please update/change this title']]);

        $data['image'] = null;
        if($request->hasFile("image")) {
            $data['image']  = $this->imageValidate($request,"image",null);
        }

        try{
            Announcement::create([
                'slug'                      => $slug,
                'announcement_category_id'  => $validated['category'],
                'data'                      => $data,
            ]);
        }catch(Exception $e) {
            return back()->with(['error' => ['Something went wrong. Please try again']]);
        }

        return redirect()->route('admin.setup.sections.announcement.index')->with(['success' => ['Announcement created successfully!']]);
    }

    public function announcementStatusUpdate(Request $request) {
        $validator = Validator::make($request->all(), [
            'status'                    => 'required|boolean',
            'input_name'                => 'required|string',
            'data_target'               => 'required|integer|exists:announcements,id',
        ]);

        if ($validator->stopOnFirstFailure()->fails()) {
            $error = ['error' => $validator->errors()];
            return Response::error($error, null, 400);
        }
        $validated = $validator->validate();

        
        try {
            $announcement = Announcement::find($validated['data_target']);
            if($announcement) {
                $announcement->update([
                    'status'    => ($validated['status'] == true) ? false : true,
                ]);
            }
        } catch (Exception $e) {
            $error = ['error' => ['Something went wrong!. Please try again.']];
            return Response::error($error, null, 500);
        }

        $success = ['success' => [__('Announcement status updated successfully!')]];
        return Response::success($success, null, 200);
    }

    public function announcementDelete(Request $request) {
        $request->validate([
            'target'    => "required|integer|exists:announcements,id"
        ]);

        try{
            $announcement = Announcement::find($request->target);
            if($announcement) {
                $image_name = $announcement->data?->image ?? null;
                if($image_name) {
                    $image_link = get_files_path('site-section') . "/" . $image_name;
                    delete_file($image_link);
                }
                $announcement->delete();
            }
        }catch(Exception $e) {
            return back()->with(['error' => ['Something went wrong. Please try again']]);
        }
        return back()->with(['success' => ['Announcement deleted successfully!']]);
    }

    public function announcementEdit($id) {
        $announcement = Announcement::find($id);
        if(!$announcement) return back()->with(['error' => ['Announcement does\'t exists!']]);
        $page_title = "Announcement Edit";
        $languages = Language::get();
        $categories = AnnouncementCategory::where("status",GlobalConst::ACTIVE)->orderByDesc("id")->get();
        return view('admin.sections.setup-sections.announcement.edit',compact("page_title","announcement","languages","categories"));
    }

    public function announcementUpdate(Request $request,$id) {

        $announcement = Announcement::find($id);
        if(!$announcement) return back()->with(['error' => ['Announcement does\'t exists!']]);

        $basic_field_name = [
            'title'         => "required|string|max:255",
            'description'   => "required|string|max:5000000",
            'tags'          => "required|array",
        ];

        $data['language']  = $this->contentValidate($request,$basic_field_name);

        $validated = Validator::make($request->all(),[
            'category'  => "required|integer|exists:announcement_categories,id",
        ])->validate();

        $data['image'] = $announcement->data?->image ?? null;
        if($request->hasFile("image")) {
            $data['image']  = $this->imageValidate($request,"image",$data['image']);
        }

        try{
            $announcement->update([
                'announcement_category_id'  => $validated['category'],
                'data'                      => $data,
            ]);
        }catch(Exception $e) {
            return back()->with(['error' => ['Something went wrong. Please try again']]);
        }

        return redirect()->route('admin.setup.sections.announcement.index')->with(['success' => ['Announcement updated successfully!']]);
    }

    /**
     * Method for validate request data and re-decorate language wise data
     * @param object $request
     * @param array $basic_field_name
     * @return array $language_wise_data
     */
    public function contentValidate($request,$basic_field_name,$modal = null) {
        $languages = Language::get();

        $current_local = get_default_language_code();
        $validation_rules = [];
        $language_wise_data = [];
        foreach($request->all() as $input_name => $input_value) {
            foreach($languages as $language) {
                $input_name_check = explode("_",$input_name);
                $input_lang_code = array_shift($input_name_check);
                $input_name_check = implode("_",$input_name_check);
                if($input_lang_code == $language['code']) {
                    if(array_key_exists($input_name_check,$basic_field_name)) {
                        $langCode = $language['code'];
                        if($current_local == $langCode) {
                            $validation_rules[$input_name] = $basic_field_name[$input_name_check];
                        }else {
                            $validation_rules[$input_name] = str_replace("required","nullable",$basic_field_name[$input_name_check]);
                        }
                        $language_wise_data[$langCode][$input_name_check] = $input_value;
                    }
                    break;
                } 
            }
        }
        if($modal == null) {
            $validated = Validator::make($request->all(),$validation_rules)->validate();
        }else {
            $validator = Validator::make($request->all(),$validation_rules);
            if($validator->fails()) {
                return back()->withErrors($validator)->withInput()->with("modal",$modal);
            }
            $validated = $validator->validate();
        }

        return $language_wise_data;
    }

    /**
     * Method for validate request image if have
     * @param object $request
     * @param string $input_name
     * @param string $old_image
     * @return boolean|string $upload
     */
    public function imageValidate($request,$input_name,$old_image = null) {
        if($request->hasFile($input_name)) {
            $image_validated = Validator::make($request->only($input_name),[
                $input_name         => "image|mimes:png,jpg,webp,jpeg,svg",
            ])->validate();

            $image = get_files_from_fileholder($request,$input_name);
            $upload = upload_files_from_path_dynamic($image,'site-section',$old_image);
            return $upload;
        }

        return false;
    }
}
FAQ

FAQ

1. What is the Kueue Pay Payment Gateway?

The Kueue Pay Payment Gateway is an innovative technology that facilitates seamless and secure transactions between merchants and their customers. It enables businesses to accept debit and credit card payments both online and in physical stores.

2. How does the Kueue Pay Payment Gateway work?

The Kueue Pay Payment Gateway acts as a bridge between a merchant’s website or point-of-sale system and the payment processing network. It securely transmits payment information, authorizes transactions, and provides real-time status updates.

3. What is the advantage of using Kueue Pay’s Developer API?

The Kueue Pay Developer API empowers developers and entrepreneurs to integrate the Kueue Pay Payment Gateway directly into their websites or applications. This streamlines the payment process for customers and provides businesses with a customizable and efficient payment solution.

4. How can I access the Kueue Pay Developer API?

To access the Kueue Pay Developer API, you need to sign up for a developer account on our platform. Once registered, you’ll receive an API key that you can use to authenticate your API requests.

5. What types of transactions can I handle with the Kueue Pay Developer API?

The Kueue Pay Developer API allows you to initiate payments, check the status of payments, and process refunds. You can create a seamless payment experience for your customers while maintaining control over transaction management.

6. Is the Kueue Pay Developer API suitable for my business size and industry?

Yes, the Kueue Pay Developer API is designed to accommodate businesses of varying sizes and industries. Whether you’re a small online store or a large enterprise, our API can be tailored to fit your specific payment needs.

7. How user-friendly is the Kueue Pay Developer API integration process?

The Kueue Pay Developer API is designed with simplicity and ease of use in mind. Our comprehensive documentation, code samples, and developer support resources ensure a smooth integration process for any web platform.

8. Are there any fees associated with using the Kueue Pay Payment Gateway and API?

We offer competitive pricing plans for using the Kueue Pay Payment Gateway and Developer API. Details about fees and pricing tiers can be found on our developer portal.

9. Can I customize the payment experience for my customers using the Kueue Pay API?

Absolutely, the Kueue Pay Developer API offers customization options that allow you to tailor the payment experience to match your brand and user interface. You can create a seamless and cohesive payment journey for your customers.

10. What kind of support is available if I encounter issues during API integration?

We provide dedicated developer support to assist you with any issues or questions you may have during the API integration process. Reach out to our support team at developersupport@NFCPay.com for prompt assistance.

Remember, our goal is to empower your business with a robust and efficient payment solution. If you have any additional questions or concerns, feel free to explore our developer portal or contact our support team.