<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\CompanyModel;
use App\Models\AddressBookModel;
use App\Models\Invoice;
use App\Models\InvoiceItems;
use App\Models\ServiceList;
use App\Models\Journal;
use App\Models\AccountHead;
use App\User;
use App\Models\CompanyActivity;

class InvoiceController extends Controller
{
    public function __construct(){
        $this->middleware('auth');
    } 
    
    function index()
    {
        if(\Auth::user()->utype==1 || \Auth::user()->utype==3){
            if(\Auth::user()->utype==3)
            {
                $uid=\Auth::user()->id;
                $data['invoices']=Invoice::with(['items','items.service','client','company'])->where('client_id',$uid)->orderBy('id','desc')->get();
            }
            else{
                
                $data['invoices']=Invoice::with(['items','items.service','client'])->orderBy('id','desc')->get();
            }
    
            $data['account_types']=AccountHead::where('type_id',1)->get();
            $data['title']='Invoice List';  
            
            return view('admin.invoice.index',$data);
        }
        else
        {
            return "You Don't Have Access";
        }
    }


    function create()
    {
        $data['code']=$this->generate_inv_id();
        $data['companies']=User::where('utype',3)->orderBy('name','asc')->get(['id','company']);
        $data['client_list']=CompanyModel::where('status',2)->orderBy('name','asc')->get();
        $data['services']=ServiceList::orderBy('name','asc')->get(['id','name']);
        $data['title']='Create Invoice';
        return view('admin.invoice.create',$data);
    }

    function store(Request $req)
    {
        /*$this->validate($req,[
            'invoice_code'=>'required|unique:invoice'
        ]);*/

        $code=$req->get('invoice_code');

        $file_name='';
        if($req->hasFile('attachment')){

            $allowed=['docx','doc','pdf','jpg','jpeg','png'];
            $file=$req->file('attachment');
            $ext=$file->getClientOriginalExtension();
            if(in_array($ext, $allowed))
            {
                $file_name=$code.'.'.$ext;
            }

            $file->move('assets/invoice/',$file_name);

        }

        $invoice=new Invoice();

        $invoice->invoice_code=$code;
        $invoice->client_id=$req->get('client');
        $invoice->invoice_date=$req->get('invoice_date');
        $invoice->due_date=$req->get('due_date');
        $invoice->notes=$req->get('note');
        $invoice->po_no=$req->get('po_no');
        $invoice->currency=$req->get('currency');
        $invoice->tax=$req->get('tax');
        $invoice->vat=$req->get('vat');
        $invoice->attachment=$file_name;
        $invoice->created_by=\Auth::user()->id;
        $invoice->status=0;

        $saved=$invoice->save();


        if($saved)
        {
            $service=$req->get('service');
            $payable=$req->get('payable_amount');
            $paid=$req->get('paid_amount');
            $particular=$req->get('particular');
            if(count($payable)>0)
            {
                $indx=0;
                foreach($payable as $row){
                    $items=new InvoiceItems();
                    $items->invoice_id=$invoice->id;
                    $items->particular=$particular[$indx];
                    $items->service_id=$service[$indx];
                    $items->payable_amount=$payable[$indx];
                    $items->paid_amount=$paid[$indx];
                    $items->save();
                    $indx++;
                }
            }


            $inv=Invoice::with(['items','items.service','client','company'])->orderBy('id','desc')->find($invoice->id);

            date_default_timezone_set("Asia/Dhaka");
            $date = date("Y-m-d h:i:s");
            $sav1 = new CompanyActivity;
            $sav1->activity = "Invoice Created";
            $sav1->company_id = $req->get('client');
            $sav1->user_id = 2;
            $sav1->created_at = $date;
            $sav1->date = $date;
            $sav1->save();


            $data['invoice']=$inv;
            //dd($inv);
            $company_id = $inv->company?$inv->company->id:'';
            $client_email=User::where('company',$company_id)->pluck('email')->toArray();
            foreach ($client_email as $value) {
                \Mail::send('emails.invoice_created', $data, function ($message) use($value,$file_name) {

                    $message->from('m.revinr@gmail.com', 'Revinr CMS');
                    //$message->sender('john@johndoe.com', 'John Doe');
                
                    $message->to($value, 'Revinr CMS');
                    $message->to('info@revinr.com', 'Revinr CMS');
                
                    // $message->cc('john@johndoe.com', 'Revinr CMS');
                    $message->bcc('shamim@revinr.com', 'Revinr CMS');
                
                    //$message->replyTo('john@johndoe.com', 'John Doe');
                
                    $message->subject('An invoice has been generated from revinr');
                
                    // $message->priority(3);
                
                    $message->attach('assets/invoice/'.$file_name);

                });
            }
            //});
        }
        return redirect()->back()->with('message','Invoice created successfully !');

    }

    function invoice_created_email($id)
    {
        $inv=Invoice::with(['items','items.service','client','company'])->orderBy('id','desc')->find($id);
        $data['invoice']=$inv;

        /*$client_email=$inv->client?$inv->client->email:'';*/
        $company_id = $inv->company?$inv->company->id:'';
        $client_email=User::where('company',$company_id)->pluck('email')->toArray();
        foreach ($client_email as $value) {

            \Mail::send('emails.invoice_created', $data, function ($message) use($value) {

                $message->from('m.revinr@gmail.com', 'Revinr CMS');
                //$message->sender('john@johndoe.com', 'John Doe');
            
                $message->to($value, 'Revinr CMS');
                $message->to('info@revinr.com', 'Revinr CMS');
            
                $message->cc('helaldu@gmail.com', 'Revinr CMS');
                $message->bcc('shamim@revinr.com', 'Revinr CMS');
            
            
                $message->subject('An invoice has been generated from revinr');
            
            });
        }

        return 'ok';
    }


    function edit($id)
    {
        $data['title']='Edit Invoice';
        return view('admin.invoice.edit',$data);
    }

    function update(Request $req)
    {

    }

    function delete($id)
    {

    }


    function show($id)
    {
        $data['invoice']=Invoice::with(['items','items.service','client'])->orderBy('id','desc')->find($id);
        $data['title']='View Invoice';
        return view('admin.invoice.show',$data);
    }

    function generate_inv_id()
    {
        $inv=Invoice::orderBy('id','desc')->first();

        $code="0000001";

        if($inv)
        {
            if(!empty($inv->invoice_code))
            {
                $inv_code=(int)$inv->invoice_code;
                $inv_code=$inv_code+1;

                if($inv_code<10){
                    $code="000000".$inv_code;
                }
                elseif($inv_code<100){
                    $code="00000".$inv_code;
                }
                elseif($inv_code<1000){
                    $code="0000".$inv_code;
                }
                elseif($inv_code<10000){
                    $code="000".$inv_code;
                }
                elseif($inv_code<100000){
                    $code="00".$inv_code;
                }
                elseif($inv_code<1000000){
                    $code="0".$inv_code;
                }
                elseif($inv_code<10000000){
                    $code=$inv_code;
                }
            }
        }

        return $code;
    }


    function make_payment(Request $req)
    {

        $id=$req->get('id');
        $amount=$req->get('amount');

        $invoice=Invoice::find($id);
        $invoice->status=1;

        $invoice->save();


        $journal=new Journal();

        $journal->ref_id=$req->get('acc_id');
        $journal->debit_account=$req->get('mode_of_payment');
        $journal->credit_account=$req->get('acc_id');
        $journal->description=$req->get('description');
        $journal->amount=$amount;
        $journal->is_approaved=0;
        $journal->created_by=\Auth::user()->id;
        $journal->created_at=$req->get('date',date('Y-m-d'));
        $journal->client_id=$req->get('client');
        $journal->save();

        $inv=Invoice::with(['items','items.service','client','company'])->orderBy('id','desc')->find($id);
        $data['invoice']=$inv;

        /*$client_email=$inv->client?$inv->client->email:'';*/
        date_default_timezone_set("Asia/Dhaka");
            $date = date("Y-m-d h:i:s");
            $sav1 = new CompanyActivity;
            $sav1->activity = "Invoice Created";
            $sav1->company_id = $req->get('client');
            $sav1->user_id = 2;
            $sav1->created_at = $date;
            $sav1->date = $date;
            $sav1->save();
        $company_id = $inv->company?$inv->company->id:'';
        $client_email=User::where('company',$company_id)->pluck('email')->toArray();
        foreach ($client_email as $value) {

            \Mail::send('emails.payment_receipt', $data, function ($message) use($value) {

                $message->from('m.revinr@gmail.com', 'Revinr CMS');
                //$message->sender('john@johndoe.com', 'John Doe');
            
                $message->to($value, 'Revinr CMS');
                $message->to('info@revinr.com', 'Revinr CMS');
            
                $message->cc('helaldu@gmail.com', 'Revinr CMS');
                $message->bcc('shamim@revinr.com', 'Revinr CMS');
            
            
                $message->subject('Payment receipt from revinr');
            
            });
        }

        // echo "Payment done successfully !";
        \Session::flash('success','Payment done successfully !');
        return redirect('invoice');
    }
}