<?php

namespace App\Http\Controllers\Admin;

use App\Exports\RestaurantExport;
use App\Exports\RestaurantExportSelected;
use App\Http\Controllers\Controller;
use App\Models\ManageRestaurant;
use App\Models\OperatingHour;
use Illuminate\Http\Request;
use Exception;
use App\Helpers\onesignalhelper;
use App\Models\IamPrincipal;
use App\Models\ManageState;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;

class ManageRestrauntController extends Controller
{
    /*
   Created By : Sayli Raut
   Created at : 29 May 2024
   Use : To Get Restaurant Page.
   */
    public function index(Request $request)
    {
        $activeQuery = $request->query('active');
        if ($activeQuery == 1) {

            $restaurant = ManageRestaurant::where('is_active', 1)->latest()->get();
        } else if ($activeQuery == 0 && $activeQuery != null) {
            $restaurant = ManageRestaurant::where('is_active', 0)->latest()->get();
        } else {
            $restaurant = ManageRestaurant::latest()->get();
        }
        return view('Admin.pages.manage_restaurants.manage_restaurants', compact('restaurant'));
    }


    /*
   Created By : Sayli Raut
   Created at : 29 May 2024
   Use : To Add Restaurant Page.
   */
    public function add()
    {
        $state = ManageState::where('is_active', 1)->get()->toArray();
        return view('Admin.pages.manage_restaurants.add_restaurant',  compact('state'));
    }


    /*
   Created By : Sayli Raut
   Created at : 29 May 2024
   Use : To store resturant form.
   */
    public function store_restaurant(Request $request)
    {
        try {
            DB::beginTransaction();

            // Handling image upload
            if ($request->hasFile('image')) {
                $image = $request->file('image');
                $imagePath = saveSingleImageWithoutCrop($image, 'restaurant_images');
            } else {
                $imagePath = $request->image;
            }

            // Creating the restaurant
            $restaurant = new ManageRestaurant();
            $restaurant->name = $request->input('name');
            $restaurant->image = $imagePath;
            $restaurant->restaurant_id = $request->input('rest_id');
            $restaurant->address = $request->input('address');
            $restaurant->bio = $request->input('bio');
            $restaurant->latitude = $request->input('latitude');
            $restaurant->longtitude = $request->input('longitude');
            $restaurant->exclusion = $request->input('exclusion');
            $restaurant->phone_number = $request->input('phone_number');
            $restaurant->state_xid = $request->input('state_xid');
            $restaurant->try_on_1 = $request->input('try_on_1');
            $restaurant->try_on_2 = $request->input('try_on_2');
            $restaurant->try_on_3 = $request->input('try_on_3');
            $restaurant->try_on_4 = $request->input('try_on_4');
            $restaurant->save();

            foreach ($request->input('operating_hours') as $day => $hours) {
                OperatingHour::create([
                    'manage_restaurant_xid' => $restaurant->id,
                    'day_of_week' => $day,
                    'start_time' => $hours['start_time'],
                    'end_time' => $hours['end_time']
                ]);
            }

            $imagePath = ListingImageUrl('restaurant_images', $restaurant->image);

            $allCustomerOneSignalIds = IamPrincipal::select('id', 'one_signal_player_id')->where('is_active', 1)->where('notification_status', 1)->where('principal_type_xid', 3)->get();
            $title = "New " . $restaurant->name . " is added";
            $message = "New Restaurant is Now Live.";
            $content_type = 'New Restaurant Added';
            $imageUrl = $imagePath;

            foreach ($allCustomerOneSignalIds as $customerIdItem) {
                if ($customerIdItem->one_signal_player_id) {
                    onesignalhelper::sendNotificationApi(
                        $customerIdItem->one_signal_player_id,
                        $title,
                        $message,
                        $content_type,
                        $imageUrl,
                        $id = null
                    );
                }
                onesignalhelper::StoreNotificationDetails($customerIdItem->id, $content_type, $title, $imagePath);
            }


            DB::commit();
            return jsonResponseWithSuccessMessage(__('success.save_data'));
        } catch (Exception $e) {
            DB::rollBack();
            Log::error("Restaurant Store Page Load Failed: " . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }


    /*
   Created By : Sayli Raut
   Created at : 29 May 2024
   Use : To edit Restaurant Page.
   */
    public function edit_restaurant(Request $request, $id)
    {
        try {
            $operating_hours = OperatingHour::where('manage_restaurant_xid', $id)->get()->keyBy('day_of_week');
            $restaurantItem = ManageRestaurant::where('id', $id)->first();
            $state = ManageState::where('is_active', 1)->get()->toArray();
            $restaurantItem['image'] = ListingImageUrl('restaurant_images', $restaurantItem['image']);
            return view(
                'Admin.pages.manage_restaurants.edit_restaurant',
                compact(
                    'restaurantItem',

                    'operating_hours',
                    'state'
                )
            );
        } catch (Exception $e) {
            Log::error("edit voucher Page Load Failed " . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }

    /*
    Created By : Sayli Raut
    Created at : 29 May 2024
    Use : To Update Resturant Form.
    */
    public function update(Request $request)
    {
        try {
            DB::beginTransaction();

            $restaurant = ManageRestaurant::where('id', $request->id)->first();

            if ($request->hasFile('image')) {
                $image = $request->file('image');
                $imagePath = saveSingleImageWithoutCrop($image, 'restaurant_images');
            } else {
                $imagePath = $restaurant->image;
            }

            $restaurant->name = $request->input('name');
            $restaurant->description = $request->input('description');
            $restaurant->image = $imagePath;
            $restaurant->restaurant_id = $request->input('restaurant_id');
            $restaurant->address = $request->input('location_name');
            $restaurant->exclusion = $request->input('exclusion');
            $restaurant->phone_number = $request->input('phone_number');
            $restaurant->state_xid = $request->input('state_xid');
            $restaurant->latitude = $request->input('latitude');
            $restaurant->longtitude = $request->input('longitude');
            $restaurant->bio = $request->input('bio');
            $restaurant->try_on_1 = $request->input('try_on_1');
            $restaurant->try_on_2 = $request->input('try_on_2');
            $restaurant->try_on_3 = $request->input('try_on_3');
            $restaurant->try_on_4 = $request->input('try_on_4');
            $restaurant->save();

            foreach ($request->input('operating_hours') as $day => $hours) {
                $operatingHour = OperatingHour::where('manage_restaurant_xid', $restaurant->id)
                    ->where('day_of_week', $day)
                    ->first();

                if ($operatingHour) {
                    // Update existing record
                    $operatingHour->update([
                        'start_time' => $hours['start_time'],
                        'end_time' => $hours['end_time']
                    ]);
                } else {
                    // Create new record
                    OperatingHour::create([
                        'manage_restaurant_xid' => $restaurant->id,
                        'day_of_week' => $day,
                        'start_time' => $hours['start_time'],
                        'end_time' => $hours['end_time']
                    ]);
                }
            }

            DB::commit();

            return jsonResponseWithSuccessMessage(__('success.update_data'));
        } catch (Exception $e) {
            DB::rollBack();
            Log::error("update Restaurant Services Page Load Failed " . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }



    /*
   Created By : Sayli Raut
   Created at : 29 May 2024
   Use : To view restaurant Page.
   */
    public function viewRestaurant(Request $request, $id)
    {
        try {

            $restaurantItem = ManageRestaurant::where('id', $id)->first();
            $restaurantItem['image'] = ListingImageUrl('restaurant_images', $restaurantItem['image']);
            $operating_hours = OperatingHour::where('manage_restaurant_xid', $id)->get()->keyBy('day_of_week');

            return view('Admin.pages.manage_restaurants.view_restaurant', compact('restaurantItem', 'operating_hours'));
        } catch (Exception $e) {
            Log::error("view Voucher Load Failed" . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }

    /*
Created By : Sayli Raut
Created at : 30 May 2024
Use : To Update status of restaurant.
*/
    public function updateRestaurantStatus(Request $request)
    {
        try {
            DB::beginTransaction();
            $voucher_data = ManageRestaurant::where('id', $request->dataId)->first();
            $voucher_data->is_active = $request->status ?? 0;
            $voucher_data->save();
            DB::commit();

            return jsonResponseWithSuccessMessage(__('success.update_data'));
        } catch (Exception $e) {
            Log::error("Update Status function Load Failed " . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }

    /*
Created By : Sayli Raut
Created at : 30 May 2024
Use : To Delete  Restaurant.
*/
    public function deleteRestaurant(Request $request, $id)
    {
        try {

            DB::beginTransaction();
            $update = ManageRestaurant::where('id', $id)->update(['is_active' => 0]);
            $deleteRestaurant = ManageRestaurant::where('id', $id)->delete();
            DB::commit();

            return jsonResponseWithSuccessMessage(__('success.delete'));
        } catch (Exception $e) {
            Log::error("delete function Load Failed " . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }
    /*
    Created By : Sayli Raut
    Created at : 30 May 2024
    Use : To Get archieve restaurants.
    */
    public function archive_restaurant()
    {

        try {
            $restaurant = ManageRestaurant::onlyTrashed()->latest()->get();
            return view('Admin.pages.manage_restaurants.archive_manage_restaurant', compact('restaurant'));
        } catch (Exception $e) {
            Log::error("Manage Voucher Page Not Load " . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }


    /*
    Created By : Sayli Raut
    Created at : 30 May 2024
    Use : To archieve restaurant.
    */
    public function archive_delete_restaurant($id)
    {

        try {
            DB::beginTransaction();
            $restaurant = ManageRestaurant::find($id);
            $restaurant->delete();
            DB::commit();

            return jsonResponseWithSuccessMessage(__('success.update_data'));
        } catch (Exception $e) {
            DB::rollBack();
            Log::error("delete_passport function Load Failed " . $e->getMessage());
            return response()->json(['success' => false, 'status' => 500, 'message' => __('auth.something_went_wrong')]);
        }
    }



    /*
        Created By : Sayli Raut
        Created at : 30 May 2024
        Use : To Deleted Data Restore.
    */
    public function unarchive_restaurant($id)
    {

        try {
            DB::beginTransaction();
            ManageRestaurant::withTrashed()->where('id', $id)->restore();

            DB::commit();

            return response()->json(['success' => true, 'status' => 200]);
        } catch (Exception $e) {
            DB::rollBack();
            Log::error("delete_passport function Load Failed " . $e->getMessage());
            return response()->json(['success' => false, 'status' => 500, 'message' => __('auth.something_went_wrong')]);
        }
    }

    /*
        Created By : Sayli Raut
        Created at : 17 June 2024
        Use : To download Excel.
    */
    public function exportSelectedRestaurant(Request $request)
    {
        try {
            if ($request->has('all_id')) {
                return Excel::download(new RestaurantExport, 'Restaurant_data.xlsx');
            }

            $ids = $request->selected_id;
            // dd( $ids);
            $fileName = 'selected_restaurant_data.xlsx';
            return Excel::download(new RestaurantExportSelected($ids), $fileName);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Export failed. Something went wrong.'], 500);
        }
    }
}
