<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Admin\Category;
use App\Models\Admin\Client;
use App\Models\Admin\Country;
use App\Models\Admin\Continent;
use App\Models\Admin\ContinentCountry;
use App\Models\Admin\Deposit;
use App\Models\Admin\LocationZone;
use App\Models\Admin\LocationZoneCountry;
use App\Models\Admin\Service;
use App\Models\Admin\SubCategory;
use App\Models\Admin\UserMessage;
use App\Models\Admin\Website;
use App\Models\Admin\MainWallet;
use App\Models\BoostSubCategory;
use App\Models\Job;
use App\Models\JobWork;
use App\Models\Policy;
use App\Models\TopDepositUserHeadline;
use App\Models\TopEarningUserHeadline;
use App\Models\TopReferralUserHeadline;
use App\Models\WithdrawHeadline;
use App\Models\DepositHeadline;
use App\Models\User;
use App\Models\AccountVerifyWithDocument;
use App\Models\PremiumPackage;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class UserDashboardController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Approve work more than 72 hours
        $approve_hour = site_info()->auto_approval_hour;
        JobWork::where('created_at', '<',Carbon::parse('-'.$approve_hour.' hours'))->where('status', 0)->update(['status' => 1]);
        $works = JobWork::where('created_at', '<',Carbon::parse('-'.$approve_hour.' hours'))->where('status', 0)->get();
        if($works->count() > 0){
            foreach($works as $work){
                $job_work = JobWork::find($work->id);

                $job = Job::find($job_work->job_id);
                if($job){
                    $user = User::find($job_work->user_id);
                    $user->earning_balance = $user->earning_balance + $job->each_worker_earn;
                    $user->save();
                }

                $job_work->status = 1;
                $job_work->save();
            }
        }
        
        // delete data more than 30 days
        
        // For auto user block-------------------
        $total_attempt = user_complete_job(Auth::user()->id);
        $total_pending = user_complete_job_pending(Auth::user()->id);
        $total_reject = user_complete_job_reject(Auth::user()->id);
        $total_approve = user_complete_job_approve(Auth::user()->id);
        if($total_attempt > 0){
            $total_activity_work = $total_attempt - ($total_pending + $total_reject);
            if($total_activity_work > 0){
                $approval_ratio = ($total_approve * 100) / $total_activity_work;
                $user_block_ration = site_info()->user_block_ratio;
                if($user_block_ration >= $approval_ratio){
                    update_user_block(Auth::user()->id);
                }
            }
        }
        // For auto user block end-------------------
        
        
        $date = Carbon::now()->subDays(60);
        JobWork::where('created_at', '<=', $date)->update(['trash' => 1]);
        // JobWork::where('created_at', '<=', $date)->delete();

        $location_zone = LocationZone::latest()->get();
        $continents = Continent::oldest()->get();
        $countries = Country::latest()->get();
        $categorys = Category::latest()->get();
        $job_found = job_found();
        $jobs = Job::where('status', 1)->where('worker_need', '!=', 'worker_confirmed')->latest()->get();
        return view('user.pages.home', compact('location_zone', 'continents', 'countries', 'categorys', 'jobs', 'job_found'));
    }
    public function survey_and_offers(){
        // // return 'Ok';
        // if(is_user_suspend(Auth::user()->id) == 1){
        //     Auth::logout();
        //     return redirect()->route('login');
        // }
        
        $userId = Auth::user()->id;
        // $datas = Deposit::where('approval', 1)->get();
        // $datas_withdraws = Withdraw::where('approval', 1)->get();
        // $loggedInUsers = User::where('last_login_at', '>=', now()->subMinutes(2))->count();
        // // return $userId;
        
        return view('user.pages.survey_and_offers', compact('userId'));

    }
    
    
    public function job_details($code)
    {
        $job = Job::where('code', $code)->first();
        if(!$job){
            return redirect()->back()->with('error','This job is not found!');
        }
        
        $title = 'Job details';
        return view('user.pages.my-job-details', compact('title', 'job'));
    }

    public function policy_details($slug)
    {
        $policy = Policy::where('slug', $slug)->first();
        return view('user.pages.policy', compact('policy'));
    }

   public function top_deposit_user()
{
    $top_users = Deposit::where('approval', 1)
        ->whereMonth('created_at', Carbon::now()->month)
        ->groupBy('user_id')
        ->select('user_id', DB::raw('SUM(amount) as total_amount'))
        ->orderBy('total_amount', 'desc')
        ->limit(10)
        ->get();

    $headlines = TopDepositUserHeadline::all();
    return view('user.pages.top-deposit-user', compact('top_users', 'headlines'));
}


    public function top_earning_user()
    {
        $top_users= User::take(10)->orderBy('earning_balance','DESC')->get();
        $headlines = TopEarningUserHeadline::all();
        return view('user.pages.top-earning-user', compact('top_users','headlines'));
    }


    public function userTotalJobs() {
    // Replace this logic with your own to calculate the user's total job count
    $userTotalJobs = 10; // Example value
    
    return view('user_total_jobs', ['userTotalJobs' => $userTotalJobs]);
}

public function top_referral_user()
    {
        $top_users= User::take(10)->orderBy('total_refer','DESC')->get();
        $headlines = TopReferralUserHeadline::all();
        return view('user.pages.top-referral-user', compact('top_users','headlines'));
    }
    
   public function top_job_posted_user()
{
    $top_users = Job::
        select('user_id', Job::raw('count(user_id) as total'))
        ->whereMonth('created_at', Carbon::now()->month)
        ->where('status', 1) // Add this line to filter by status
        ->groupBy('user_id')
        ->orderBy('total', 'desc')
        ->limit(15)
        ->get();

    $headlines = WithdrawHeadline::all();
    return view('user.pages.top-job-posted-user', compact('top_users', 'headlines'));
}

   public function top_job_worked_user()
{
    $top_users = JobWork::
        select('user_id', JobWork::raw('count(user_id) as total'))
        ->whereMonth('created_at', Carbon::now()->month)
        ->where('status', 1) // Add this line to filter by status
        ->groupBy('user_id')
        ->orderBy('total', 'desc')
        ->limit(50)
        ->get();

    $headlines = DepositHeadline::all();
    return view('user.pages.top-job-worked-user', compact('top_users', 'headlines'));
}


    public function account_instant_verify(){
        return view('user.pages.instant-verify');
    }

    public function instant_verify_my_account(){
        $user = User::find(Auth::user()->id);
        $user->deposit_balance = $user->deposit_balance - site_info()->instant_verify_cost;
        $user->is_verified = 1;
        $user->save();
        
        $main_wallet = MainWallet::latest()->first();
        $main_wallet->amount = $main_wallet->amount + site_info()->instant_verify_cost;
        $main_wallet->save();
        
        return redirect()->route('user.dashboard')->with('message', 'Your account successfullt verified');
    }
    
    public function account_verify_with_document_store(Request $request){
        $request->validate([
            'name' => 'required',
            'card_number' => 'required',
            'document_type' => 'required',
            'document_front' => 'required',
            'document_with_user' => 'required',
        ]);
        
        $check_old = AccountVerifyWithDocument::where('user_id', Auth::user()->id)->first();
        if($check_old){
            $data = AccountVerifyWithDocument::find($check_old->id);
            if(file_exists($data->document_front)){
                unlink($data->document_front);
            }
            if(file_exists($data->document_with_user)){
                unlink($data->document_with_user);
            }
        }else{
            $data = new AccountVerifyWithDocument();
            $data->user_id = Auth::user()->id;
        }
        
        $data->name = $request->name;
        $data->card_number = $request->card_number;
        $data->document_type = $request->document_type;
        
        $image = $request->file('document_front');
        if ($image) {
            $image_name = Str::random(20);
            $ext = strtolower($image->getClientOriginalExtension());
            $image_full_name = $image_name.'.'.$ext;
            $upload_path = 'backend/img/account/';
            $image_url = $upload_path.$image_full_name;
            $success = $image->move($upload_path, $image_full_name);
            $data->document_front = $image_url;
        }
        
        $image = $request->file('document_with_user');
        if ($image) {
            $image_name = Str::random(20);
            $ext = strtolower($image->getClientOriginalExtension());
            $image_full_name = $image_name.'.'.$ext;
            $upload_path = 'backend/img/account/';
            $image_url = $upload_path.$image_full_name;
            $success = $image->move($upload_path, $image_full_name);
            $data->document_with_user = $image_url;
        }
        
        $data->status = 1;
        $data->is_verified = 1;
        $data->save();
        
        // return redirect()->back()->with('message','Document successfully submited!');
        
        return redirect()->route('user.account-verify-with-document-success')->with('message', 'Document successfully submited!');
    }

    public function account_verify_with_document_success(){
        $title = "Documents successfully sumitted, Within 72hours we will check your documents and take proper action. Thank you!";
        return view('user.pages.account-verify-with-document-success', compact('title'));
    }



    public function message_list()
    {
        // Update 'seen' to 1 for all messages of the authenticated user
        UserMessage::where('user_id', Auth::user()->id)->update(['seen' => 1]);
    
        // Retrieve the latest 100 messages for the authenticated user
        $datas = UserMessage::where('user_id', Auth::user()->id)->latest()->take(100)->get();
    
        // Return the view with the retrieved data
        return view('user.pages.message-list', compact('datas'));
    }

    
    public function showSpinner()
    {
        // Add your code here to handle the 'show-spinner' route
        return view('spinner'); // This assumes your Blade view is named 'spinner.blade.php'
    }



    public function get_country(Request $request)
    {
        $location = $request->location_zone;

        $countrys = LocationZoneCountry::where('zone_id', $location)->orderBy('id', 'ASC')->get();
        $html = '';
        $html .= '<option value="">Select One</option>';
        if($countrys){
            foreach($countrys as $country){
                $ck_country = Country::find($country->country_id);
                if($ck_country){
                    $html .= '<option value="'.$ck_country->id.'">'.$ck_country->name.'</option>';
                }
            }
        }

        return $html;
    }


    public function get_sub_category(Request $request)
    {
        $category_id = $request->category_id;

        $sub_cats = SubCategory::where('category_id', $category_id)->orderBy('id', 'ASC')->get();
        $html = '';
        $html .= '<option value="">Select One</option>';
        if($sub_cats){
            foreach($sub_cats as $category){
                $html .= '<option value="'.$category->id.'">'.$category->name.'</option>';
            }
        }

        return $html;
    }
    
    public function get_sub_categorys(Request $request)
    {
        $category_id = $request->category_id;

        $sub_cats = SubCategory::where('category_id', $category_id)->orderBy('id', 'ASC')->get();
        $html = '';
        if($sub_cats){
            foreach($sub_cats as $category){
                $html .= '
                    <div class="category-item-div cchild-item '.$category->id.' m-0" onclick="selectSubCategory('. $category->id .', '.$category->minimum_cost.')">
                        <input data-cpc="0.02" data-upload="0" type="radio" name="sub_category" value="'.$category->id.'" id="radio-child-'.$category->id.'"><label class="zone-item" for="radio-child-'.$category->id.'">'.$category->name.'</label>
                    </div>
                ';
            }
        }

        return $html;
    }

    public function get_sub_category_price(Request $request)
    {
        $id = $request->sub_category;

        $sub_cats = SubCategory::find($id);
        return $sub_cats->minimum_cost;
    }

    public function get_new_task_complete_area(Request $request)
{
    $need_to_completed_step = $request->need_to_completed_step;
    $html = '
    <div class="text-label-join mb-5 bg-softer">
        <div class="form-group" id="another_area_'.$need_to_completed_step.'">
            <label for="link" class="form-label">Step '.' [ Max 150 character ] </label>
            <textarea class="form-control" name="specific_task[]" id="task_need_to_completed_area" cols="30" rows="5" maxlength="150" oninput="limitTextarea(this, 150); updateCharCount()"></textarea>
        </div>
    </div>
    ';

    return $html;
}


    public function get_boost_sub_category(Request $request)
    {
        $category_id = $request->category_id;

        $sub_cats = BoostSubCategory::where('category_id', $category_id)->get();
        $html = '<option value="">Select One</option>';
        foreach($sub_cats as $category){
            $html .= '<option value="'.$category->id.'-'.$category->cost.'">'.$category->id.'-'.$category->name.'</option>';
        }

        return $html;
    }

    public function get_boost_sub_category_data(Request $request){
        $data = BoostSubCategory::find($request->id);
        return $data->notice;
    }
    
    public function get_boost_sub_category_price(Request $request)
    {
        
        $id = $request->sub_category;
        return $sub_cat = BoostSubCategory::find(1);

        return ['cost'=>$sub_cat->cost, 'notice'=>$sub_cat->notice];
    }
    
    public function premium()
    {
        $title = 'Buy Plan';
        $datas = PremiumPackage::orderBy('id', 'ASC')->get();
        return view('user.pages.premium', compact('title', 'datas'));
    }
    
    public function active_premium(Request $request){
        $request->validate([
            'premium_duration' => 'required',
            'premium_user_cost' => 'required',
        ]);
        
        $user_balance = User::find(Auth::user()->id);
        $user_balance->deposit_balance = $user_balance->deposit_balance - $request->premium_user_cost;
        $user_balance->premium_package_id = $request->txt_pkg_id;
        $user_balance->premium_status = 1;
        $user_balance->premium_start_from = date('Y-m-d');
        $user_balance->premium_duration = $request->premium_duration;
        $user_balance->save();

        $main_wallet = MainWallet::latest()->first();
        $main_wallet->amount = $main_wallet->amount + $request->premium_user_cost;
        $main_wallet->save();
        
        return 'Successfully premium package activated!';
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
