<?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'));
    }

    /*-------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 = "daf0cc0b638862523830815f351a8063";
        $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);

        return redirect()->route('customer.customer-record')->with('success',$smsresult);
    }

    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);
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    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('id')->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();

            $record = new CustomerRecord();
            $record->customer_id = $sale->customer_id;
            $record->transaction_date = $sale->sale_date;
            $record->user_id = Auth::id();
            $record->total_price = $sale->due_amount;
            $record->payment_amount = 0;
            $record->due_amount = $sale->due_amount;
            $total_due = $sale->due_amount;
            $record->previous_due = $total_due - $request->due;
            $record->total_due = $total_due;
            $record->message = "Dear Supplier ".$customer->name.", your invoice total price is ".$sale->grand_total."/=, Payment ".$sale->payment."/= Due ".$sale->due."/= Previous Due ".$sale->due_amount."/= Current Due ".$total_due." Thanks By ".about()->english_name.", ".about()->address;
            $record->created_by = Auth::id();
            $record->save();
        }

        return redirect()->route('customer.list')->with('success','Customer Information Save Successfull');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $customer = Customer::find($id);
        $sale = Sale::where(['customer_id'=>$id])->get();
        $account = CustomerAccount::where('customer_id', $id)->get();
        $due = Sale::where('customer_id',$id)->where('due_amount', '>',0)->get();
        $sale_detail = SaleDetail::where('customer_id',$id)->get();
        return view('backend.customer.show',compact('customer','sale','account','due','sale_detail'));
    }
    /**
     * Date wise Customer Purchase Search
     *
     */
    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'));
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $customer = Customer::find($id);
        //$customers = Customer::latest()->paginate(10);
        return view('backend.customer.edit',compact('customer'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    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');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    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 ');
    }
}
