<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\AgentProductList;
use App\Models\Agent;
use App\Models\AgentDeliveryCharge;

// use Excel;

class AgentController extends Controller
{
	public function agentDetails(Request $request)
	{
        $result = DB::table('agents')->get();
        return view('admin.agent.agent_details', compact('result','request'));
	}

    public function agentProductList($id,Request $request)
    {   
        $agents = DB::table('agents')->get();
                  
        $agent_id=decrypt($id);
        $result = DB::table('agent_product_list')  // change to your actual table
                    ->where('agent_id', $agent_id)
                    ->orderBy('created_at', 'desc')
                    ->get();

        $agent_delivery_charge = AgentDeliveryCharge::where('agent_id', $agent_id)->get();
        // dd($agent_delivery_charge);
        if($agent_id){
            $agent=DB::table('agents')->where('id',$agent_id)->first();            
        }

        return view('admin.agent.agent_product_list', compact('agent_id','agent_delivery_charge','agent','agents','result','request'));            
        
        // $html = '';
        
        // if(!$agentData->isEmpty()) {
        //     foreach ($agentData as $data) {
        //         $html .= "<p>{$data->item}</p>";
        //     }
            
        // }else{
        //     $html .= "<p>No data found for this agent.</p>";
        // }

        // return $html;
        
    }
    public function importexcel(Request $request,$id){
        $id = decrypt($id);
        $agent = DB::table('agents')->where('id',$id)->first();

        if($request->isMethod('POST')){
            $titles = $request->input('title');
            $prices = $request->input('price');
            $gsts = $request->input('gst');
            $without_gsts = $request->input('without_gst');
            $personalized = $request->input('personalized');

            $tableItems = [];

            foreach ($titles as $i => $title) {
                $tableItems[] = [
                    'title' => $title,
                    'price' => $prices[$i],
                    'gst' => $gsts[$i],
                    'without_gst' => $without_gsts[$i],
                    'personalized' => $personalized[$i],
                ];
            }

            foreach ($tableItems as $tableItem) {
                 DB::connection('mysql')->table('agent_product_list')->insert([
                    'agent_id' => $id,
                    'item' => $tableItem['title'],
                    'price' => $tableItem['price'],
                    'gst' => $tableItem['gst'],
                    'price_without_gst' => $tableItem['without_gst'],
                    'is_personalized' => $tableItem['personalized'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            }
            return redirect('/admin/agent/agent-product-list/' . encrypt($id))->with('success', 'Uploaded Successfully');

        }else{
            return view('admin.agent.import_excel',compact('id','agent'));
        }
    }

    public function deliveryChargeEdit($id = null, Request $request)
    {
        $adc_id = decrypt($id);
        $dataDetails  = AgentDeliveryCharge::where('id',$adc_id)->first();
        // dd($dataDetails);
        
        $obj = new AgentDeliveryCharge;
         
        if($request->isMethod('POST')){
            // dd('hello');
            
            $request->validate([

                's_delivery'=>'required',
                'm_delivery'=>'required',
                'e_delivery'=>'required',
            ]);

            $formid = $request->formid;
            //dd($request->item);
            $update_arr['s_delivery'] = $request->s_delivery;
            $update_arr['m_delivery'] = $request->m_delivery;
            $update_arr['e_delivery'] = $request->e_delivery;
            $update_arr['updated_at'] = date('Y-m-d H:i:s');
            
            if(AgentDeliveryCharge::where(['id' => $formid])->update($update_arr)){
                $request->session()->flash('alert-success', 'Agent dlivery charges updated.');
                // return redirect()->route('admin.agent.list');
                return redirect()->route('admin.agent.agentProductList', ['id' => encrypt($dataDetails->agent_id)]);
            }else{
                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
                return redirect()->back()->with($request->except(['_method', '_token']));
            }
        }
        return view('admin.agent.agent_delivery_charge_edit', compact('dataDetails','request'));
    }

    public function agentProductAdd($agent_id,Request $request){

        // $agents = DB::table('agents')->get();
        $agent_id=decrypt($agent_id);

        $obj = new AgentProductList;

        if($request->isMethod('POST')){

            $request->validate([
                
                'item'=>'required',
                'price'=>'required',
                'gst'=>'required',
                'price_without_gst'=>'required',
                'is_personalized'=>'required'
                ]);

                if($blog = $obj->create([
                    
                    'agent_id' => $agent_id,
                    'item' => $request->item,
                    'slug' => $request->slug,
                    'price' => $request->price,
                    'gst' => $request->gst,
                    'price_without_gst' => $request->price_without_gst, 
                    'is_personalized' => $request->is_personalized,

                ]))
              
                {
                    $request->session()->flash('alert-success', 'Agent Product successfully added.');
                    // return redirect()->route('admin.agent.list');
                    return redirect()->route('admin.agent.agentProductList', ['id' => encrypt($agent_id)]);
                }else{
                    $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
                    return redirect()->back()->with($request->except(['_method', '_token']));
                }

        }
        return view('admin.agent.agent_product_add', compact('agent_id','request'));
    }

    public function agentProductEdit($id = null, Request $request)
    {
        $apl_id = decrypt($id);
        $dataDetails  = DB::table('agent_product_list')->where('id',$apl_id)->first();
        
        $obj = new AgentProductList;
         
        if($request->isMethod('POST')){
            // dd('hello');
            
            $request->validate([

                'item'=>'required',
                'price'=>'required',
                'gst'=>'required',
                'without_gst'=>'required',
                'is_personalized'=>'required'
            ]);

            $formid = $request->formid;
            //dd($request->item);
            $update_arr['item'] = $request->item;
            $update_arr['slug'] = $request->slug;
            $update_arr['price'] = $request->price;
            $update_arr['gst'] = $request->gst;
            $update_arr['price_without_gst'] = $request->without_gst;
            $update_arr['is_personalized'] = $request->is_personalized;
            $update_arr['updated_at'] = date('Y-m-d H:i:s');
            
            if(AgentProductList::where(['id' => $request->formid])->update($update_arr)){
                $request->session()->flash('alert-success', 'Agent product successfully updated.');
                // return redirect()->route('admin.agent.list');
                return redirect()->route('admin.agent.agentProductList', ['id' => encrypt($dataDetails->agent_id)]);
            }else{
                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
                return redirect()->back()->with($request->except(['_method', '_token']));
            }
        }
        return view('admin.agent.agent_product_edit', compact('dataDetails','request'));
    }

    public function agentProductDelete($id = null, Request $request)
    {
        if($id == null){
            return redirect()->back();
            // return redirect()->route('admin.testimonial.list', ['id' => 1]);
        }
        $id = base64_decode($id);
        $dataDetails  = DB::table('agent_product_list')->where('id',$id)->first();
        //@unlink(public_path() . '/uploaded/event_images/' . $event_details->eimg);

        if(AgentProductList::where(['id' => $id])->delete()){
            $request->session()->flash('alert-success', 'Product deleted successfully.');
            return redirect()->route('admin.agent.agentProductList', ['id' => encrypt($dataDetails->agent_id)]);
        }else{
            $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
            return redirect()->back();
        }
    }

    public function allAgents(Request $request){
        $agents = DB::connection('mysql')->table('agents')->get();
        return view('admin.agent.all_agents_list',compact('agents'));          
    }

    public function add(Request $request){

        $obj = new Agent();

        if($request->isMethod('POST')){

            $request->validate([
                'name' => 'required',
                'password' => 'min:6',
                'cpassword' => 'required_with:password|same:password|min:6',
                'email' => 'required|unique:agents,email'
            ]);

            $agent = $obj->create([

                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),

            ]);

            //$agent_id=$agent->id;
            //dd($agent);
            if($agent){

                DB::connection('mysql')->table('agent_delivery_charge')->insert([
                    'agent_id' => $agent->id,
                    's_delivery' => 0,
                    'm_delivery' => 0,
                    'e_delivery' => 0
                ]);

                $request->session()->flash('alert-success', 'Agent successfully added.');
                return redirect()->route('admin.agent.allAgents');
            }else{
                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
                return redirect()->back()->withInput($request->except(['_method', '_token']));
            }
        }
        return view('admin.agent.agent_add', compact('request'));
    }

    public function edit($id = null, Request $request)
    {
        $agent_id = decrypt($id);
        $agentDetails  = Agent::where('id',$agent_id)->first();
        
        $obj = new Agent;
         
        if($request->isMethod('POST')){
            // dd('hello');
            
            $request->validate([

                'name' => 'required',
                'password' => 'min:6',
                'cpassword' => 'required_with:password|same:password|min:6',
                'email' => 'required|unique:agents,email,' . $request->post('agent_id'),

            ]);

            $agent_id = $request->agent_id;
            //dd($request->item);
            $update_arr['name'] = $request->name;
            $update_arr['email'] = $request->email;
            $update_arr['password'] = Hash::make($request->password);
            $update_arr['updated_at'] = date('Y-m-d H:i:s');
            
            if(Agent::where(['id' => $agent_id])->update($update_arr)){
                $request->session()->flash('alert-success', 'Agent successfully updated.');
                return redirect()->route('admin.agent.allAgents');
            }else{
                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
                return redirect()->back()->with($request->except(['_method', '_token']));
            }
        }
        return view('admin.agent.agent_edit', compact('agentDetails','request'));
    }

    // public function add($id=null, Request $request)
    // {
    // 	// dd($request);
    // 	$site_id = $id;

    //     $obj = new Blog;

    //     if($request->isMethod('POST')){

    //         $slug_url=$request->blog_slug;
    //         $data  = DB::table('blogs')
    //                 ->where(['site_id'=>$site_id])
    //                 ->where(['slug'=>$slug_url])
    //                 ->first();
    //         // dd($data);

    //         if($data){        
    //             $blog_id = $data->id;
    //             // dd($cat_ban_id);
    //         }else{
    //             $blog_id = 0;
    //         }  

    //         // if ($request->post('blog_image')) {
    //         //     $image_validation = "mimes:jpeg,jpg,png,webp";
    //         // } else {
    //         //     $image_validation = "required|mimes:jpeg,jpg,png,webp";
    //         // }

    //         $request->validate([
    //             'blog_image'=>'nullable|file|mimes:jpeg,jpg,png,webp',
    //             'blog_slug'=>'required',
    //             'blog_heading'=>'required',
    //             'blog_content'=>'required',
    //             'blog_date'=>'required',
    //             'blogmeta_title'=>'required',
    //             'blogmeta_description'=>'required'
    //             ], [
    //                 'blog_image.mimes' => 'Please upload a valid image (jpeg, jpg, png, or webp).',
    //             ]);
    //         if($blog_id!=0){
    //             $request->session()->flash('alert-danger', 'Blog already exists.');
    //         }else{
    //             if ($request->hasFile('blog_image')) {
                
    //                 $image = $request->file('blog_image');
    //                 // $originalName = $image->getClientOriginalName();
    //                 $originalName = pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
    //                 $ext = $image->extension();
    //                 $image_name = $originalName.'_'.time() . '.' . $ext;
    //                 $request->blog_image->move(public_path('upload/blog_images'), $image_name);
    //             }else{
    //                 $image_name = null;
    //             }

    //             if($blog = $obj->create([
                    
    //                 'slug' => $request->blog_slug,
    //                 'site_id' => $request->site_id,
    //                 'blog_heading' => $request->blog_heading,
    //                 'blog_img' => $image_name,
    //                 'blog_content' => $request->blog_content, 
    //                 'post_date' => $request->blog_date,
    //                 'meta_title' => $request->blogmeta_title, 
    //                 'meta_description' => $request->blogmeta_description, 

    //             ]))
              
    //             {
    //                 $request->session()->flash('alert-success', 'Blog successfully added.');
    //                 return redirect()->route('admin.blog.list', ['id' => $site_id]);
    //             }else{
    //                 $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
    //                 return redirect()->back()->with($request->except(['_method', '_token']));
    //             }
    //         }

    //     }
    //     return view('admin.blog.add', ['site_id' => $site_id, 'request' => $request]);
    // }


	// public function edit($id = null, Request $request)
    // {
    // 	$blog_id = $id;
    //     $dataDetails  = Blog::where('id',$blog_id)->first();
    //     $siteId = $dataDetails->site_id;
        
    //     $obj = new Blog;
         
    //     if($request->isMethod('POST')){

    //         $request->validate([
    //             'blog_image'=>'nullable|file|mimes:jpeg,jpg,png,webp',
    //             'blog_slug'=>'required',
    //             'blog_date'=>'required',
    //             'blog_heading'=>'required',
    //             'blog_content'=>'required',
    //             'blogmeta_title'=>'required',
    //             'blogmeta_description'=>'required'
    //         ],[
    //             'blog_image.mimes' => 'Please upload a valid image (jpeg, jpg, png, or webp).',
    //         ]);

    //         $formid = $request->formid;
    //         $site_id = $request->site_id;

    //         if ($request->hasFile('blog_image')) {
            
    //             $image = $request->file('blog_image');
    //             $originalName = pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
    //             $ext = $image->extension();
    //             $image_name = $originalName.'_'.time() . '.' . $ext;
    //             $request->blog_image->move(public_path('upload/blog_images'), $image_name);

    //             if ($dataDetails->blog_img && file_exists(public_path('upload/blog_images/' . $dataDetails->blog_img))) {
    //                 unlink(public_path('upload/blog_images/' . $dataDetails->blog_img));
    //             }

    //         }else{
    //             $image_name = $request->old_blog_image;
    //         }

    //         $update_arr['site_id'] = $request->site_id;
    //         $update_arr['slug'] = $request->blog_slug;
    //         $update_arr['blog_heading'] = $request->blog_heading;
    //         $update_arr['blog_content'] = $request->blog_content;
    //         $update_arr['post_date'] = $request->blog_date;
    //         $update_arr['blog_img'] = $image_name;
    //         $update_arr['meta_title'] = $request->blogmeta_title;
    //         $update_arr['meta_description'] = $request->blogmeta_description;
    //         $update_arr['updated_at'] = date('Y-m-d H:i:s');
            
    //         if(Blog::where(['id' => $request->formid])->update($update_arr)){
    //             $request->session()->flash('alert-success', 'Blog successfully updated.');
    //             return redirect()->route('admin.blog.list', ['id' => $site_id]);
    //         }else{
    //             $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
    //             return redirect()->back()->with($request->except(['_method', '_token']));
    //         }
    //     }
    //     return view('admin.blog.edit', ['dataDetails' => $dataDetails, 'request' => $request, 'siteId' => $siteId]);
    // }

    // public function delete($id = null, Request $request){
    //     // dd($id);
    //     $blog_id = decrypt($id);

    //     $Blog = Blog::find($blog_id);
    //     $site_id=$Blog->site_id;
        
    //     if (!$Blog) {
    //         $request->session()->flash('alert-danger', 'No data found for this id!');
    //     }

    //     if ($Blog->blog_img && file_exists(public_path('upload/blog_images/' . $Blog->blog_img))) {
    //         unlink(public_path('upload/blog_images/' . $Blog->blog_img));
    //     }

    //     $Blog->delete();

    //     $request->session()->flash('alert-danger', 'Blog successfully delete.');
    //     return redirect()->route('admin.blog.list', ['id' => $site_id]);
    // }

    // public function status(Request $request)
    // {
    //     if($request->id == null || $request->status == null){
    //         // return redirect()->route('admin.category.list');
    //     }
    //     $id = base64_decode($request->id);
    //     switch($request->status){
    //         case 'N':
    //             $block = 'Y';
    //             $blockText = 'Block';
    //             break;
    //         case 'Y':
    //             $block = 'N';
    //             $blockText = 'Unblock';
    //             break;
    //         default:
    //             $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
    //             return redirect()->back();
    //     }

    //     if(Blog::where(['id' => $id])->update(['is_block' => $block])){
    //         $prompt = array('status' => 1, 'id' => $id, 'event' => $blockText);
    //         echo json_encode($prompt);
    //     }else{
    //         $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
    //         return redirect()->back();
    //     }
    // }

}