<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Hash;
use Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use App\Models\User;
use App\Models\UserData;
use App\Models\UserDocuments;
use App\Models\UserCorporate;
use App\Models\WalletHistoryUsers;
use Illuminate\Support\Facades\Validator;

class UserController extends BaseController
{
    
    /**
     * Customer List View
     */
    public function customers(){
        $users = User::with('UserData')->where('user_type', '=', 'Subscribers')->orWhere('user_type', '=', 'Corporate')->get();

        return view('admin.users.customers', compact('users'));
    }
    /**
     * Angels(Driver) List View
     */
    public function angels(){

        $users = User::with('UserData')->where('user_type', '=', 'Driver')->get();

        return view('admin.users.customers', compact('users'));
    }
    /**
     * Staff (Admin,Manager) List View
     */
    public function staff(){
        $users = User::with('UserData')->where('user_type', '=', 'Staff')->get();

        return view('admin.users.customers', compact('users'));
    }
    /**
     * Render Customer add form in GET Method
     */
    public function add_customer(){

        return view('admin.users.add_customer');
    }
    /**
     * Render Angels add form in GET Method
     */
    public function add_angel(){

        return view('admin.users.add_customer');
    }
    /**
     *  Validate New user form request in User Model
     *  return json responsr with HTTP status
     */
    public function new_user_form_validate(Request $request){
        $user = new User();
        return $user->signupValidate($request);
    }
    /**
     *  Store New Subscriber or Corporate user to table from Admin portal
     *  User, UserData, UserDocuments, Update Wallet History if wallet amount added
     */
    public function store_customer(Request $request){
        $postData = $request->all();
        $user = [
            'name' => $postData['first_name'] .' ' . $postData['last_name'],
            'email' => $postData['email'],
            'phone_number' => $postData['phone_number'],
            'user_type' => $postData['user_type'],
            'password' => '123456'
        ];
        
        $user = User::create($user);
        
        $userData = [
            'user_id' => $user['id'],
            'first_name' => $postData['first_name'],
            'last_name' => $postData['last_name'],
            'phone_number' => $postData['phone_number'],
            'wallet_amount' => ( $postData['wallet_amount'] > 0) ? $postData['wallet_amount'] : 0
        ];
        $userData = UserData::create($userData);
        
        foreach($request['user-docs'] as $userDoc){
            if($userDoc['doc']){
                (new UserDocuments())->uploadFile($userDoc, $user);
            }
        }
        if($postData['user_type']  == 'Corporate'){
            $userCorporate = [
                'user_id' => $user['id'],
                'employee_id' => 'EMP'.$user['id'].$postData['business_name'],
                'business_model' => $postData['business_name'],
                'business_for' => $postData['business_for'],
            ];
            
            $userCorporate = UserCorporate::create($userCorporate);
        }
        if($postData['wallet_amount'] > 0){
            $walletHistory = [
                'user_id' => $user['id'],
                'purpose' => $postData['reason'],
                'amount' => $postData['wallet_amount'],
                'transaction_type' => 'Credited',
            ];
            
            $walletHistory = WalletHistoryUsers::create($walletHistory);
        }
        if($postData['user_type'] == 'Driver'){
            return Redirect::to(route('admin.angels'));
        }
        return Redirect::to(route('admin.customers'));
        
    }
    
    /**
     * Render Customer Edit form in GET Method
     */
    public function edit_customer($id){
        $user = User::with(['UserData'])->where('id', '=', $id)->first();
        //$userDocuments = UserDocuments::where('user_id', $id)->get()->keyBy('doc_page')->toArray();
        $userDocuments = UserDocuments::where('user_id', $id)->get()->toArray();

        return view('admin.users.edit_customer', compact('user', 'userDocuments'));
    }
    /**
     *  Update Subscriber or Corporate user to table from Admin portal
     *  User, UserData, UserDocuments, Update Wallet History if wallet amount added
     */
    public function update_customer(Request $request, $id){
        $request->validate([
            'email' => 'required|email',
            'first_name' => 'required',
            'last_name' => 'required',
            'phone_number' => 'required',
            'user_type' => 'required',
        ]);
        $postData = $request->all();
        $user = User::findOrFail($id);
        $userUpdate = [
            'name' => $postData['first_name'] .' ' . $postData['last_name'],
            'email' => $postData['email'],
            'phone_number' => $postData['phone_number'],
            'user_type' => $postData['user_type'],
            'password' => '123456'
        ];
        $userDataUpdate = [
            'user_id' => $user['id'],
            'first_name' => $postData['first_name'],
            'last_name' => $postData['last_name'],
            'phone_number' => $postData['phone_number'],
            'wallet_amount' => ( $postData['wallet_amount'] > 0) ? $postData['wallet_amount'] : 0
        ];
        $userData = UserData::where('user_id', $user['id'])->first();
        if($postData['wallet_amount'] != $userData['wallet_amount']){
            $amount  = $userData['wallet_amount'] > $postData['wallet_amount'] ? $userData['wallet_amount'] - $postData['wallet_amount'] : $postData['wallet_amount'] - $userData['wallet_amount'];
            $transaction_type  = $userData['wallet_amount'] > $postData['wallet_amount'] ? 'Debited' : 'Credited';
            $walletHistory = [
                'user_id' => $user['id'],
                'purpose' => $postData['reason'],
                'amount' => $amount,
                'transaction_type' => $transaction_type,
            ];
            
            $walletHistory = WalletHistoryUsers::create($walletHistory);
        }
        $user->update($userUpdate);
        $userData->update($userDataUpdate);
        //$userDocs = UserDocuments::where('user_id', $id)->get()->toArray();
        // foreach($userDocs as $userDoc){
        //     $this->destroyUserDoc($userDoc['id']);
        // }
        
        foreach($request['user-docs'] as $userDoc){
            if($userDoc['doc']){
                (new UserDocuments())->uploadFile($userDoc, $user);
            }elseif($userDoc['doc_id']){
                if($userDocument = UserDocuments::findOrFail($userDoc['doc_id'])){
                    $userDocUpdate = [
                        'user_id' => $user['id'],
                        'doc_name' => $userDoc['doc_name'],
                        'doc_number' => $userDoc['doc_number'],
                        'doc_page' =>  $userDoc['doc_page'],
                        'description' => isset($userDoc['description']) ? $userDoc['description'] : '',
                        'verify' => isset($userDoc['verify']) ? $userDoc['verify'] : 0
                    ];
                    $userDocument->update($userDocUpdate);
                }
            }
        }
        
        if($postData['user_type'] == 'Driver'){
            return Redirect::to(route('admin.angels'));
        }
        return Redirect::to(route('admin.customers'));
        
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $user = User::with(['UserData'])->where('id', '=', $id)->first();
        $userDocuments = UserDocuments::where('user_id', $id)->get()->toArray();
        $walletHistories = WalletHistoryUsers::where('user_id', $id)->get();
        $userCorporate = UserCorporate::where('user_id', $id)->get()->toArray();


        return view('admin.users.show', compact('user', 'userDocuments', 'walletHistories', 'userCorporate'));
    }
    public function admin_login(Request $request){
        if (Auth::check()) {
            return Redirect::to('admin/dashboard');
        }else{
            $request->validate([
                'email' => 'required',
                'password' => 'required',
            ]);
    
            $credentials = $request->only('email', 'password');
            //print_r($credentials ); exit;
            if (Auth::attempt($credentials)) {
                return Redirect::to('admin/dashboard');
            }else{
                echo 'test'; exit;
            }
        }
  
        
    }
    public function signup(){
        
    }
    public function destroy($id)
    {
        User::destroy($id);
        $userDocs = UserDocuments::where('user_id', $id)->get()->toArray();
        foreach($userDocs as $userDoc){
            $this->destroyUserDoc($userDoc['id']);
        } 
        $userData = UserData::where('user_id', $id)->first();
        UserData::destroy($userData['id']);
        $walletHistory = WalletHistoryUsers::where('user_id', $id)->get()->toArray();
        foreach($walletHistory as $history){
            WalletHistoryUsers::destroy($history['id']);
        } 
        return redirect('admin/customers')->with('flash_message', 'users  deleted!');
    }
    public function destroyUserDoc($id){
        if(UserDocuments::destroy($id)){
            return true;
        }
    }
}
