<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; 
use Illuminate\Support\Facades\Auth;
use App\Invoice;
use App\User;
use App\Product;
use App\Numbertowordconvertsconver;
use Session;

class TransactionController extends Controller
{
    public function saveAll(Request $request)
    {
        // Start DB transaction
        DB::beginTransaction();
        
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $u_name = $user_data[0]->user_name;
        $u_id = $user_data[0]->user_id;
             $username = $user_data[0]->user_name;
             $udepo = $user_data[0]->user_depoid;
             $error="Invoice Created";

        try {
            /** ------------------------
             * 1. Save Invoice
             * ------------------------*/
            $invoiceData = $request->input('invoice'); // array of invoice fields
            $invoiceItems = $request->input('invoice_items'); // array of items
            
           
                $unc = new Invoice();
                $invuniq_id = $unc->unique_code(8);
                
                $outs = new Invoice();
                $outt = $outs->outstand($invoiceData['po_sup_id']);
                $out = $outt+$invoiceData['actual_final'];
                
                $cur_dt =  date('d-m-y h:i:s');
                
                $temp_item =   app('db')->select("SELECT * from `temp_qto_items` where `po_user` ='$u_id'");
                $count = count($temp_item);
            
             if($count>0){
                 $invoiceId = DB::table('mes_qto')->insertGetId(array_merge(
                $invoiceData,
                [
                    
                    'po_cdate' => date('Y-m-d'),
                    'uniq_id' => $invuniq_id,
                    'depo' => $udepo,
                    'po_sup_outstand' => $out,
                    'po_tot_items' => $count,
                    'po_cuser' => $u_id,
                    'po_ref_id' => $u_id,
                    'po_auth' => 1,
                    'po_time' => $cur_dt,
                    'po_status' => 1,
                ]
            ));
            
            
       

            // Insert Invoice Items
            foreach ($temp_item as $item) {
                DB::table('qto_items')->insert([
                    'po_itm_po_id' => $invoiceId,
                    'po_itm_item_id' => $item->po_itm_item_id,
                    'depo_id' => $item->depo_id ?? null,
                    'po_itm_batch' => $item->po_itm_batch ?? null,
                    'po_itm_partno' => $item->po_itm_partno ?? 0,
                    'service_des' => $item->service_des ?? null,
                    'po_itm_qty' => $item->po_itm_qty ?? 0,
                    'free_item' => $item->free_item ?? 0,
                    'po_itm_unit' => $item->po_itm_unit ?? 1,
                    'po_itm_dis' => $item->po_itm_dis ?? 0,
                    'po_itm_unitprice' => $item->po_itm_unitprice ?? 0,
                    'po_itm_currancy' => $item->po_itm_currancy ?? '1',
                    'po_itm_description' => $item->po_itm_description ?? null,
                    'po_aprvl' => 0,
                    'po_user' => $u_id ?? null
                ]);
                
                $inserttemp_id = $item->po_itm_id;
                $updt_inv = app('db')->update("UPDATE `mes_inventry` SET `invt_type_id`='$invoiceId',`invt_type`='INV' WHERE `invt_type_id` = '$inserttemp_id' and `invt_type` = 'temp'");
                            
                DB::delete('DELETE FROM temp_qto_items WHERE po_itm_id = ?', [$item->po_itm_id]);
                
            }
            
            }else{
                $error="No Invoice Item";
            }

           


             /** ------------------------
             * 2. Save Return
             * ------------------------*/
            if ($request->has('return')) {
                
                $returnData = $request->input('return'); // return main
                $returnItems = $request->input('return_items'); // return items
                    
                if(count($returnItems)>0){
                    $returnmId = DB::table('inv_return_main')->insertGetId(
                    [   'retm_invnum'=> 00, 
                        'retm_depo'=> $udepo, 
                        'retm_totqty'=> $returnData['ret_totqty'], 
                        'retm_amount'=> $returnData['ret_amount'], 
                        'retm_cuser'=> $u_id, 
                        'retm_cdate'=> date('Y-m-d'), 
                        'retm_stetus'=> 1,
                        'retm_proceed'=> 0,
                    ]
                );    
                    
                $returnId = DB::table('inv_return')->insertGetId(array_merge(
                    $returnData,
                    [   'ret_invnum'=>$invoiceId,
                        'ret_depo'=>$udepo, 
                        'ret_cuser'=>$u_id, 
                        'ret_cdate'=>date('Y-m-d'), 
                        'ret_stetus'=>1, 
                        'ret_proceed'=>0, 
                        'ret_main_id'=>$returnmId,
                    ]
                ));
                
                
                 
            
                // Loop through items by index
                for ($i = 0; $i < count($returnItems[0]); $i++) {
                    $name = $returnItems[0][$i];
                    $qty = $returnItems[1][$i];
                    $amount = $returnItems[2][$i];
                    $code = $returnItems[3][$i];
                    
                     if($udepo!=0){
                                $prc = app('db')->select("SELECT `retail_price`,`batch_id` FROM `batch_depo` WHERE `product` = '$code' AND `depo` = '$udepo'");
                                 $prd_btch = $prc[0]->batch_id;
                            }else{
                                $prc = app('db')->select("SELECT `retail_price`,`batch_id` FROM `batch` WHERE `product` = '$code'");
                                 $prd_btch = $prc[0]->batch_id;
                            }
            
                   DB::table('return_items')->insert([
                        'ret_itm_item_id'=>$code,
                        'ret_item_batch'=>$prd_btch, 
                        'depo_id'=>$udepo,
                        'ret_note_id'=>$returnId, 
                        'ret_inv_id'=>$invoiceId, 
                        'ret_itm_qty'=>$qty, 
                        'free_item'=>0, 
                        'ret_itm_unit'=>0, 
                        'ret_itm_unitprice'=>$amount, 
                        'ret_itm_currancy'=>0,
                        'ret_aprvl'=>0,
                        'ret_user'=>$u_id,
                        'ret_to_stock'=>0,
                        'ret_to_stock_auth'=>0
                    ]);
                    
                    $todaay = date('Y-m-d');
                    $chkk = app('db')->insert("INSERT INTO `mes_inventry` (`invt_type`, `invt_type_id`, `invt_itemid`, `invt_qty`, `cal`, `invt_cuser`, `invt_cdate`)
                    VALUES ('INVRTN','$returnId','$code','$qty','plus','$u_id','$todaay') ");
                }
    
    
                }
                
    
               
            }

            /** ------------------------
             * 3. Save Payment
             * ------------------------*/
            if ($request->has('payment')) {
                $paymentData = $request->input('payment'); // main payment
                $paymentDetails = $request->input('payment_details'); // payment items
                $unc = new Invoice();
                    $uniq_id = $unc->unique_code(10);

            if(count($paymentDetails)>0){
                 for ($i = 0; $i < count($paymentDetails[0]); $i++) {
                    $amnt = $paymentDetails[0][$i];
                    $type = $paymentDetails[1][$i];
                    $bank = $paymentDetails[2][$i]?? 0;
                    $branch = $paymentDetails[3][$i]?? 0;
                    $chq = $paymentDetails[4][$i];
                    $chdt = $paymentDetails[5][$i];
                    
                    if($type=="Cash"){
                      $paytid =0;
                    }if($type=="Cheque"){
                      $paytid =1;
                    }if($type=="Bank Deposit"){
                      $paytid =2;
                    }
                   
                    $paymentId = DB::table('mes_payment_main')->insertGetId([
                   
                        'pay_cust_id'=>$invoiceData['po_sup_id'], 
                        'pay_ref_id'=>$u_id, 
                        'pay_inv_id'=>0, 
                        'pay_uniqid'=>$uniq_id, 
                        'pay_type'=>$paytid, 
                        'pay_chkid'=>$chq, 
                        'pay_chkbnk'=>$bank, 
                        'pay_bbranch'=>$branch, 
                        'pay_chkdate'=>$chdt, 
                        'pay_amount'=>$amnt, 
                        'pay_date'=>date('Y-m-d'), 
                        'pay_user'=>$u_id, 
                        'pay_stetus'=>1, 
                    
                ]);
                    
            
                   DB::table('mes_payment')->insert([
                       'pay_uniqid'=>$uniq_id, 
                       'pay_type'=>$paytid, 
                       'pay_chkid'=>$chq, 
                       'pay_chkbnk'=>$bank, 
                       'pay_bbranch'=>$branch, 
                       'pay_chkdate'=>$chdt, 
                       'pay_amount'=>$amnt, 
                       'pay_invid'=>$invoiceId, 
                       'pay_date'=>date('Y-m-d'), 
                       'pay_user'=>$u_id, 
                       'pay_stetus'=>1, 
                       'pay_main_id'=>$paymentId
                        
                    ]);
                }
            }
                
                
                
            }
            

            DB::commit();

            return response()->json(['status' => 'Invoice Created', 'invoice_id' => $invoiceId,'uniq_id' => $invuniq_id]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                    'status' => 'Recreate',
                    'message' => $e->getMessage(),
                    'line' => $e->getLine(),
                    'file' => $e->getFile(),
                    'trace' => $e->getTraceAsString(), // optional (very detailed)
                ], 500);
        }
    }
}
