<?php
namespace App\Http\Controllers\Admin\accounting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\LogActivity;
use App\Models\{
    User,
    Role,
    School,
    Plan
};
use App\Models\accounting\{
    
    AccountCustomer
};

use App\Imports\CustomerImport;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Exports\CustomerExport;
use Maatwebsite\Excel\Facades\Excel;
use Validator;

class CustomerController extends Controller
{
    protected $admin_id;
    protected $school_id, $res,$allData,$data,$validate;
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            // fetch session and use it in entire class with constructor
            if (session()->get('loggedIn')['user_type'] == 'admin') {
                $this->admin_id = session()->get('loggedIn')['id'];
                $this->school_id = School::where("admin_id",$this->admin_id)->pluck("id")->first();
            } else {
                $this->admin_id = session()->get('loggedIn')['admin_id'];
                $this->school_id = School::where("admin_id",$this->admin_id)->pluck("id")->first();
            }
         
            return $next($request);
        });
    }

    public function exportCustomer()
    {        
        $filename = "customer.xlsx";
        return Excel::download(new CustomerExport($this->admin_id,"debitor"),$filename);
        
    }

    public function importCustomer(Request $request)
    {
        $file = $request->file('excel_file');        

        Excel::import(new CustomerImport($this->admin_id,"debitor"), $file);

        return response()->json(["message"=>"success"],200);
    }

    public function exportVendor()
    {        
        $filename = "vendor.xlsx";
        return Excel::download(new CustomerExport($this->admin_id,"creditor"),$filename);
        
    }

    public function importVendor(Request $request)
    {
        $file = $request->file('excel_file');        

        Excel::import(new CustomerImport($this->admin_id,"creditor"), $file);

        return response()->json(["message"=>"success"],200);
    }

     // Display all employees
     public function index()
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'vendor';
        $data['superadminSubMenu'] = 'vendor';

        $search = isset($_GET["search"]) ? $_GET["search"] : null;
        $name = isset($_GET["name"]) ? $_GET["name"] : null;
        $mobile = isset($_GET["mobile"]) ? $_GET["mobile"] : null;
        $email = isset($_GET["email"]) ? $_GET["email"] : null;
        
        $start_date = isset($_GET["start_date"]) ? $_GET["start_date"] : null;
        $end_date = isset($_GET["end_date"]) ? $_GET["end_date"] : null;
       
       
        $query = AccountCustomer::where('admin_id',$this->admin_id)->where("type","creditor");
        

        if($search)
        {
            $query->where('name', 'LIKE', '%' . $search . '%');
            
        }
        if($mobile)
        {
            $query->where('mobile', 'LIKE', '%' . $mobile . '%');
            
        }
        if($email)
        {
            $query->where('email', $email);
            
        }
        if($start_date && $end_date)
        {
            $query->whereDate("created_at",">=",$start_date);
            $query->whereDate("created_at","<=",$end_date);
        }
       
        $data['vendors'] = $query->orderBy('created_at','desc')->paginate(10);

        

        return view('accounting.vendor.list',$data);
     }
 
     // Show the form to create a new product
     public function vendorCreate()
     {
       

        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'vendor';
        $data['superadminSubMenu'] = 'vendor';
             

        return view('accounting.vendor.add',$data);
     }
 
     // Store a new product in the database
     public function vendorStore(Request $request)
     {
       
        $this->allData = $request->all();       
       
       // return $this->allData;
        $this->validate = Validator::make($request->all(),[
            "name"=>"required"
        ]);

        if($this->validate->fails())
        {
            return back()->withErrors($this->validate)->withInput();
        }

        if(isset($request->vendor_id) && !empty($request->vendor_id))
        {
            unset($this->allData["vendor_id"]);
            unset($this->allData["_token"]);
            if(isset($request->contact_name) && !empty($request->contact_name)) {
                $contacts = []; // Initialize as empty array
                
                foreach($request->contact_name as $index => $name) {
                    $contact = []; // Create new contact array for each iteration
                    
                    $contact['name'] = $name;
                    $contact['email'] = $request->contact_email[$index] ?? '';
                    $contact['phone'] = $request->contact_phone[$index] ?? '';
                    
                    $contacts[] = $contact; // Add the contact to contacts array
                }
                
                $this->allData['contact_details'] = json_encode($contacts);
            }

            unset($this->allData["contact_name"]);
            unset($this->allData["contact_email"]);
            unset($this->allData["contact_phone"]);
            
            $this->res = AccountCustomer::where("id",$request->vendor_id)->update($this->allData);

            if($this->res)
            {
                return back()->with("success","Vendor update successfully !");
            }
            return back()->with("error","failed !");
        }

        

        $this->allData["admin_id"] = $this->admin_id;
        $this->allData['type'] = "creditor";

        if(isset($request->contact_name) && !empty($request->contact_name)) {
            $contacts = []; // Initialize as empty array
            
            foreach($request->contact_name as $index => $name) {
                $contact = []; // Create new contact array for each iteration
                
                $contact['name'] = $name;
                $contact['email'] = $request->contact_email[$index] ?? '';
                $contact['phone'] = $request->contact_phone[$index] ?? '';
                
                $contacts[] = $contact; // Add the contact to contacts array
            }
            
            $this->allData['contact_details'] = json_encode($contacts);
        }

        unset($this->allData["contact_name"]);
        unset($this->allData["contact_email"]);
        unset($this->allData["contact_phone"]);

        $this->res = AccountCustomer::create($this->allData);

        if($this->res)
        {
            return back()->with("success","Vendor add successfully !");
        }
        return back()->with("success","failed !");
      
        
     }
 
     // Show the form to edit an existing product
     public function vendorEdit($id)
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'vendor';
        $data['superadminSubMenu'] = 'vendor';

        $data['vendor'] = AccountCustomer::where("id",$id)->first(); 
        

        return view('accounting.vendor.edit',$data); 
     }
 
     
     
     // Delete a product
     public function deleteVendor(Request $request)
     {
       // return $request->id;

         $this->res = AccountCustomer::where('id',$request->id)->delete();
         if($this->res)
         {
            $logMessage = $request->rolename . ' vendor delete successfully!';
			    LogActivity::addToLog($logMessage);
                
            
            return response()->json(["message"=>"success"],200);
         }
         
            return response()->json(["message"=>"failed"],424);
         
     }

     public function deleteMultipleVendor(Request $request)
     {
        //$request->ids;
        $this->res = AccountCustomer::whereIn('id', $request->ids)->delete();
        if($this->res)
        {
            return response()->json(["message"=>"success"],200);
        }
        return response()->json(["message"=>"failed"],424);

     }

     //customer code
     // Display all employees
     public function customerIndex()
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'customer';
        $data['superadminSubMenu'] = 'customer';

        $search = isset($_GET["search"]) ? $_GET["search"] : null;
        $name = isset($_GET["name"]) ? $_GET["name"] : null;
        $mobile = isset($_GET["mobile"]) ? $_GET["mobile"] : null;
        $email = isset($_GET["email"]) ? $_GET["email"] : null;
        
        $start_date = isset($_GET["start_date"]) ? $_GET["start_date"] : null;
        $end_date = isset($_GET["end_date"]) ? $_GET["end_date"] : null;
       
       
        $query = AccountCustomer::where('admin_id',$this->admin_id)->where("type","debitor");
        

        if($search)
        {
            $query->where('name', 'LIKE', '%' . $search . '%');
            
        }
        if($mobile)
        {
            $query->where('mobile', 'LIKE', '%' . $mobile . '%');
            
        }
        if($email)
        {
            $query->where('email', $email);
            
        }
        if($start_date && $end_date)
        {
            $query->whereDate("created_at",">=",$start_date);
            $query->whereDate("created_at","<=",$end_date);
        }
       
        $data['vendors'] = $query->orderBy('created_at','desc')->paginate(10);

        

        return view('accounting.customer.list',$data);
     }
 
     // Show the form to create a new product
     public function customerCreate()
     {
       

        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'customer';
        $data['superadminSubMenu'] = 'customer';
             

        return view('accounting.customer.add',$data);
     }
 
     // Store a new product in the database
     public function customerStore(Request $request)
     {
       
        $this->allData = $request->all();       
       
       // return $this->allData;
        $this->validate = Validator::make($request->all(),[
            "name"=>"required"
        ]);

        if($this->validate->fails())
        {
            return back()->withErrors($this->validate)->withInput();
        }

        if(isset($request->vendor_id) && !empty($request->vendor_id))
        {
            unset($this->allData["vendor_id"]);
            unset($this->allData["_token"]);
            if(isset($request->contact_name) && !empty($request->contact_name)) {
                $contacts = []; // Initialize as empty array
                
                foreach($request->contact_name as $index => $name) {
                    $contact = []; // Create new contact array for each iteration
                    
                    $contact['name'] = $name;
                    $contact['email'] = $request->contact_email[$index] ?? '';
                    $contact['phone'] = $request->contact_phone[$index] ?? '';
                    
                    $contacts[] = $contact; // Add the contact to contacts array
                }
                
                $this->allData['contact_details'] = json_encode($contacts);
            }

            unset($this->allData["contact_name"]);
            unset($this->allData["contact_email"]);
            unset($this->allData["contact_phone"]);
            
            $this->res = AccountCustomer::where("id",$request->vendor_id)->update($this->allData);

            if($this->res)
            {
                return back()->with("success","Customer update successfully !");
            }
            return back()->with("error","failed !");
        }

        

        $this->allData["admin_id"] = $this->admin_id;
        $this->allData['type'] = "debitor";

        if(isset($request->contact_name) && !empty($request->contact_name)) {
            $contacts = []; // Initialize as empty array
            
            foreach($request->contact_name as $index => $name) {
                $contact = []; // Create new contact array for each iteration
                
                $contact['name'] = $name;
                $contact['email'] = $request->contact_email[$index] ?? '';
                $contact['phone'] = $request->contact_phone[$index] ?? '';
                
                $contacts[] = $contact; // Add the contact to contacts array
            }
            
            $this->allData['contact_details'] = json_encode($contacts);
        }

        unset($this->allData["contact_name"]);
        unset($this->allData["contact_email"]);
        unset($this->allData["contact_phone"]);


        $this->res = AccountCustomer::create($this->allData);

        if($this->res)
        {
            return back()->with("success","Customer add successfully !");
        }
        return back()->with("success","failed !");
      
        
     }
 
     // Show the form to edit an existing product
     public function customerEdit($id)
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'customer';
        $data['superadminSubMenu'] = 'customer';

        $data['vendor'] = AccountCustomer::where("id",$id)->first(); 
        

        return view('accounting.customer.edit',$data); 
     }

}
