<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Admin\Advertisement;
use App\Models\Admin\MainWallet;
use App\Models\User;
use App\Models\adsPost;
use App\Models\adsjobworker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use App\Models\Admin\Website;
use App\Models\Admin\JobFee;
use App\Models\Admin\UserMessage;




class UserAdvertisementController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('user.pages.ads');
    }

    public function advertisement_list()
    {
        $datas = Advertisement::where('user_id', Auth::user()->id)->latest()->take(100)->get();
        return view('user.pages.ads-list', compact('datas'));
    }

   public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'image' => 'required',
            'days' => 'required|numeric|min:1|max:7', // Adjust the max value based on your requirement
        ]);
    
        $days = $request->days;
        $cost = $request->amount;
    
        $request->session()->forget('ads_error');
        $request->session()->flash('ads_error', true);
    
        if(Auth::user()->deposit_balance < $cost){
            return redirect()->back();
        } else {
            $user_balance = User::find(Auth::user()->id);
            $user_balance->deposit_balance = $user_balance->deposit_balance - $cost;
            $user_balance->save();
    
            $main_wallet = MainWallet::latest()->first();
            $main_wallet->amount = $main_wallet->amount + $cost;
            $main_wallet->save();
        }
    
        $today = date("Y-m-d");
        $exp_date = date("Y-m-d", strtotime("$today +$days day"));
    
        $category = new Advertisement();
        $category->title = $request->input('title');
        $category->link = $request->input('link');
    
        $image = $request->file('image');
        if ($image) {
            $image_name = Str::random(20);
            $ext = strtolower($image->getClientOriginalExtension());
            $image_full_name = $image_name.'.'.$ext;
            $upload_path = 'backend/img/ads/';
            $image_url = $upload_path.$image_full_name;
            $success = $image->move($upload_path, $image_full_name);
        }
        $category->image = $image_url;
        $category->exp_date = $exp_date;
        $category->duration = $days;
        $category->cost = $cost;
        $category->user_id = Auth::user()->id;
        $category->save();
        
        $request->session()->forget('ads_error');
        $request->session()->flash('ads_success', true);
    
        return redirect()->back();
    }
    
    public function ads_create(){
        
        $website = Website::first();
        $jobFees = JobFee::first();
        
        $minimum_worker_ads = $website->minimum_worker_ads;
        $minimum_duration_ads = $website->minimum_duration_ads;
        $minimum_cost_per_worker = $website->minimum_cost_per_worker;
        $minimum_cost_per_duration = $website->minimum_cost_per_duration;
        $commission = $jobFees->fee;
        
        $data = AdsPost::orderBy('created_at', 'desc')->where('userID', Auth::user()->id)->paginate(10);
        // return $data;
        return view('user.pages.ads_post', compact('minimum_worker_ads', 'minimum_duration_ads', 'minimum_cost_per_worker', 'minimum_cost_per_duration','commission', 'data'));
    }
   
   public function ads_store(Request $request)
        {
            // return $request;
            // Get the first records for Website and JobFees
            $website = Website::first();
            $jobFees = JobFee::first();
        
            // Set the minimum values from the website settings and commission fee
            $minimum_worker_ads = $website->minimum_worker_ads;
            $minimum_duration_ads = $website->minimum_duration_ads;
            $minimum_cost_per_worker = $website->minimum_cost_per_worker;
            $minimum_cost_per_duration = $website->minimum_cost_per_duration;
            $commission = $jobFees->fee;
        
            // Validate request data
            $request->validate([
                'worker' => 'required|integer|min:' . $minimum_worker_ads,
                'duration' => 'required|integer|min:' . $minimum_duration_ads,
            ]);
        
            // Cost calculation logic
            $workerCost = $request->worker * $minimum_cost_per_worker;
            $durationCost = $request->duration * $minimum_cost_per_duration;
            
            $totalCost = $workerCost + $durationCost;
        
            // Add commission to the total cost
            $budget = $totalCost + ($totalCost / 100 * $commission);
        
            // Check if the user's deposit balance is sufficient
            $job_cost = $budget;
            if (Auth::user()->deposit_balance < $job_cost) {
                return redirect()->back()->with('error', 'Sorry, your deposit balance is less than your budget amount, please make a deposit.');
            } else {
                // Deduct the job cost from the user's deposit balance
                $user_balance = User::find(Auth::user()->id);
                $user_balance->deposit_balance = $user_balance->deposit_balance - $job_cost;
                $user_balance->save();
        
                // Ensure there is a MainWallet entry before updating
                $main_wallet = MainWallet::latest()->first();
                if ($main_wallet) {
                    $main_wallet->amount = $main_wallet->amount + $job_cost;
                    $main_wallet->save();
                } else {
                    return redirect()->back()->with('error', 'Error updating the wallet.');
                }
            }
            // Create a new Ads Post
            $ads_save = AdsPost::create([
                'userID' => Auth::user()->id,
                'user_name' => Auth::user()->name,
                'status' => 1,
                'ads_title' => $request->ads_title,
                'adsLink' => $request->adsLink,
                'worker' => $request->worker,
                'duration' => $request->duration,
                'cost' => $totalCost,
                'slug' => 'ads_' . time() . rand(1000, 9999),
                'created_at' => now('Asia/Dhaka'),  // This is optional if your model uses timestamps
            ]);
        
            if ($ads_save) {
                return redirect()->back()->with('message', 'Ads Post successfully created!');
            } else {
                return redirect()->back()->with('error', 'Failed to create Ads Post.');
            }
        }
        
        public function click_create()
        {
            $user = User::where('id', Auth::user()->id)->firstOrFail();
           
                
            // $datas = AdsPost::whereColumn('worker', '!=', 'worker_confirmed')->orderBy('created_at', 'desc')->get();
            
            $datas = AdsPost::whereColumn('worker','!=', 'worker_confirmed')->orderBy('created_at', 'desc')->get();
            // return $datas;
           
            $work_complates = adsjobworker::where('workerID', Auth::id())->pluck('verify')->toArray();
            
            // return $work_complates;
        
            return view('user.pages.ads_create', compact('datas', 'user', 'work_complates'));
        }
                
        public function updateStatus(Request $request, $id)
        {
            $data = AdsPost::findOrFail($id);

            if ($request->status == 1) { // Correct comparison
                $data->update([
                    'status' => 0,
                    'worker_confirmed' => $data->worker_confirmed + 1,
                ]);
                
                $ads_complate = new adsjobworker();
                $ads_complate->workerID = Auth::user()->id;
                $ads_complate->adsLink = $data->adsLink;
                $ads_complate->earn = $data->cost / $data->worker;
                $ads_complate->duration = $data->duration;
                $ads_complate->verify = $data->slug;
                $ads_complate->worker_name = Auth::user()->name;
                $ads_complate->save();
                
                $user = User::find($ads_complate->workerID);
                $user->click_earn_balance = $user->click_earn_balance + $data->cost / $data->worker;
                $user->save();
                
            }
        
            return response()->json(['message' => 'Status updated successfully'], 200);
        }
        
     public function bal_withdraw(Request $request, $id)
        {
            // Retrieve the user
            $user = User::findOrFail($id);
        
            // Validate the withdrawal amount
            if ($request->withdraw_bal <= 0) {
                return redirect()->back()->with('error', 'Invalid withdrawal amount.');
            }
        
            // if ($request->withdraw_bal > $user->click_earn_balance) {
            //     return redirect()->back()->with('error', 'Sorry, you don\'t have enough balance.');
            // }
        
            // Perform the balance update
            $click_balance = $request->withdraw_bal;
            $user->click_earn_balance -= $click_balance;
            $user->earning_balance += $click_balance;
        
            // Save the updated user record
            $user->save();
            
        // Create a success message for the user
        $upgradeMessage = new UserMessage();
        $upgradeMessage->user_id = $user->id;
        $upgradeMessage->message_title = 'Click and Earning Withdrawal';
        $upgradeMessage->message = 'Congratulations! You have successfully withdrawn $' . number_format($request->withdraw_bal, 4) . ' from your Click and Earning balance in Powerworkerearn.';
        $upgradeMessage->save();
    
        // Return success response with feedback message
        return back()->with('message', 'Your withdrawal of $' . number_format($request->withdraw_bal, 4) . ' was successful. Your balances have been updated.');
    }
   public function history($id)
    {
        $data = adsjobworker::where('workerID', $id)->paginate(50);
    
        $total_show_ads = adsjobworker::where('workerID', $id)->count();
        $total_credit = adsjobworker::where('workerID', $id)->sum('earn');
    
        return view('user.pages.ads_history', compact('data', 'total_show_ads', 'total_credit'));
    }
   public function history_buyer($slug)
    {
        $data = adsjobworker::where('verify', $slug)->get();
        $link = adsjobworker::where('verify', $slug)->latest()->first();
        $latest_link = $link->verify;
        
        // return $data;
        return view('user.pages.ads_history_buyer', compact('data', 'latest_link'));
    }



}
