<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Branch;
use App\Models\Inventory;
use App\Models\Product;
use App\Models\Category;
use App\Models\OBF;
use App\Models\Order;
use App\Http\Requests\InventoryRequest;
use App\Http\Requests\InventoryAcceptRequest;
use Auth, DB, Mail, Validator, File, DataTables;
use App\Imports\Importpetty_cash;
use App\Exports\Exportpetty_cash;
use Maatwebsite\Excel\Facades\Excel;
use Elibyy\TCPDF\Facades\TCPDF;
use PDF;

class PettyController extends Controller
{
    /** construct */
    public function __construct()
    {
        $this->middleware('permission:petty_cash-create', ['only' => ['create']]);
        $this->middleware('permission:petty_cash-edit', ['only' => ['edit']]);
        // $this->middleware('permission:inventory-view', ['only' => ['view']]);
        // $this->middleware('permission:petty_cash-delete', ['only' => ['delete']]);
    }
    /** construct */
    
    public function index(Request $request)
    {
       
        $data = DB::table('petty_cash')->orderBy('id', 'desc')->where('branch_id',auth()->user()->branch)->get();
        $expense_data = DB::table('petty_cash_expense')->where('branch_id',auth()->user()->branch)->SUM('amount');
        $petty_cash_amount = DB::table('petty_cash')->where('branch_id',auth()->user()->branch)->SUM('petty_cash_amount');
        return view('pettycash.index')->with(['data' => $data, 'expense_data' => $expense_data,'petty_cash_amount' => $petty_cash_amount]);
    }   

    /** index */
    public function indexData(Request $request)
    {
        if ($request->ajax()) {
            $data = DB::table('petty_cash_expense as pce')->select('pce.id as petty_cash_id', 'pce.description','pce.department_id','pce.pay_to','pce.expense_type_id','pce.amount','pce.created_at','dept.name','et.title')->leftjoin('department as dept', 'dept.id', 'pce.department_id')
                ->leftjoin('expense_type as et', 'et.id', 'pce.expense_type_id')->where('pce.branch_id',auth()->user()->branch)->orderBy('pce.id', 'desc')->get();
            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($data) {
                    $return = '<div class="btn-group">';

                    if(auth()->user()->can('petty_cash-edit')){

                    $return .= '<a href="' . route('pettycash.edit', ['id' => base64_encode($data->petty_cash_id)]) . '" class="btn btn-default btn-xs">
                                <i class="fa fa-edit"></i>
                                </a> &nbsp;';
                    }

                    $return .= '</div>';

                    return $return;
                })
               
                ->rawColumns(['action'])
                ->make(true);
        }
       // return view('pettycash.index');
    }
    /** index */

    /** create */
    public function create(Request $request)
    {
        
         $expensetypes = DB::table('expense_type')->get();
         $departments = DB::table('department')->orderBy('id', 'desc')->get();
        return view('pettycash.create')->with(['expensetypes' => $expensetypes, 'departments' => $departments]);
    }
    /** create */

    /** insert */
    public function insert(Request $request)
    {
        if ($request->ajax()) {
            return true;
        }

        $data = [
            'expense_type_id' => $request->expense_type_id ?? NULL,
            'department_id' => $request->department_id  ?? NULL,
            'pay_to' => $request->pay_to ?? NULL,
            'amount' => $request->amount ?? NULL,
            'branch_id' => auth()->user()->branch,
            'description' => $request->description ?? NULL,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
            'updated_by' => auth()->user()->id
        ];
       
        $last_id = DB::table('petty_cash_expense')->insertGetId($data);

        if ($last_id){
          //  $this->recipt_pdf($last_id);
        //     $filename ='voucher.pdf';
        //     $view = \View::make('pettycash.voucher');
        //     $html = $view->render();
    
        // 	$pdf = new TCPDF('L','A5');
            
        //     $pdf::SetTitle('Hello World');
        //     $pdf::AddPage();
        //     $pdf::writeHTML($html, true, false, true, false, '');
    
        //     $pdf::Output(public_path($filename), 'F');
    
        //     return response()->download(public_path($filename));
            
          return redirect()->route('pettycash')->with('success', 'Record inserted successfully');
        } else {
            return redirect()->back()->with('error', 'Failed to insert record')->withInput();
        }
    }
    /** insert */

    /** view */
    public function view(Request $request)
    {
        $id = base64_decode($request->id);

        $categories = Category::select('id', 'name')->where(['status' => 'active'])->get();
        $branches = Branch::select('id', 'name')->where(['status' => 'active'])->get();
        $data = Inventory::where(['id' => $id])->first();

        return view('inventory.view')->with(['data' => $data, 'branches' => $branches, 'categories' => $categories]);
    }
    /** view */

    /** edit */
    public function edit(Request $request)
    {
        $id = base64_decode($request->id);
        $data = DB::table('petty_cash_expense')->where(['id' => $id])->first();
        $expensetypes = DB::table('expense_type')->get();
        $departments = DB::table('department')->orderBy('id', 'desc')->get();
        return view('pettycash.edit')->with(['data' => $data,'expensetypes' =>$expensetypes,'departments' => $departments]);
    }
    /** edit */
    
    /** edit pettycash */
    public function modify(Request $request)
    {
        $id = base64_decode($request->id);

        $data = DB::table('petty_cash')->first();

        return view('pettycash.modifypettycash')->with(['data' => $data]);
    }
    /** edit pettycash */
    
    
     /** edit pettycash */
    public function updatepettycash(Request $request)
    {
        $id = base64_decode($request->id);

        $data = [
            
            'petty_cash_amount' => $request->petty_cash_amount ?? NULL,
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        $update = DB::table('petty_cash')->where(['id' => $request->id])->update($data);

        if ($update)
            return redirect()->route('pettycash')->with('success', 'Record updated successfully');
        else
            return redirect()->back()->with('error', 'Failed to update record')->withInput();
    }
    /** edit pettycash */
    
            
    /** update */
    public function update(Request $request)
    {
        if ($request->ajax()) {
            return true;
        }

        $data = [
            'expense_type_id' => $request->expense_type_id ?? NULL,
            'department_id' => $request->department_id  ?? NULL,
            'pay_to' => $request->pay_to ?? NULL,
            'amount' => $request->amount ?? NULL,
            'branch_id' => auth()->user()->branch,
            'description' => $request->description ?? NULL,
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id
        ];

        $update = DB::table('petty_cash_expense')->where(['id' => $request->id])->update($data);

        if ($update)
            return redirect()->route('pettycash')->with('success', 'Record updated successfully');
        else
            return redirect()->back()->with('error', 'Failed to update record')->withInput();
    }
    /** update */
    
    
   
    /** Import */
        public function import(Request $request){
            $import = Excel::import(new Importpetty_cash(), $request->file('file'));    
            if($import){
                Excel::store(new Importpetty_cash(), 'PettyCash_'.Date('YmdHis').'.xlsx' ,'excel_import');
                return redirect()->route('pettycash')->with('sucess' ,'File Imported Sucessfully');
            }
        }
    /** Import */

    /** Export */
        public function export(Request $request){
            $slug = $request->slug;
            $name = 'PettyCash_'.Date('YmdHis').'.xlsx';

            try {
                return Excel::download(new Exportpetty_cash($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
    /** Export */
        public function addBalance(Request $request){
            if ($request->ajax()) {
            return true;
            }

        $data = [
            'petty_cash_amount' => $request->petty_cash ?? NULL,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id
        ];
       
        $last_id = DB::table('petty_cash')->insertGetId($data);

        if ($last_id)
               return redirect()->route('pettycash')->with('sucess' ,'Balance Added Sucessfully');
        }
    
     public function recipt_pdf($id)
    {
        
       // $page = $request->page;
        $cash_receipt_id = $id;
        
       $img = DB::table('global_configuration')->select('*')->where('status','active')->first();
        //dd($img);
        $img1 = $img->cash_receipt_logo1;
        $img2 = $img->cash_receipt_logo2;
       /*if($img == null){
           $img1 = "http://erp.ibgroup.in/public/assets/img/111.jpg";
           $img2 = "http://erp.ibgroup.in/public/assets/img/222.jpg";
       }
       else{
           $img1 = $img->cash_receipt_logo1;
           $img2 = $img->cash_receipt_logo2;
       }
*/
               
             ini_set('memory_limit', '48M');

            PDF::SetAuthor('Nicola Asuni');
            PDF::SetTitle('RECEIPT');
            PDF::SetSubject('RECEIPT');
            PDF::setImageScale(PDF_IMAGE_SCALE_RATIO);
            PDF::AddPage('L', 'A4');
            /*PDF::Image('assets/img/atul-logo.jpg', 15, 18, 23, 24, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);*/

            PDF::Image(public_path('uploads/global_configuration/cash_receipt_logo_one/'.$img1), 15, 11, 46, 19, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);


            PDF::Image(public_path('uploads/global_configuration/cash_receipt_logo_two/'.$img2), 180, 14, 100, 16, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);

            /*PDF::Image(public_path('assets/img/ib_logo.jpeg'), 15, 14, 60, 12, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);*/
            
           
          

            $receipt_title = '';
            $payment_type = '';
            
            /*$cheque_no
            $cheque_date 
            $bank_name */

            /*var_dump($data->cash_receipt_payment_type);
            die('stp[');*/
            
         
                $receipt_title = 'PAYMENT RECEIPT';
                $payment_type = 'cash';
        
          
            $data = DB::table('petty_cash_expense')->where('id',$id)->first();      $amount_word = $this->prisetoword($data->amount);
            
           // $img1 = 'http://erp.ibgroup.in/public/assets/img/111.jpg';
          //  $img2 = 'http://erp.ibgroup.in/public/assets/img/222.jpg';
            
            //receipt no
            // $branch = $data->branch_name;
            // if($branch == 'Rajkot'){
            //     $b_name = 'RJT';
            // }
            // elseif($branch == 'Jamnagar'){
            //     $b_name = 'Jam';
            // }
            // elseif($branch == 'Junagadh'){
            //     $b_name = 'Juna';
            // }elseif($branch == 'Morbi'){
            //     $b_name = 'Mor';
            // }else{
            //     $b_name = '';
            // }
        //receipt no
        
             /*<h1 align="center" style="font-size:26px;">ATUL MOTORS JAM LLP</h1>
                        <p align="center">Near Royal Enfield, Jamnagar-Rajkot Highway, Hapa, Jamnagar - 361120, GUJARAT, INDIA.</p>*/
            $tbl = '<div>   
                        <table cellspacing="0" cellpadding="5" border="0" >
                            <tr>
                                <td></td>
                                <td  style="width:33%;border-right:1px solid black;"><b>Pay to </b><span style="text-decoration:underline">'.$data->pay_to.'</span><br></td>
                                <td ><span style="background-color:black;color:white">Voucher</span><br><b>No. : </b>'.$cash_receipt_id.'<br><b>Receipt Date :</b>'.$data->created_at.'</td>
                                 <td></td>
                            </tr>
                        </table>
                        <table cellspacing="0" cellpadding="5" border="0"  style="border:1px solid black;">
                            <tr>
                                <td style="width:70%;border-right:1px solid black;border-top:1px solid black;border-bottom:1px solid black;"></td>
                                <td style="width:30%;border-top:1px solid black;border-bottom:1px solid black;">
                                  
                                </td>
                                <td></td>
                            </tr>
                            <tr>
                                <td style="width:70%;border-right:1px solid black;border-top:1px solid black;border-bottom:1px solid black;"><b>Rupees in words :</b> '.$amount_word.'ONLY</td>
                                <td style="width:30%;border-right:1px solid black;border-top:1px solid black;border-bottom:1px solid black;"><b>Rs. </b>'.$data->amount.'/- </td>
                                <td></td>
                            </tr>
                            
                        </table>
                        <br><br><br><br>
                        <br><br>
                        <table>
                            <tr>
                                <td style="width:30%;"><b>Authorised by</b></td>
                                <td style="width:30%;text-align:center"><b>Accountant</b></td>
                                <td style="width:30%;text-align:right"><b>Receiver Signature</b></td>
                            </tr>
                        </table>
                    </div>';

            PDF::writeHTML($tbl, true, false, false, false, '');

            PDF::SetFont('dejavusans', '', 10);
            //$content = "Office Copy";
            PDF::SetXY(260, 42);
            //PDF::Cell(0, 0, $content);
            PDF::Output('receipt.pdf', 'I');
    }
     public function prisetoword($number){
        // $number = 230558;
        $no = floor($number);
        $point = round($number - $no, 2) * 100;
        $hundred = null;
        $digits_1 = strlen($no);
        $i = 0;
        $str = 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_1) {
            $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;
        }
        $str = array_reverse($str);
        $word_price = implode('', $str);
       /* $points = ($point) ?
        "." . $words[$point / 10] . " " . 
          $words[$point = $point % 10] : '';*/
        $word_price . "ONLY";

        return $word_price;
    }

    

   

    
}
