<?php

namespace App\Http\Controllers\web\home;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Userdata;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class myprofileController extends Controller
{
    public function profilepage()
    {
        $user = Auth::user();
        $voucherNotifications = [];
        $hasNewVoucher = false;
        $activeVouchers = [];
        $orderdata = null;

        if ($user) {
            $voucherNotifications = \App\Models\Notification::where('user_id', $user->id)
                ->where(function($query) {
                    $query->where('title', 'like', '%Voucher%')
                          ->orWhere('message', 'like', '%voucher%');
                })
                ->latest()
                ->get();

            $hasNewVoucher = \App\Models\Notification::where('user_id', $user->id)
                ->where('is_read', false)
                ->where(function($query) {
                    $query->where('title', 'like', '%Voucher%')
                          ->orWhere('message', 'like', '%voucher%');
                })
                ->exists();

            // Fetch active vouchers that this user has not used
            $allActive = \App\Models\Voucher::where('status', 'active')
                ->where('expiry_date', '>=', now()->toDateString())
                ->get();

            foreach ($allActive as $voucher) {
                $used = \App\Models\Order::where('userid', $user->id)
                    ->where('voucher_code', $voucher->code)
                    ->exists();
                if (!$used) {
                    $activeVouchers[] = $voucher;
                }
            }

            // Fetch paginated orders
            $orderdata = \App\Models\Order::where('userid', $user->id)
                ->orderBy('created_at', 'desc')
                ->paginate(5);
        }

        return view('web.home.profile.myprofile', compact('voucherNotifications', 'hasNewVoucher', 'activeVouchers', 'orderdata'));
    }

    public function user_address(Request $request)
    {
        try {
            $user = Auth::user();

        // Check if the user ID exists in the Userdata table
        $exists = Userdata::where('userid', $user->id)->exists();

        if ($exists) {
            $existdata = Userdata::where('userid', $user->id)->first();
            $existid = $existdata->id; // Accessing id property after making sure $existdata is not null

            $address = Userdata::find($existid);
            $address->address = $request->address;
            $address->address_two = $request->addresstwo;
            $address->city = $request->city;
            $address->area = $request->area;
            $address->zipcode = $request->zipcode;
            $result = $address->update();

            if ($result) {
                return redirect()->back();
            } else {
                return response()->json(['code' => 'false', 'msg' => 'something went wrong']);
            }
        } else {
            $address = new Userdata();
            $address->userid = $user->id;
            $address->address = $request->address;
            $address->address_two = $request->addresstwo;
            $address->city = $request->city;
            $address->area = $request->area;
            $address->zipcode = $request->zipcode;
            $address->status = 1;
            $result = $address->save();

            if ($result) {
                return redirect()->back();
            } else {
                return response()->json(['code' => 'false', 'msg' => 'something went wrong']);
            }
        }
        } catch (\Throwable $th) {
             DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
           ]);
        return redirect()->route('american.plastic.web');
        }
    }

    public function user_profiledata(Request $request)
    {
        try {
            $user = Auth::user();
        // Check if the user ID exists in the Userdata table
        $userdata = Userdata::where('userid', $user->id)->first();
        $userdataid = $userdata->id ?? null;

        if ($userdata) {
            $address = Userdata::find($userdataid);
            $address->first_name = $request->first_name;
            $address->last_name = $request->last_name;
            $address->dob = $request->date;
            $result = $address->update();
            if ($result) {
                return redirect()->back();
            } else {
                return response()->json(['code' => 'false', 'msg' => 'somethong went wrong']);
            }
        } else {
            $address = new Userdata();
            $address->userid = $user->id;
            $address->first_name = $request->first_name;
            $address->last_name = $request->last_name;
            $address->dob = $request->date;
            $address->status = 1;
            $result = $address->save();
            if ($result) {
                return redirect()->back();
            } else {
                return response()->json(['code' => 'false', 'msg' => 'somethong went wrong']);
            }
        }
        } catch (\Throwable $th) {
             DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
           ]);
        return redirect()->route('american.plastic.web');
        }
    }

    public function upload_profile_pic(Request $request){
       try {
         if ($request->hasFile('profile_img')) {
            $filename = time() . rand(1, 1000) . '.' . $request->profile_img->extension();
            $request->profile_img->move(public_path('assets/images/userpic'), $filename);
            $user=Auth::user();
            $data=User::where('id',$user->id)->first();
            $data->image=$filename;
            $result=$data->update();


            // Return a response indicating success
            return redirect()->back();
        } else {
            // Return a response indicating failure
            return response()->json(['success' => false, 'message' => 'No image uploaded']);
        }
       } catch (\Throwable $th) {
         DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
           ]);
        return redirect()->route('american.plastic.web');
       }
    }

    public function delete_profile_pic(Request $request){
        try {
            $user=Auth::user();
        $userdata=User::where('id',$user->id)->first();
        $userimg=$userdata->image;
        $file_old = './assets/images/userpic/' . $userimg;
        unlink($file_old);

        $userdata->image=null;
        $userdata->update();
        // Return a response indicating success
        return redirect()->back();
        } catch (\Throwable $th) {
           DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
           ]);
        return redirect()->route('american.plastic.web');
        }
    }

    public function user_logout()
    {
        Auth::logout();
        return redirect()->route('american.plastic.web');
    }
}
