<?php

namespace App\Http\Controllers;

use App\Models\BillingService;
use DateTime;

class ParseBillingServicesController extends Controller
{
    /**
     *  Parse csv to Array and save in DB
     */
    public function parse()
    {
        $file = fopen(storage_path() . '/app/public/billing_services.csv', 'r');
        $count = 0;
        while (($line = fgetcsv($file)) !== FALSE) {
            if ($line[0] != 'Service Ref') {
                $count++;
                echo "<pre>";
                print_r($line);
                echo "</pre>";
                $service = new BillingService;
                $service->service_ref = $line[0];
                $setup_date = DateTime::createFromFormat('d/m/Y', $line[2]);
                //echo $setup_date->format('Y-m-d');
                if ($setup_date)
                    $service->setup_date = $setup_date->format('Y-m-d');

                $last_billed = DateTime::createFromFormat('d/m/Y', $line[3]);
                if ($last_billed)
                    $service->last_billed = $last_billed->format('Y-m-d');

                $next_billed = DateTime::createFromFormat('d/m/Y', $line[4]);
                if ($next_billed)
                    $service->next_billed = $next_billed->format('Y-m-d');

                $service->description = $line[5];
                $service->do_not_bill = $line[6];
                $service->fee = $line[7];
                $service->renew = $line[8];
                $service->agreement = $line[9];
                $service->notes = $line[10];
                $service->username = $line[11];
                $service->password = $line[12];

                $service->save();
            }
        }
        fclose($file);
    }
}
