<?php

namespace App\Console\Commands;

use App\Invoice;
use App\InvoiceItems;
use App\UniversalSearch;
use Carbon\Carbon;
use Illuminate\Console\Command;

class AutoCreateRecurringInvoices extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'recurring-invoice-create';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'auto create recurring invoices ';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $invoices = Invoice::with('recurrings','items')->whereNull('parent_id')->where('recurring', 'yes')->get();

        $currentDate = Carbon::now();
        foreach($invoices as $invoice){
            $createdInvoice = 1;
            if($invoice->recurrings->count() > 0){
                $createdInvoice = $invoice->recurrings->count();
            }
            $allDates = [];
            $billingCycle   = $invoice->billing_cycle;
            for($i=1;$i<=$billingCycle;$i++){
                if($createdInvoice < ($billingCycle-1))
                {
                    $issueDate = $newIssueDate = $invoice->issue_date;
                    if($invoice->billing_frequency == 'day'){
                        $addDays = $invoice->billing_interval*$createdInvoice;
                        $newIssueDate = $issueDate->addDays($addDays)->format('Y-m-d');
                    }
                    elseif($invoice->billing_frequency == 'week'){
                        $addWeeks = $invoice->billing_interval*$createdInvoice;
                        $newIssueDate = $issueDate->addWeeks($addWeeks)->format('Y-m-d');
                    }
                    elseif($invoice->billing_frequency == 'month'){
                        $addMonths = $invoice->billing_interval*$createdInvoice;
                        $newIssueDate = $issueDate->addMonths($addMonths)->format('Y-m-d');
                    }
                    elseif($invoice->billing_frequency == 'year'){
                        $addYears = $invoice->billing_interval*$createdInvoice;
                        $newIssueDate = $issueDate->addYears($addYears)->format('Y-m-d');
                    }
                    $allDates[] = $newIssueDate;
                    $createdInvoice++;
                }

            }
            if(in_array($currentDate->format('Y-m-d'), $allDates)){
                $this->invoiceCreate($invoice);
            }
        }
    }

    public function invoiceCreate($invoiceData)
    {
        $invoice = $invoiceData->replicate();

        $diff = $invoice->issue_date->diffInDays($invoice->due_date);
        $currentDate = Carbon::now();
        $invoice->parent_id = $invoiceData->id;
        $invoice->send_status = 1;
        $invoice->issue_date = $currentDate->format('Y-m-d');
        $invoice->due_date   = $currentDate->addDays($diff)->format('Y-m-d');
        $invoice->recurring   = 'no';
        $invoice->billing_cycle   = null;
        $invoice->billing_interval   = null;
        $invoice->billing_frequency   = null;
        $invoice->save();

        foreach ($invoiceData->items as $key => $item) :
            InvoiceItems::create(
                [
                    'invoice_id' => $invoice->id,
                    'item_name' => $item->item_name,
                    'item_summary' => $item->item_summary,
                    'type' => 'item',
                    'quantity' => $item->quantity,
                    'unit_price' => $item->unit_price,
                    'amount' => $item->amount,
                    'taxes' => $item->taxes
                ]
            );
        endforeach;

        //log search
        $this->logSearchEntry($invoice->id, 'Invoice ' . $invoice->invoice_number, 'admin.all-invoices.show', 'invoice');

    }
    public function logSearchEntry($searchableId, $title, $route, $type)
    {
        $search = new UniversalSearch();
        $search->searchable_id = $searchableId;
        $search->title = $title;
        $search->route_name = $route;
        $search->module_type = $type;
        $search->save();
    }
//    public function invoiceCreate($invoiceData)
//    {
//        $invoice = new Invoice();
//
//        $diff = $invoiceData->issue_date->diffInDays($invoiceData->due_date);
//        $currentDate = Carbon::now();
//        $invoice->project_id = $invoiceData->project_id;
//        $invoice->client_id = $invoiceData->client_id;
//        $invoice->parent_id = $invoiceData->id;
//        $invoice->send_status = 1;
//        $invoice->issue_date = $currentDate->format('Y-m-d');
//        $invoice->due_date   = $currentDate->addDays($diff)->format('Y-m-d');
//        $invoice->recurring   = 'no';
//        $invoice->billing_cycle   = null;
//        $invoice->billing_interval   = null;
//        $invoice->billing_frequency   = null;
//        $invoice->sub_total   = $invoiceData->sub_total;;
//        $invoice->discount = $invoiceData->discount;;
//        $invoice->discount_type = $invoiceData->discount_type;;
//        $invoice->total = $invoiceData->total;;
//        $invoice->currency_id = $invoiceData->currency_id;
//        $invoice->status = $invoiceData->status;
//        $invoice->note = $invoiceData->note;
//        $invoice->show_shipping_address = $invoiceData->show_shipping_address;
//        $invoice->save();
//
//        foreach ($invoiceData->items as $key => $item) :
//            InvoiceItems::create(
//                [
//                    'invoice_id' => $invoice->id,
//                    'item_name' => $item->item_name,
//                    'item_summary' => $item->item_summary,
//                    'type' => 'item',
//                    'quantity' => $item->quantity,
//                    'unit_price' => $item->unit_price,
//                    'amount' => $item->amount,
//                    'taxes' => $item->taxes
//                ]
//            );
//        endforeach;
//
//        //log search
//        $this->logSearchEntry($invoice->id, 'Invoice ' . $invoice->invoice_number, 'admin.all-invoices.show', 'invoice');
//
//    }
}
