<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\DataImport;
use Yajra\Datatables\Datatables;

class DataController extends Controller
{
    public function index()
    {


        return view('home');
    }

    public function import()
    {
        return view('import');
    }

    public function dirtyData()
    {
        return view('dirty');
    }

    public function toimport(Request $request)
    {
        if (!$request->all()) {
            return redirect('data-import');
        }
        $import = new DataImport($request->sname);
        $data = Excel::import($import, $request->file('importfile'));
        $row = $import->getRowCount();

        return redirect('data-dirty')->with('row', $row);
    }

    public function dataCleaning()
    {
        DB::select(DB::raw("

            update data SET phone = SUBSTR(phone,4,LENGTH(phone)) where  SUBSTRING(phone, 1, 3) = '959' ;

        "));

        DB::select(DB::raw("

            update data SET phone = SUBSTR(phone,3,LENGTH(phone))  where  SUBSTRING(phone, 1, 2) = '95' and length(phone)=11 ;

        "));

        DB::select(DB::raw("

            update data SET phone = SUBSTR(phone,2,LENGTH(phone))  where  SUBSTRING(phone, 1, 1) = '9' and length(phone)=10 ;
            
        "));
    }

    public function getDirtyData()
    {
        $data = DB::table('data')->get();
        return DataTables::of($data)->make(true);
    }
}
