<?php
namespace App\Http\Controllers\Admin;
use App\Models\User;
use App\Models\SellerRequest;
use App\Models\BuyerRequest;
use App\Models\RequestImage;
use App\Models\MessageThread;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Config;
use App\Http\Controllers\Controller;
use Crypt;

class CustomersController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
         if($request->ajax()){
             return datatables()->of(User::select('id', 'name', 'email', 'status', 'phone_number', 'created_at')->where('user_type','3'))
           ->addColumn('actions', function($row){
                return '<span class="action-links"><a class="uk-text-primary uk-edit" href="'.url('admin/customers/'.$row->id.'/edit').'" uk-tooltip="Edit Customer"><i class="fa-solid fa-pen-to-square"></i></a>  <a data-id="'.$row->id.'" class="uk-text-danger delete-customer" href="javascript:void(0)" uk-tooltip="Delete Customer"><i class="fa-solid fa-trash"></i></a></span>';
            })
            ->addColumn('status', function($row){
                if($row->status == '1'){ 
                    $status = '<a href="javascript:void(0)" data-id="'.$row->id.'" class="uk-label uk-label-success active">Active</a>';
                }else{
                    $status = '<a href="javascript:void(0)" data-id="'.$row->id.'" class="uk-label uk-label-danger inactive">Inactive</a>';
                }
                return $status;
            })
            ->addColumn('login', function($row){
                if(auth()->user()->user_type == 1){
                    return '<a class="uk-label uk-label-success" href="'.url('customers/admin-login/'.Crypt::encrypt($row->id)).'">Login</a>';
                }else{
                    return  '';
                }
            })
            ->rawColumns(['actions','status', 'login'])->toJson();
        }
        else{
            $this->bladeContent['title']  = 'Customers'; 
            $this->bladeContent['active'] = 'customers';
            return view('admin.customers.index',$this->bladeContent);
        }
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        $this->bladeContent['title']  = 'Add Customer';
        $this->bladeContent['active'] = 'customers';
        return view ('admin.customers.create', $this->bladeContent);
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
     public function store(Request $request)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        
        $customer = new User();
        $customer->name         = request('name');
        $customer->user_name    = 'Anonymous_'.rand(100, 1000);
        $customer->email        = request('email');
        $customer->phone_number = request('phone_number');
        $customer->password     = (request('password') ? Hash::make(request('password')) : '');
        $customer->user_type    = 3;
        $customer->save();
        return redirect('admin/customers')->with('success','Customer successfully created.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Users  $users
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        // $request->session()->put('name',$request->input('name'));
        // return view('task')->with('name',$request->session()->get('name'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Users  $users
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        $customer                     = User::select('id', 'name', 'email', 'phone_number', 'profile_pic')->where('id', $id)->first();
        $this->bladeContent['title']  = 'Edit Customer';
        $this->bladeContent['active'] = 'customers';
        $this->bladeContent['data']   =  $customer;
        return view('admin.customers.edit', $this->bladeContent);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Users  $users
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$id)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        
        $customer = User::select('id', 'name', 'email', 'phone_number', 'profile_pic')->where('id', $id)->first();
        $customer->name         = request('name');
        $customer->email        = request('email');
        $customer->phone_number = request('phone_number');
        if($request->get('password')){
            $customer->password   = Hash::make(request('password'));  
        }
        
        if($request->hasFile('profile_pic')){
            $file    = $request->file('profile_pic');
            $newDir  = storage_path('profile_pictures/customer/'.$id);
            if (!file_exists($newDir)) {
                mkdir($newDir, 0777, true);
            }
            $fileName = time() . "_" . str_replace(" ","_",$file->getClientOriginalName());
            $file->move(storage_path('profile_pictures/customer/'.$id),$fileName);
            $customer->profile_pic = $fileName;
        }

        $customer->save();
        return redirect('admin/customers')->with('success','Customer successfully updated.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Users  $users
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        User::where('id',$id)->delete();
        
        SellerRequest::where('user_id', $id)->delete();
        BuyerRequest::where('user_id', $id)->delete();

        MessageThread::where('request_user_id', $id)->delete();
        MessageThread::where('realtor_user_id', $id)->delete();
        
        return response()->json([
            'success' => 1,
            'message' => 'Data successfully deleted.'
        ]);
    } 
    
    public function status(Request $request)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        $id = request('id');
        if($request->type == 'active'){
            $value = '1';
        }else{
            $value = '0';
        }
       User::where('id', $id)->update(array('status' => $value));
        return response()->json([
        'success' => 1,
        'message' => 'status changed.'
      ]);
    } 
    
    public function removeProfilePicture(Request $request){
     
        $userId         = request('id');
        
        $profilePic = User::where('id', $userId)->first();
        
        $fileName  = $profilePic->profile_pic;
        
        $path      = storage_path('profile_pictures/customer/'.$userId.'/'.$profilePic->profile_pic);
        
        if(file_exists($path)){
            unlink($path);
        }
        
        User::where('id', $userId)->update([
            'profile_pic' => '',
        ]);
        
        return response()->json([
            'success'  => 1,
            'message' => 'Profile picture successfully removed',
        ]);
        

    }
    
    
}