<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tax;
use App\User;
use Illuminate\Support\Facades\Validator;
use Auth;
use App\Models\Transaction;
use App\Models\SellLines;
use App\Models\TaxDetails;
use DB;
use Carbon\Carbon;
class TaxGenerateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //  $customer_data=User::select('users.id','users.company_name')->join('transaction','transaction.customer_id','=','users.id')->where('transaction.type','=','sale')->where('role','=','client')->whereMonth('transaction.transaction_date', Carbon::now()->month); 
          if(auth()->user()->role == 'client'){
               $customer_data=User::select('users.id','users.company_name')->where('users.id',auth()->user()->id)->where('role','=','client')->get(); 
          }else{
               $customer_data=User::select('users.id','users.company_name')->where('role','=','client')->get(); 
          } 
         

        //  $customer_data=$customer_data->groupBy(['users.company_name','users.id'])->get();
         return view('add-invoice',compact('customer_data'));
    }
    public function manage_tax_report()
    {
        if(auth()->user()->role == 'client'){
           $customer_data=User::select('users.id','users.company_name')->where('users.id',auth()->user()->id)->where('role','=','client')->get(); 
        }else{
           $customer_data=User::select('id','company_name')->where('role','=','client')->get();
        } 
          
         return view('manage-invoice',compact('customer_data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
         
        $validator = Validator::make($request->all(), [
        'invoice_no' => 'required',
        'customer_id' => 'required',
        'datefrom' => 'required',
        'dateto' => 'required',
        
        ]);

        if ($validator->fails()) {
        return redirect('add-register')
                 ->withErrors($validator)
                 ->withInput();
        }else{
            try {
            
                $tax_generate=array('invoice_no'=>$request->invoice_no,
                    'customer_id'=>$request->customer_id,
                    'datefrom'=>$request->datefrom,
                    'dateto'=>$request->dateto,
                    'created_by'=>Auth::user()->id);
                $insert=Tax::create($tax_generate);
                $this->updated_transaction_tax($insert->id);
                // $check_transaction_invoice=Transaction::where('transaction_date','>=',$request->datefrom)
                // ->where('transaction_date','<=',$request->dateto)->where('type','=','sale')->get();
                // if(!empty($check_transaction_invoice)){
                //     foreach($check_transaction_invoice as $check_transaction){
                //         $update_invoice_no=Transaction::where('id','=',$check_transaction['id'])->update(['tax_invoice_no'=>$request->invoice_no]);
                //     }
                // }else{
                //     echo 'transaction not found';
                // }
       
                if($insert){
                    return redirect('manage-invoice')->with('success','Successfully Submitted');
                }
            } catch (\Throwable $th) {
                //dd($th->getMessage());
                return redirect('manage-invoice')->with('error',$th->getMessage());  
            }

        }
    }

    function fetchTaxData(Request $request){
        $user_id=Auth::user()->id;
        $result = array('data' => array());
        if(auth()->user()->role =='client'){
            $report=Tax::select('tax.*','users.company_name')
                            ->leftjoin('users','users.id','=','tax.customer_id')
                            ->where('users.id',auth()->user()->id)
                            ->latest();
        }else{
            $report=Tax::select('tax.*','users.company_name')
                            ->leftjoin('users','users.id','=','tax.customer_id')
                            ->latest();
        }


        if(!empty($request->datefrom)){
         $datefrom=date('Y-m-d',strtotime($request->datefrom));

         $report->whereDate('tax.datefrom', '>=', $datefrom);

        }
        if (!empty($request->dateto)) {
            $dateto=date('Y-m-d',strtotime($request->dateto));
            $report->whereDate('tax.dateto', '<=', $dateto);
        }
        
        if (!empty($request->company_id)) {
            if (auth()->user()->role == 'admin' || auth()->user()->role == 'users') {
                $report->where('tax.customer_id','=',$request->company_id);
            }
           
        }
// && auth()->user()->role == 'users
        $data=$report->get();
        // echo $request->company_id;die;

         $i=1;
         foreach ($data as $key => $value) {
         
           $check_existed=TaxDetails::where('tax_id','=',$value['id'])->first();
           
            $button='';
     
                 if (auth()->user()->role == 'admin' ) {
                $button.='<td> <a type="button" class="btn bg-gradient-danger btn-sm" data-id="'.$value['id'].'" id="delete">Delete</a></td>';
                if(empty($check_existed)){
                    $button.='<td> <a type="button" class="btn bg-gradient-primary btn-sm" data-id="'.$value['id'].'" id="update">Generate</a></td>';
                }else{
                    $button.='<td> <a type="button" class="btn bg-gradient-primary btn-sm" >Generated</a></td>';
                }
                                
            }

            $button.=' <td> <a  class="btn bg-gradient-green btn-sm" href="'.url('print-tax/'.$value['customer_id'].'/'.$value['invoice_no'].'/'.$value['datefrom'].'/'.$value['dateto'].'/'.$value['created_at']).'" target="_blank">Print</a>
                </td>';


                $result['data'][$key] = array(
                $i,
                $value['company_name'],
                $value['invoice_no'],
                $value['datefrom'],
                $value['dateto'],
                $button,
            );
       $i++;  }
     echo json_encode($result);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($customer_id,$invoice_no,$datefrom,$dateto,$created_at)
    {
        $customer_data=User::select('*')->where('role','=','client')->where('id','=',$customer_id)->first(); 
         $sell_quantity=Transaction::leftjoin('sell_lines','sell_lines.transaction_id','=','transaction.id')
                            ->whereDate('transaction.transaction_date', '>=', $datefrom)
                            ->whereDate('transaction.transaction_date', '<=', $dateto)
                            ->where('transaction.customer_id','=',$customer_id)
                            ->sum('sell_lines.quantity');
                          
          $sell_unit_price=Transaction::leftjoin('sell_lines','sell_lines.transaction_id','=','transaction.id')
                            ->whereDate('transaction.transaction_date', '>=', $datefrom)
                            ->whereDate('transaction.transaction_date', '<=', $dateto)
                            ->where('transaction.customer_id','=',$customer_id)
                        
                            ->sum('sell_lines.unit_price');
        //   $tax_rate=($sell_quantity*$customer_data->amount)*5/100;
          $dono_from=DB::select("SELECT a.ledger_value FROM transaction a 
WHERE a.type='sale' AND a.ledger='DoNo' AND a.customer_id=$customer_id AND a.transaction_date >='$datefrom' AND a.transaction_date <='$dateto' AND a.ledger_value!=''
ORDER BY a.ledger_value ASC LIMIT 1");
             $dono_to=DB::select("SELECT a.ledger_value FROM transaction a 
WHERE a.type='sale' AND a.ledger='DoNo' AND a.customer_id=$customer_id AND a.transaction_date >='$datefrom' AND a.transaction_date <='$dateto' AND a.ledger_value!=''
ORDER BY a.ledger_value DESC LIMIT 1");
              $cashmemo_from=DB::select("SELECT a.ledger_value FROM transaction a 
WHERE a.type='sale' AND a.ledger='CashMemo' AND a.customer_id=$customer_id AND a.transaction_date >='$datefrom' AND a.transaction_date <='$dateto' AND a.ledger_value!=''
ORDER BY a.ledger_value ASC LIMIT 1");
                   $cashmemo_to=DB::select("SELECT a.ledger_value FROM transaction a 
WHERE a.type='sale' AND a.ledger='CashMemo' AND a.customer_id=$customer_id AND a.transaction_date >='$datefrom' AND a.transaction_date <='$dateto' AND a.ledger_value!=''
ORDER BY a.ledger_value DESC LIMIT 1");
                      // print_r( $dono_from);
                      // print_r( $dono_to); die;
                      $abc=array();
                       $total_sell=Transaction::leftjoin('sell_lines','sell_lines.transaction_id','=','transaction.id')
                            ->whereDate('transaction.transaction_date', '>=', $datefrom)
                            ->whereDate('transaction.transaction_date', '<=', $dateto)
                            ->where('transaction.customer_id','=',$customer_id)
                        
                            ->sum('sell_lines.gallon_price');
                            //  print_r($sell_quantity);
                            // print_r($total_sell);die;
                            if ($sell_quantity > 0) {
                 $tax_rate=($sell_quantity *round($total_sell / $sell_quantity,2))*5/100;
           }else{
        return redirect('manage-invoice')->with('success','generated issue found');
           }
        
        //   $tax_rate=($sell_quantity*($total_sell/$sell_quantity))*5/100;
                       $cashmemo=Transaction::select('transaction.ledger_value')
                            ->whereDate('transaction.transaction_date', '>=', $datefrom)
                            ->whereDate('transaction.transaction_date', '<=', $dateto)
                            ->where('transaction.customer_id','=',$customer_id)
                            ->where('transaction.type','=','sale')
                            ->where('transaction.ledger','=','CashMemo')->orderBy('transaction.ledger_value', 'asc')->get();
                            foreach($cashmemo as $cash_mem){
                                $abc[]=$cash_mem['ledger_value'];
                            }
                            $new_memo=implode(",", $abc);
                // $amount_word=   $this->convert_number(($sell_quantity*$customer_data->amount)+$tax_rate); 
                $final= ($sell_quantity *round($total_sell / $sell_quantity,2))+$tax_rate;
                //  echo round($final,2);die;
                    $amount_word=   $this->convert_number(round($final,1)); 
                   
                
        return view('taxInvoice',compact('customer_data','invoice_no','created_at','sell_quantity','sell_unit_price','tax_rate','dono_from','dono_to','cashmemo_from','cashmemo_to','amount_word','new_memo','total_sell','dateto'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $delete = Tax::find($id);
        $delete->delete();
        $delete1=TaxDetails::where('tax_id',$id)->delete();
    }
     public function updated_transaction_tax($id)
    {
        $t_data = Tax::find($id)->toArray();
           $check_transaction_invoice=Transaction::leftjoin('sell_lines', 'sell_lines.transaction_id', '=', 'transaction.id')
                ->where('transaction.transaction_date','>=',$t_data['datefrom'])
                ->where('transaction.transaction_date','<=',$t_data['dateto'])->where('transaction.type','=','sale')
                ->where('transaction.customer_id','=',$t_data['customer_id'])
                ->where('sell_lines.tax','!=','')
                ->get()->toArray();
          
                $sum_of_qty=0;
                $sum_total=0;
                $sum_rate=0;
                $sum_tax_amount=0;
                $sum_final_total=0;
                if(!empty($check_transaction_invoice)){
                    foreach($check_transaction_invoice as $check_transaction){
                        $update_invoice_no=Transaction::where('id','=',$check_transaction['id'])->update(['tax_invoice_no'=>$t_data['invoice_no']]);
                        $sum_of_qty +=$check_transaction['quantity'];
                        $sum_total +=$check_transaction['gallon_price'];
                    }
                }else{
                    return redirect('manage-invoice')->with('error','transaction not found');  exit;
                   // dd('transaction not found');
                }
                $sum_rate=round($sum_total/$sum_of_qty,2);
                $sum_tax_amount=($sum_total*5)/100;
                $sum_final_total =round($sum_tax_amount+$sum_total,2);
                $customer_name=User::find($t_data['customer_id'])->toArray();
                $tax_details=array();
                $tax_details['invoice_no']=$t_data['invoice_no'];
                $tax_details['customer_name']=$customer_name['name'];
                $tax_details['trn_no']=$customer_name['trn_no'];
                $tax_details['qty']=$sum_of_qty;
                $tax_details['rate']=$sum_rate;
                $tax_details['total']=$sum_total;
                $tax_details['tax']=$sum_tax_amount;
                $tax_details['final_total']=$sum_final_total;
                 $tax_details['tax_id']=$id;
                  $tax_details['cust_id']=$t_data['customer_id'];
        
                $tax_details['datefrom']=$t_data['datefrom'];
                $tax_details['dateto']=$t_data['dateto'];
                $check_transaction_updated_or_not=TaxDetails::where('datefrom',$t_data['datefrom'])->where('dateto',$t_data['dateto'])
                ->where('cust_id',$t_data['customer_id'])->orderBy('invoice_no', 'asc')->get()->toArray();
                if(empty($check_transaction_updated_or_not)){
                     $insert=TaxDetails::create($tax_details);
                     return json_encode(['status' => true,'message'=>'successfully updated']);
                }else{
                    return json_encode(['status' => false,'message'=> 'alreday existed ! please contact Support team']);
                }
               
      
    }

//     function convert_number($number) {
//     if (($number < 0) || ($number > 999999999)) {
//         throw new Exception("Number is out of range");
//     }

//     $Gn = floor($number / 1000000);
//     /* Millions (giga) */
//     $number -= $Gn * 1000000;
//     $kn = floor($number / 1000);
//     /* Thousands (kilo) */
//     $number -= $kn * 1000;
//     $Hn = floor($number / 100);
//     /* Hundreds (hecto) */
//     $number -= $Hn * 100;
//     $Dn = floor($number / 10);
//     /* Tens (deca) */
//     $n = $number % 10;
//     /* Ones */

//     $res = "";

//     if ($Gn) {
//         $res .= $this->convert_number($Gn) .  "Million";
//     }

//     if ($kn) {
//         $res .= (empty($res) ? "" : " ") .$this->convert_number($kn) . " Thousand";
//     }

//     if ($Hn) {
//         $res .= (empty($res) ? "" : " ") .$this->convert_number($Hn) . " Hundred";
//     }

//     $ones = array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", "Nineteen");
//     $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eigthy", "Ninety");

//     if ($Dn || $n) {
//         if (!empty($res)) {
//             $res .= " and ";
//         }

//         if ($Dn < 2) {
//             $res .= $ones[$Dn * 10 + $n];
//         } else {
//             $res .= $tens[$Dn];

//             if ($n) {
//                 $res .= "-" . $ones[$n];
//             }
//         }
//     }

//     if (empty($res)) {
//         $res = "zero";
//     }

//     return $res;
// }
// function convert_number(float $amount)
// {
//     // echo $amount;die;
//   $amount_after_decimal = round($amount - ($num = floor($amount)), 2) * 100;
//   // Check if there is any number after decimal
//   $amt_hundred = null;
//   $count_length = strlen($num);
//   $x = 0;
//   $string = array();
//   $change_words = array(0 => '', 1 => 'One', 2 => 'Two',
//      3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six',
//      7 => 'Seven', 8 => 'Eight', 9 => 'Nine',
//      10 => 'Ten', 11 => 'Eleven', 12 => 'Twelve',
//      13 => 'Thirteen', 14 => 'Fourteen', 15 => 'Fifteen',
//      16 => 'Sixteen', 17 => 'Seventeen', 18 => 'Eighteen',
//      19 => 'Nineteen', 20 => 'Twenty', 30 => 'Thirty',
//      40 => 'Forty', 50 => 'Fifty', 60 => 'Sixty',
//      70 => 'Seventy', 80 => 'Eighty', 90 => 'Ninety');
//     $here_digits = array('', 'Hundred','Thousand','Lakh', 'Crore');
//     while( $x < $count_length ) {
//       $get_divider = ($x == 2) ? 10 : 100;
//       $amount = floor($num % $get_divider);
//       $num = floor($num / $get_divider);
//       $x += $get_divider == 10 ? 1 : 2;
//       if ($amount) {
//       $add_plural = (($counter = count($string)) && $amount > 9) ? 's' : null;
//       $amt_hundred = ($counter == 1 && $string[0]) ? '  ' : null;
//       $string [] = ($amount < 21) ? $change_words[$amount].' '. $here_digits[$counter]. $add_plural.' 
//       '.$amt_hundred:$change_words[floor($amount / 10) * 10].' '.$change_words[$amount % 10]. ' 
//       '.$here_digits[$counter].$add_plural.' '.$amt_hundred;
//         }
//   else $string[] = null;
//   }
//   $implode_to_Rupees = implode('', array_reverse($string));
// //   echo $change_words[$amount_after_decimal / 10];die;
// // echo $amount_after_decimal / 10;
// //   echo $change_words[$amount_after_decimal / 10];die;
//   $get_paise = ($amount_after_decimal > 0) ? "And " . ($change_words[$amount_after_decimal / 10] . " 
//   " . $change_words[$amount_after_decimal % 10]) . ' Fills' : '';
//   return ($implode_to_Rupees ? $implode_to_Rupees . 'Dirhams ' : '') . $get_paise;
// }
function convert_number($number)
{
 $decimal = round($number - ($no = floor($number)), 2) * 100;
    $decimal_part = $decimal;
    $hundred = null;
    $hundreds = null;
    $digits_length = strlen($no);
    $decimal_length = strlen($decimal);
    $i = 0;
    $str = array();
    $str2 = array();
    $words = array(0 => '', 1 => 'one', 2 => 'two',
        3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six',
        7 => 'seven', 8 => 'eight', 9 => 'nine',
        10 => 'ten', 11 => 'eleven', 12 => 'twelve',
        13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen',
        16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
        19 => 'nineteen', 20 => 'twenty', 30 => 'thirty',
        40 => 'forty', 50 => 'fifty', 60 => 'sixty',
        70 => 'seventy', 80 => 'eighty', 90 => 'ninety');
    $digits = array('', 'hundred','thousand','lakh', 'crore');

    while( $i < $digits_length ) {
        $divider = ($i == 2) ? 10 : 100;
        $number = floor($no % $divider);
        $no = floor($no / $divider);
        $i += $divider == 10 ? 1 : 2;
        if ($number) {
            $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
            $hundred = ($counter == 1 && $str[0]) ? '  ' : null;
            $str [] = ($number < 21) ? $words[$number].' '. $digits[$counter]. $plural.' '.$hundred:$words[floor($number / 10) * 10].' '.$words[$number % 10]. ' '.$digits[$counter].$plural.' '.$hundred;
        } else $str[] = null;
    }

    $d = 0;
    while( $d < $decimal_length ) {
        $divider = ($d == 2) ? 10 : 100;
        $decimal_number = floor($decimal % $divider);
        $decimal = floor($decimal / $divider);
        $d += $divider == 10 ? 1 : 2;
        if ($decimal_number) {
            $plurals = (($counter = count($str2)) && $decimal_number > 9) ? 's' : null;
            $hundreds = ($counter == 1 && $str2[0]) ? ' and ' : null;
            @$str2 [] = ($decimal_number < 21) ? $words[$decimal_number].' '. $digits[$decimal_number]. $plural.' '.$hundred:$words[floor($decimal_number / 10) * 10].' '.$words[$decimal_number % 10]. ' '.$digits[$counter].$plural.' '.$hundred;
        } else $str2[] = null;
    }

    $Rupees = implode('', array_reverse($str));
    $paise = implode('', array_reverse($str2));
    $paise = ($decimal_part > 0) ? ' and '. $paise . ' Fills' : '';
    return ($Rupees ? $Rupees . 'Dirham ' : '') . $paise;
}
}
