<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use App\Models\Customer;
use App\Models\CustomerAccount;
use App\Models\CustomerRecord;
use App\Models\Sale;
use App\Models\SaleDetail;
use DB;

class CustomerController extends Controller
{    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
     public function index(Request $request){
        $this->checkpermission('customer-list');
        $show = $request->show;
        if($show != ''){
         $customers = Customer::latest()->paginate($show);
        }else{
            $customers = Customer::latest()->paginate(setting()->ddspinp);
        }
        
        return view('backend.customer.index',compact('customers'));
    }
    public function customer_search(Request $request){
        if($request->column == 'name' || $request->column == 'phone'){
            $customers = Customer::with('sales')->where($request->column,$request->search_value)->get();
            if($customers){
                return view('backend.customer.list', compact('customers'));
            }else{
                return redirect()->route('customer.index')->with('error','Woops!! no result found');
            }
        }
        if($request->column == ''){
            return redirect()->route('customer.index')->with('error','Woops!! no result found');
        }
    }
    public function customers(Request $request){
        // সার্চ ভ্যালু নেয়া
        $searchValue = $request->input('search');
    
        // সার্চ ভ্যালু একটি সংখ্যা কিনা তা যাচাই
        if (is_numeric($searchValue)) {
            // এটি একটি সংখ্যা, তাই আমরা ফোন কলামে অনুসন্ধান করব
            $customers = Customer::where('phone', $searchValue)->get();
        } else {
            // এটি একটি স্ট্রিং, তাই আমরা নাম কলামে অনুসন্ধান করব
            $customers = Customer::where('name', 'LIKE', "%{$searchValue}%")->get();
        }
        if($customers){
            return view('backend.customer.list', compact('customers'));
        }else{
            return redirect()->route('customer.index')->with('error','Woops!! no result found');
        }
    }
    /*-------customer record/history--------*/
    public function customer_record(Request $request){
        $this->checkpermission('customer-list');
        $from_date = date('Y-m-01');
        $to_date = date('Y-m-t');
        
        $records = CustomerRecord::whereDate('transaction_date', '>=',$from_date)->whereDate('transaction_date', '<=' , $to_date)->latest()->get();
        
        $customers = Customer::get(['id','name','phone']);
        return view('backend.customer.record',compact('records','customers','from_date','to_date'));
    }
    public function customer_records(Request $request){
        $this->checkpermission('customer-list');
        $from_date = date('Y-m-d',strtotime($request->from_date));
        $to_date = date('Y-m-d',strtotime($request->to_date));
        
        if($request->customer == 'All'){
            $records = CustomerRecord::whereDate('transaction_date', '>=',$from_date)->whereDate('transaction_date', '<=' , $to_date)->get();
        }else{
            $records = CustomerRecord::where('customer_id',$request->customer)->whereDate('transaction_date', '>=',$from_date)->whereDate('transaction_date', '<=' , $to_date)->get();
        }
        $customers = Customer::get(['id','name','phone']);
        return view('backend.customer.record',compact('records','customers','from_date','to_date'));
    }
    /*-----------sms send from customer record-------------*/
    public function record_send($id){
        $record = CustomerRecord::find($id);
        //return $record;
        $to = $record->customer->phone;//"017xxxxxxx,+88016xxxxxxx";
        $token = "7a787dd847f4650b1ba1adfb8771c733";
        $message = "Dear Customer Total price:".$record->total_price.',pay:'.$record->payment_amount.',due:'.$record->due_amount.',prev due:'.$record->previous_due.',total due:'.$record->total_due.',Date:'.date('d-m-Y',strtotime($record->transaction_date)).'.'.about()->english_name.','.about()->phone;
        $url = "http://api.greenweb.com.bd/api.php";
        $data= array(
            'to'=>"$to",
            'message'=>"$message",
            'token'=>"$token"
        ); // Add parameters in key value

        $ch = curl_init(); // Initialize cURL
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_ENCODING, '');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $smsresult = curl_exec($ch);
        DB::table('sms')->where('id',1)->decrement('sms_balance',2);
        return redirect()->route('customer.customer-record')->with('success',$smsresult);
    }
    public function record_print($id){
        $record = CustomerRecord::find($id);
        return view('backend.customer.record_print',compact('record'));
    }
    public function create(){
        return view('backend.customer.create');
    }
    /*-----customer list for ledger section-----*/
    public function customerList2(){
        $customer = Customer::orderBy('customer_name','ASC')->get();
    
        return response()->json($customer);
    }
    public function store(Request $request){
        $this->validate($request,[
            'customer_name'=>'required',
            'customer_phone'=>'required',
            //'customer_address'=>'required',
        ]);

        $customer = new Customer();
        $customer->name = $request->customer_name;
        $customer->phone = $request->customer_phone;
        $customer->email = $request->customer_email;
        $customer->address = $request->customer_address;
        $customer->save();

        if($request->due_amount != ''){
            /*---------to create unique invoice id----------*/
            $invoices = Sale::latest()->first();
            if($invoices != ''){
                $inv_no = date('dmy').$invoices->id + 1; 
            }
            else{
                $inv_no = date('dmy').'1';
            }

            $sale = new Sale();
            $sale->customer_id = $customer->id;
            $sale->user_id = Auth::id();
            $sale->sale_date = date('Y-m-d');
            $sale->invoice_no = $inv_no;
            $sale->total_price = $request->due_amount;
            $sale->discount = 0;
            $sale->grand_total_price = $request->due_amount;
            $sale->payment = 0;
            $sale->payment_status = 'Due';
            $sale->due_amount = $request->due_amount;
            $sale->save();
        }

        return redirect()->route('customer.list')->with('success','Customer Information Save Successfull');
    }
    public function status($id){
        $customer = Customer::find($id);
        if($customer->status != 'Inactive'){
            $customer->status = "Inactive";
        }else{
            $customer->status = "Active";
        }
        $customer->updated_by = Auth::id();
        $customer->save();
        return back()->with('success','Customer Status Change succesfull');
    }
    public function purchaseHistory(Request $request)
    {
        $id = $request->customer_id;
        $from_date = date_create($request->from_date);
        $to_date = date_create($request->to_date);

        $customer = Customer::find($id);
        //$sale = Sale::where('customer_id',$id)->whereDate('sale_date','>=', $from_date)->whereDate('sale_date','<=', $to_date)->get();
        $sale_detail = SaleDetail::where('customer_id',$id)->whereDate('sale_date','>=', $from_date)->whereDate('sale_date','<=', $to_date)->get();
        $account = CustomerAccount::where('customer_id', $id)->get();
        $due = Sale::where('customer_id',$id)->where('due_amount', '>',0)->get();
        return view('backend.customer.show',compact('sale_detail','customer','account','due'));
    }
    public function edit($id)
    {
        $customer = Customer::find($id);
        //$customers = Customer::latest()->paginate(10);
        return view('backend.customer.edit',compact('customer'));
    }
    public function update(Request $request, $id)
    {  
        $this->validate($request,[
        'customer_name'=>'required',
        'customer_phone'=>'required',
        'customer_address'=>'required',
    ]);
      
        $customer = Customer::find($id);
        $customer->name = $request->customer_name;
        $customer->phone = $request->customer_phone;
        $customer->email = $request->customer_email;
        $customer->address = $request->customer_address;
        $customer->save();

        return redirect()->route('customer.list')->with('success','Customer Information Update Successfull');
    }
    public function destroy($id)
    {
		$customer = Customer::find($id);
        if (Storage::disk('public')->exists('customer/'.$customer->image))
        {
            Storage::disk('public')->delete('customer/'.$customer->image);
        }
        $customer->delete();
        return redirect()->back()->with('success','Customer Information Successfully Deleted ');
    }
}
