<?php

namespace App\Http\Controllers\backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\Productcategory;
use App\Models\Product;
use App\Models\Purchase;
use App\Models\Supplier;
use App\Models\Customer;
use App\Models\CustomerAccount;
use App\Models\SupplierAccount;
use App\Models\Sale;
use App\Models\SaleDetail;
use App\Models\PurchaseDetail;
use App\Models\SaleReturnDetail;
use App\Models\PurchaseReturnDetail;
use App\Models\Expensetype;
use App\Models\Expense;
use App\Models\About;
use App\Models\Loan;
use App\Models\Transaction;
use App\Models\CustomerRecord;
use App\Models\SupplierRecord;
use App\Models\Worker;
use App\Models\Production;
use App\Models\WorkerAccount;
use App\Models\WorkerRecord;
use App\Models\CashClosing;

class AccountController extends Controller
{
    public function spi(Request $request){
        /*---------delete 0 amount---------------*/
        SupplierAccount::where('amount',0)->delete();

        $show = $request->show;
        if($show != ''){
            $payments = SupplierAccount::latest()->paginate($show);

        }else{
            $payments = SupplierAccount::latest()->paginate(setting()->ddspinp);
        }
        /*--------------search which supplier who have due amount------------------------*/
       // $suppliers = Supplier::orderBy('supplier_name','ASC')->get();
       $suppliers = DB::select("SELECT s.id, s.name as supplier_name, sum(p.due_amount) as total_due FROM suppliers s, purchases p WHERE s.id = p.supplier_id AND p.due_amount > 0 GROUP by p.supplier_id ORDER BY p.due_amount DESC ");
        return view('backend.supplier_payment.index',compact('payments','suppliers'));
    }
    public function spsearch(Request $request){
       // return $request->all();
        $this->validate($request, [
            'supplier_name' => 'required',
        ]);
        $pd = Supplier::where('id',$request->supplier_name)->first();

        if($pd != NULL){

            $purchases = Purchase::where('supplier_id',$pd->id)->where('due_amount','!=',0)->get();
            //return $purchases;
            $suppliers = DB::select("SELECT s.id, s.name as supplier_name, sum(p.due_amount) as total_due FROM suppliers s, purchases p WHERE s.id = p.supplier_id AND p.due_amount > 0 GROUP by p.supplier_id ORDER BY p.due_amount DESC ");
            return view('backend.supplier_payment.create',compact('pd','purchases','suppliers'));
        }
        else{
            return back()->with('error','Woops! No Information Found, Please Check the Supplier Name Or Phone No ');
        }
    }
    public function spstore(Request $request){
        $closing =  DB::table('cash_closings')->where('closing_date', date('Y-m-d',strtotime($request->pay_date)))->exists();

        if($closing != true){
            //return $request->all();
            $supplier_id = $request->supplier_id;
            $amount = $request->amount;
            $pay_date = $request->pay_date;
        /*----------check current balance--------*/
           $closing_date =  date('Y-m-d',strtotime($request->pay_date));

           $balance = $this->cashCheck($closing_date);

        if($balance > $request->payment){
            $pays  = Purchase::where(['supplier_id'=>$supplier_id])->where('due_amount', '>',0)->get();
                foreach($pays  as $pay){
                    if($amount >= $pay->due_amount && $amount >= 0){
                        $x = $amount - $pay->due_amount;
                        $need_amount = $amount - $x;
                        $pay->paid_amount = $pay->paid_amount + $need_amount;
                        $pay->due_amount = $pay->due_amount - $need_amount;
                        if($pay->paid_amount >= $pay->net_purchase_price){
                            $pay->payment_status = 'Paid';
                        }else{
                            $pay->payment_status = 'Due';
                        }
                        $pay->save();
                        $amount = $x;

                        //for customer account
                        $c_ac = new SupplierAccount();
                        $dt = Carbon::parse($pay_date);
                        $c_ac->payment_date = $dt->toDateTimeString();
                        $c_ac->supplier_id = $request->supplier_id;
                        $c_ac->purchase_id =  $pay->id;
                        $c_ac->amount =  $need_amount;
                        $c_ac->note = $request->note;
                        $c_ac->save();
                        //DB::commit();
                    }else{
                        if($amount > 0){
                            $pay->paid_amount = $pay->paid_amount + $amount;
                            $pay->due_amount = $pay->due_amount - $amount;
                            $pay->save();

                            //for customer account
                            $c_ac = new SupplierAccount();
                            $dt = Carbon::parse($pay_date);
                            $c_ac->payment_date = $dt->toDateTimeString();
                            $c_ac->supplier_id = $request->supplier_id;
                            $c_ac->purchase_id =  $pay->id;
                            $c_ac->amount =  $amount;
                            $c_ac->note = $request->note;
                            $c_ac->save();
                        }
                        $amount = 0;
                    //	DB::commit();
                    }
                }
                $supplier = Supplier::with('purchase')->find($request->supplier_id);
                /*-------customer record section----------*/
                $record = new SupplierRecord();
                $record->supplier_id = $request->supplier_id;
                $record->transaction_date = date('Y-m-d',strtotime($pay_date));
                $record->user_id = Auth::id();
                $record->total_price = '0.00';
                $record->payment_amount = $request->amount;
                $record->due_amount = '0.00';
                $total_due = $supplier->purchase->sum('due_amount');
                $record->previous_due = $total_due + $request->amount;
                $record->total_due = $total_due;
                $record->note = $request->note;
                $record->message = "Dear ".$supplier->name.", Payment amount is ".$request->amount."/=  Previous Due ".$record->previous_due."/= Current Due ".$total_due."/= Thanks By ".about()->english_name.", ".about()->address;
                $record->created_by = Auth::id();
                $record->save();

                /*--------check the sms sending section--------*/
                if(isset($request->sms)){
                    //return $request->sms;
                    $to = $supplier->phone;//"017xxxxxxx,+88016xxxxxxx";
                    $token = "daf0cc0b638862523830815f351a8063";
                    $message = 'Previous due:'.$record->previous_due.',payment:'.$record->payment_amount.',total due:'.$record->total_due.',Note:'.$record->note.',Date:'.date('d-m-Y',strtotime($record->transaction_date)).'.'.about()->english_name.','.about()->phone;
                    $url = "http://api.greenweb.com.bd/api.php?json";
                    $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);
                    //Result
                    //echo $smsresult;
                    //Error Display
                    //echo curl_error($ch);
                }
                return redirect()->route('account.spi')->with('success','Due payment successfull');
            }else{
                return redirect()->route('account.spi')->with('error','Woops! Current Balance is not enough Please check curent baance ');
            }
        }
        else{
            return redirect()->route('account.spi')->with('error','Woops! After Cash Closing Transaction will not be possible ');
        }
    }
    /*-------------*/
    public function wpi(Request $request){
        $show = $request->show;
        if($show != ''){
            $payments = WorkerAccount::latest()->paginate($show);

        }else{
            $payments = WorkerAccount::latest()->paginate(setting()->ddspinp);
        }
        /*--------------search which worker who have due amount------------------------*/
        $workers = Worker::where('current_balance','>',0)->orderBy('name','ASC')->get();
        return view('backend.worker_payment.index',compact('payments','workers'));
    }
    public function wpsearch(Request $request){
       // return $request->all();
        $this->validate($request, [
            'worker_name' => 'required',
        ]);
        $pd = Worker::where('id',$request->worker_name)->first();
        $workers = Worker::where('current_balance','>',0)->orderBy('name','ASC')->get();
        if($pd != NULL){
            $productions = Production::where('worker_id',$pd->id)->where('due_wage','>',0)->get();
            return view('backend.worker_payment.create',compact('pd','productions','workers'));
        }else{
            return back()->with('error','Woops! No Information Found, Please Check the Supplier Name Or Phone No ');
        }
    }
    public function wpstore(Request $request){
        $closing =  DB::table('cash_closings')->where('closing_date', date('Y-m-d',strtotime($request->pay_date)))->exists();

        if($closing != true){
            //return $request->all();
            $worker_id = $request->worker_id;
            $amount = $request->amount;
            $pay_date = $request->pay_date;
        /*----------check current balance--------*/
           $closing_date =  date('Y-m-d',strtotime($request->pay_date));

           $balance = $this->cashCheck($closing_date);

        if($balance > $request->payment){
            $pays  = Production::where(['worker_id'=>$worker_id])->where('due_wage', '>',0)->get();
                foreach($pays  as $pay){
                    if($amount >= $pay->due_amount && $amount >= 0){
                        $x = $amount - $pay->due_amount;
                        $need_amount = $amount - $x;
                        $pay->paid_amount = $pay->paid_amount + $need_amount;
                        $pay->due_amount = $pay->due_amount - $need_amount;
                        if($pay->paid_amount >= $pay->net_purchase_price){
                            $pay->payment_status = 'Paid';
                        }else{
                            $pay->payment_status = 'Due';
                        }
                        $pay->save();
                        $amount = $x;

                        //for customer account
                        $c_ac = new WorkerAccount();
                        $dt = Carbon::parse($pay_date);
                        $c_ac->payment_date = $dt->toDateTimeString();
                        $c_ac->worker_id = $request->worker_id;
                        $c_ac->production_id =  $pay->id;
                        $c_ac->amount =  $need_amount;
                        $c_ac->note = $request->note;
                        $c_ac->save();
                        //DB::commit();
                    }else{
                        if($amount > 0){
                            $pay->paid_amount = $pay->paid_amount + $amount;
                            $pay->due_amount = $pay->due_amount - $amount;
                            $pay->save();

                            //for customer account
                            $c_ac = new WorkerAccount();
                            $dt = Carbon::parse($pay_date);
                            $c_ac->payment_date = $dt->toDateTimeString();
                            $c_ac->worker_id = $request->worker_id;
                            $c_ac->production_id =  $pay->id;
                            $c_ac->amount =  $amount;
                            $c_ac->note = $request->note;
                            $c_ac->save();
                        }
                        $amount = 0;
                    //	DB::commit();
                    }
                }
                $worker = Worker::with('production')->find($request->worker_id);
                /*-------customer record section----------*/
                $record = new WorkerRecord();
                $record->worker_id = $request->worker_id;
                $record->transaction_date = date('Y-m-d',strtotime($pay_date));
                $record->user_id = Auth::id();
                $record->total_price = '0.00';
                $record->payment_amount = $request->amount;
                $record->due_amount = '0.00';
                $total_due = $worker->production->sum('due_amount');
                $record->previous_due = $total_due + $request->amount;
                $record->total_due = $total_due;
                $record->note = $request->note;
                $record->message = "Dear ".$worker->name.", Payment amount is ".$request->amount."/=  Previous Due ".$record->previous_due."/= Current Due ".$total_due."/= Thanks By ".about()->english_name.", ".about()->address;
                $record->created_by = Auth::id();
                $record->save();

                /*---------------*/
                $worker->decrement('current_balance',$request->amount);

                /*--------check the sms sending section--------*/
                if(isset($request->sms)){
                    //return $request->sms;
                    $to = $worker->phone;//"017xxxxxxx,+88016xxxxxxx";
                    $token = "daf0cc0b638862523830815f351a8063";
                    $message = 'Previous due:'.$record->previous_due.',payment:'.$record->payment_amount.',total due:'.$record->total_due.',Note:'.$record->note.',Date:'.date('d-m-Y',strtotime($record->transaction_date)).'.'.about()->english_name.','.about()->phone;
                    $url = "http://api.greenweb.com.bd/api.php?json";
                    $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);
                    //Result
                    //echo $smsresult;
                    //Error Display
                    //echo curl_error($ch);
                }
                return redirect()->route('account.wpi')->with('success','Due payment successfull');
            }else{
                return redirect()->route('account.wpi')->with('error','Woops! Current Balance is not enough Please check curent baance ');
            }
        }
        else{
            return redirect()->route('account.wpi')->with('error','Woops! After Cash Closing Transaction will not be possible ');
        }
    }
    /**
     * => customer payment section
     */
    public function cpi(Request $request){
        /*---------delete 0 amount---------------*/
        CustomerAccount::where('amount',0)->delete();

        $show = $request->show;
        if($show != ''){
            $payments = CustomerAccount::latest()->paginate($show);

        }else{
            $payments = CustomerAccount::latest()->paginate(setting()->ddspinp);
        }
        /*--------------search which supplier who have due amount------------------------*/
       // $suppliers = Supplier::orderBy('supplier_name','ASC')->get();
       $customers = DB::select("SELECT c.id, c.name as customer_name, sum(s.due_amount) as total_due
                                    FROM customers c, sales s
                                    WHERE c.id = s.customer_id
                                    AND s.due_amount > 0
                                    GROUP by s.customer_id
                                    ORDER BY s.due_amount DESC ");
        return view('backend.customer_payment.index',compact('payments','customers'));
    }
    public function cpsearch(Request $request){
        $this->validate($request, [
            'customer_name' => 'required',
        ]);
        $cs = Customer::where('id',$request->customer_name)->first();
        $types = Expensetype::all();

        if($cs != NULL){

            $sales = Sale::where('customer_id',$cs->id)->where('due_amount', '>',0)->get();
            //return $purchases;
            $customers = DB::select("SELECT c.id, c.name as customer_name, sum(s.due_amount) as total_due FROM customers c, sales s WHERE c.id = s.customer_id AND s.due_amount > 0 GROUP by s.customer_id ORDER BY s.due_amount DESC ");
            return view('backend.customer_payment.create',compact('cs','sales','customers','types'));
        }
        else{
            return redirect()->back()->with('error','Woops! No Information Found, Please Check the Supplier Name Or Phone No ');
        }
    }
    public function cpstore(Request $request){
        $closing =  DB::table('cash_closings')->where('closing_date', date('Y-m-d',strtotime($request->pay_date)))->exists();

        if($closing != true){
            //return $request->all();
            $customer_id = $request->customer_id;
            $amount = $request->total_payment;
            $pay_date = $request->pay_date;
        /* try
            {
                DB::beginTransaction();*/
            $pays  = Sale::where(['customer_id'=>$customer_id])->where('due_amount', '>',0)->get();
                foreach($pays  as $pay){
                    if($amount >= $pay->due_amount && $amount >= 0){
                        $x = $amount - $pay->due_amount;
                        $need_amount = $amount - $x;
                        $pay->payment = $pay->payment + $need_amount;
                        $pay->due_amount = $pay->due_amount - $need_amount;
                        if($pay->payment >= $pay->net_purchase_price){
                            $pay->payment_status = 'Paid';
                        }else{
                            $pay->payment_status = 'Due';
                        }
                        $pay->save();
                        $amount = $x;

                        //for customer account
                        $c_ac = new CustomerAccount();
                        $dt = Carbon::parse($pay_date);
                        $c_ac->payment_date = $dt->toDateTimeString();
                        $c_ac->customer_id = $request->customer_id;
                        $c_ac->sale_id =  $pay->id;
                        $c_ac->amount =  $need_amount;
                        $c_ac->note = $request->note;
                        $c_ac->save();
                        //DB::commit();
                    }else{
                        if($amount > 0){
                            $pay->payment = $pay->payment + $amount;
                            $pay->due_amount = $pay->due_amount - $amount;
                            $pay->save();

                            //for customer account
                            $c_ac = new CustomerAccount();
                            $dt = Carbon::parse($pay_date);
                            $c_ac->payment_date = $dt->toDateTimeString();
                            $c_ac->customer_id = $request->customer_id;
                            $c_ac->sale_id =  $pay->id;
                            $c_ac->amount =  $amount;
                            $c_ac->note = $request->note;
                            $c_ac->save();
                        }
                        $amount = 0;
                    //	DB::commit();
                    }
                }
                /*-----------discount data insert into expense table-------------------*/
                if($request->discount != ''){
                    $ex = new Expense();
                    $ex->expensetype_id = $request->type_name;
                    $ex->user_id = Auth::id();
                    $dt = Carbon::parse($pay_date);
                    $ex->expense_date = $dt->toDateTimeString();
                    $ex->expense_amount = $request->discount;
                    $ex->description = $request->note;
                    $ex->save();
                }
                $cus = Customer::with('sales')->find($request->customer_id);
                /*-------customer record section----------*/
                $record = new CustomerRecord();
                $record->customer_id = $request->customer_id;
                $record->transaction_date = date('Y-m-d',strtotime($pay_date));
                $record->user_id = Auth::id();
                $record->total_price = '0.00';
                $record->payment_amount = $request->total_payment;
                $record->due_amount = '0.00';
                $total_due = $cus->sales->sum('due_amount');
                $record->previous_due = $total_due + $request->total_payment;
                $record->total_due = $total_due;
                $record->note = $request->note;
                $record->message = "Dear ".$cus->name.", Payment amount is ".$request->total_payment."/=  Previous Due ".$record->previous_due."/= Current Due ".$total_due."/= Thanks By ".about()->english_name.", ".about()->address;
                $record->created_by = Auth::id();
                $record->save();

                /*--------check the sms sending section--------*/
                if(isset($request->sms)){
                    //return $request->sms;
                    $to = $cus->phone;//"017xxxxxxx,+88016xxxxxxx";
                    $token = "daf0cc0b638862523830815f351a8063";
                    $message = 'Previous due:'.$record->previous_due.',payment:'.$record->payment_amount.',total due:'.$record->total_due.',Note:'.$record->note.',Date:'.date('d-m-Y',strtotime($record->transaction_date)).'.'.about()->english_name.','.about()->phone;
                    $url = "http://api.greenweb.com.bd/api.php?json";
                    $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);
                    //Result
                    //echo $smsresult;
                    //Error Display
                    //echo curl_error($ch);
                }
        /* }
            catch (\Exception $e)
            {
                DB::rollback();
                // something went wrong
                return redirect()->route('account.spi')->with('warning','Woops! Something went wrong');
            }*/
        return redirect()->route('account.cpi')->with('success','Due payment successfull');
        }
        else{
            return redirect()->back()->with('error','Woops! After cash closing all transaction has been stoped');
        }
    }
    /*-------------------*/
    
}
