<?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\Worker;
use App\Models\WorkerAccount;
use App\Models\WorkerRecord;
use App\Models\Loan;
use App\Models\Transaction;
use App\Models\Product;
use App\Models\CashClosing;
use App\Models\Purchase;
use App\Models\PurchaseDetail;
use App\Models\PurchaseStock;
use App\Models\Production;
use App\Models\ProductionDetail;
use App\Models\ProductionStock;
use PDF;

class ProductionController extends Controller{
    public function index(Request $request){
        $this->checkpermission('production-list');
        $show = $request->show;
        if($show != ''){
            $productions = Production::orderBy('created_at', 'DSC')->paginate($show);
        }else{
            $productions = Production::orderBy('created_at', 'DSC')->paginate(setting()->ddspinp);
        }
        return view('backend.production.list', compact('productions'));
    }
    public function create(){
        $this->checkpermission('production-entry');

        $invoice = Production::where('production_date',date('Y-m-d'))->latest()->first();
        //return $invoice;
        if($invoice != ''){
            $dt = date('dmy');
            $len = strlen((string)$dt);
            $lv = substr($invoice->chalan_no, $len);
            $order_no = $dt.$lv + 1;
        }
        else{
            $order_no = date('dmy').'1';
        }
        $categories = Productcategory::orderBy('name','ASC')->where('status',1)->get();
        $workers = Worker::orderBy('name','ASC')->get();
        return view('backend.production.create',compact('categories','workers','order_no'));
    }
    public function productList(Request $request){
        $test = Product::where('productcategory_id', $request->category)->get();
        return response()->json($test);
    }
    public function productDetails(Request $request){
        $test = Product::with('category','unit')->find($request->id);
        return response()->json($test);
    }
    public function productDetails2(Request $request){
        $test = Product::with('category','unit')->where('code',$request->code)->first();
        return response()->json($test);
    }
    public function store(Request $request){
       // return $request->all();
        /*-----------check cash closing------------*/
        /*$closing =  DB::table('cash_closings')->where('closing_date', date('Y-m-d',strtotime($request->production_date)))->exists();
        if($closing != true){
            $balance = $this->cashCheck($request->production_date);
            if($balance >= $request->payment){*/
                $this->validate($request,[
                    // 'product_id'=>'required',
                    'worker_name'=>'required',
                    //'chalan_no'=>'required|unique:productions,chalan_no',
                    // 'total_production_price'=>'required',
                ]);

                $data = $request->except('_token','submit');

                $invoice = Production::where('production_date',date('Y-m-d',strtotime($request->production_date)))->latest()->first();
                if($invoice != ''){
                    $dt = date('dmy',strtotime($request->production_date));
                    $len = strlen((string)$dt);
                    $lv = substr($invoice->chalan_no, $len);
                    $inv_no = $dt.$lv + 1;
                }else{
                    $inv_no = date('dmy',strtotime($request->production_date)).'1';
                }

                $production = new Production();
                $production->worker_id = $request->worker_name;
                $production->chalan_no = $inv_no;
                $dt = Carbon::parse($request->production_date);
                $production->production_date =  $dt->toDateTimeString();
                $production->total_price = $request->total_price;
                $production->discount = $request->discount;
                $production->grand_total = $request->total_price;
                $production->total_wage = $request->grand_total;
                $production->paid_wage = $request->payment;
                $production->due_wage = $request->due;
                $production->note = $request->note;
                $production->created_by = Auth::id();
                $production->save();

                DB::table('workers')->where('id',$request->worker_name)->increment('current_balance', $request->grand_total);

                // worker account data store
                if($request->payment > 0){
                    $ca = new WorkerAccount();
                    $ca->payment_date = $dt->toDateTimeString();
                    $ca->worker_id =  $request->worker_name;
                    $ca->production_id = $production->id;
                    $ca->amount = $request->payment;
                    $ca->note = $request->note;
                    $ca->save();
                    DB::table('workers')->where('id',$request->worker_name)->decrement('current_balance', $request->payment);
                }
                // production details section
                for($i = 0; $i<count($data['product_id']); $i++ ){

                    $product = Product::find($data['product_id'][$i]);

                    $list = new ProductionDetail();
                    $list->production_id = $production->id;
                    $list->worker_id =  $request->worker_name;
                    $list->product_id =  $data['product_id'][$i];
                    $list->productcategory_id = $product->productcategory_id;
                    $list->unit_id = $product->unit_id;
                    $list->chalan_no = $production->chalan_no;
                    $list->rate = $data['supplier_price'][$i];
                    $list->quantity = $data['ordered_quantity'][$i];
                    $list->now_stock = $data['ordered_quantity'][$i];
                    $list->wage = $data['ordered_quantity'][$i] * $data['worker_wage'][$i];
                    $list->production_date =  $dt->toDateTimeString();
                    $list->created_by = Auth::id();
                    $list->save();

                    /*--------update stock information---------*/
                    $stock = ProductionStock::where('product_id',$data['product_id'][$i])->first();
                    if($stock != ''){
                        $stock->productcategory_id = $product->productcategory_id;
                        $stock->unit_id = $product->unit_id;
                        $stock->rate = $data['supplier_price'][$i];
                        $stock->now_stock = $stock->now_stock + $data['ordered_quantity'][$i];
                        $stock->save();
                    }else{
                        $nstock = new ProductionStock();
                        $nstock->product_id = $product->id;
                        $nstock->productcategory_id = $product->productcategory_id;
                        $nstock->unit_id = $product->unit_id;
                        $nstock->code_no = $product->code;
                        $nstock->product_name = $product->product_name;
                        $nstock->rate = $data['supplier_price'][$i];
                        $nstock->now_stock = $data['ordered_quantity'][$i];
                        $nstock->save();
                    }

                }
                //store worker record
                $worker = Worker::find($production->worker_id);
                $record = new WorkerRecord();
                $record->worker_id = $production->worker_id;
                $record->transaction_date = $production->production_date;
                $record->user_id = Auth::id();
                $record->total_price = $production->total_wage;
                $record->payment_amount = $production->paid_wage;
                $record->due_amount = $production->due_wage;
                $tdue = $worker->production->sum('due_wage');
                $total_due = $tdue != '' ? $tdue : 0;
                $record->previous_due = $total_due - $request->due;
                $record->total_due = $total_due;
                $record->note = $request->note;
                $record->message = "Dear Worker ".$worker->name.", your invoice total price is ".$production->total_wage."/=, Payment ".$production->paid_wage."/= Due ".$production->due_wage."/= 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 = $worker->phone;//"017xxxxxxx,+88016xxxxxxx";
                    $token = "7a787dd847f4650b1ba1adfb8771c733";
                    $message = "Dear ".$worker->name." total ".$production->total_wage.'/=,pay:'.$production->paid_wage.'/=,due:'.$production->due_wage.'/=,prev due:'.$record->previous_due.'/=,total due:'.$total_due.'.'.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('production.list')->with('success','Product Production Save Success');
           /* }else{
                return redirect()->route('production.create')->with('error','Woops! current balance is not enough for this transaction , please check cuurent balance from cash module.');
            }
        }else{
            return redirect()->route('production.create')->with('error','Woops! After cash closing all transaction has been stoped');
        }*/
    }
    public function show($id){
        $production = Production::find($id);
        return view('backend.production.show',compact('production'));
    }
    public function edit($id){
        //
    }
    public function update(Request $request, $id){
        $check = $this->checkpermission('production-update');
        if ($check) {
            $this->checkpermission('production-update');
        } else {
            $production = Production::find($id);
            $production->due_amount = 0;
            $production->paid_amount = $production->total_price;
            $production->update();

            // worker account data store
            $ca = new WorkerAccount();
            $ca->payment_date = date('Y-m-d');
            $ca->worker_id =  $production->worker_id;
            $ca->production_id = $production->id;
            $ca->amount = $production->total_price;
            $ca->note = $request->note;
            $ca->save();

            return redirect()->back()->with('success', 'Successfully Paid Due Balance');
        }
    }
    public function destroy($id){
        //
    }
}
