<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\AccountTypeImport;
use App\Rules\AccountTypeFormatRule;
use App\Rules\AccountChartsOfAccountRule;
use App\Imports\ChartsOfAccountImport;
use App\Traits\MultiProjectCookie;
use App\Rules\TrialBalanceFormatRule;
use App\Imports\TrialBalanceImport;
use App\GeneralJournalEntry;
use App\Voucher;
use App\Rules\CustomerFormatRule;
use App\Imports\CustomersImport;
use App\Imports\GeneralVoucherImport;
use App\Rules\GeneralVoucherFormatRule;
class ImportLegacyDataController extends Controller
{
    //

    use MultiProjectCookie;
    public function importDataType(){
       
        return view('Setting.importdata.index');
    }
    public function importAccountType(){

        return view('Setting.importdata.accounttype');
    }
    public function submitImportAccountType(Request $request){
        $request->validate([
            'file_type'  =>
             ['required', 'mimes:xls,xlsx,csv', new AccountTypeFormatRule],     
        ]);
        $file = $request->file('file_type');
        Excel::import(new AccountTypeImport, $file);
        return redirect()->back()
        ->with([
            'message' => 'File imported successfully.!',
            'alert-type' => 'success',
                ]);  
    } 

    public function downloadAccountTypeFormate(){
        $filename =  'accounttypeformat.xlsx';
        $path = 'accounts/' . 'accounttypeformat.xlsx';

        return response()->download(storage_path('app/' . $path), $filename, [
            'Content-Type' => 'application/vnd.ms-excel',
        ]);
    }
    public function downloadChartsOfAccountFormate(){
       
        $filename =  'chartsofaccount.xlsx';
        $path = 'accounts/' . 'chartsofaccount.xlsx';

        return response()->download(storage_path('app/' . $path), $filename, [
            'Content-Type' => 'application/vnd.ms-excel',
        ]);
    }
    public function importChartOfAccount(){
        return view('Setting.importdata.chartofaccount');
    }
    public function submitImportChartOfAccount(Request $request){
        $request->validate([
            'file_type'  =>
             ['required', 'mimes:xls,xlsx,csv', new AccountChartsOfAccountRule],     
        ]);
       
        $file = $request->file('file_type');
        Excel::import(new ChartsOfAccountImport, $file);
        return redirect()->back()
        ->with([
            'message' => 'File imported successfully.!',
            'alert-type' => 'success',
                ]);  
    } 

    public function importTrialBalance(){

        $data=   $this->getCookieInfoAndMultiPro();
        return view('Setting.importdata.trialbalance',$data);   
    }

    public function downloadTrialBalanceFormat(){
        $filename =  'trialbalanceformat.xlsx';
        $path = 'accounts/' . 'trialbalanceformat.xlsx';

        return response()->download(storage_path('app/' . $path), $filename, [
            'Content-Type' => 'application/vnd.ms-excel',
        ]);
    }

    public function storeTrialBalance(Request $request){

        $request->validate([
            'multipro_id' => 'required',
            'date' => 'required',
            'file_type'  =>
             ['required', 'mimes:xls,xlsx,csv', new TrialBalanceFormatRule],     
        ]);

        $month = date('m' , strtotime($request->date));
        $year = date('Y' , strtotime($request->date));


    $voucherNo = GeneralJournalEntry::where([['voucher_type',GeneralJournalEntry::JV]])->groupBy('entry_no')->get();
   

    if(count($voucherNo) > 0 )
    {
        $voucherNo = json_decode($voucherNo);
        $voucher_no = array();
        foreach ($voucherNo as $key => $row)
        {
            if(  (date('m' , strtotime($row->date)) == $month) &&  (date('Y' ,strtotime($row->date)) == $year)  )
            {
                // $voucher_number = explode('-' , $row->voucher_no);
                $voucher_no[$key] = $row->voucher_no;
            }
        }

        
        if(count($voucher_no) > 0 )
        {
            $voucher_nobrs = array_intersect($voucher_no , array_column($voucherNo , 'voucher_no'));
            $voucher_nobrs =array_values($voucher_nobrs);
            
            usort($voucher_nobrs, function ($item1, $item2) {
            $item1 = explode('-' , $item1);
            $item2 = explode('-' , $item2);
            
            if($item1[0]==$item2[0]) return 0;
            return $item1[0] < $item2[0]?1:-1;
            
            });
            
            $break_voucher_no = explode('-' , $voucher_nobrs[0]);
            
            $voucherNo = $break_voucher_no[0] + 1;
        }
        else
        {
            $voucherNo =  1;
        }

        
    }
    else
    {
        $voucherNo =  1;
    }
  
    
    if($voucherNo < 10)
    {
        $voucherNo = '0'.$voucherNo;
    }

    $voucherNo = $voucherNo.'-' . $month . $year;
       
        $file = $request->file('file_type');
        $last_entry = GeneralJournalEntry::orderBy('entry_no','DESC')->first();

        if ($last_entry)
            $latest_entry_no = ++$last_entry->entry_no;
        else
            $latest_entry_no = 1;
            Voucher::create(['entry_no'=>$latest_entry_no]);
       $multipro_id=    decrypt($request->multipro_id);
        Excel::import(new TrialBalanceImport($request->date,$multipro_id,$latest_entry_no,$voucherNo), $file);
        return redirect()->back()
        ->with([
            'message' => 'File imported successfully.!',
            'alert-type' => 'success',
                ]);  
    }

    public function customerImport(){
        return view('Setting.importdata.customerimport');  
    }
    public function downloadCustomerFormat(){
        $filename =  'customerformate.xlsx';
        $path = 'customer/' . 'customerformate.xlsx';

        return response()->download(storage_path('app/' . $path), $filename, [
            'Content-Type' => 'application/vnd.ms-excel',
        ]);
    }

    public function storeCustomerimport(Request $request){     
        $request->validate([ 
            'file_type'  =>
             ['required', 'mimes:xls,xlsx,csv', new CustomerFormatRule],     
        ]);

        $file = $request->file('file_type');
       
        Excel::import(new CustomersImport, $file);
        return redirect()->back()
        ->with([
            'message' => 'File imported successfully.!',
            'alert-type' => 'success',
                ]);  

    }
    public function importGeneralVouchers(){

        $data=   $this->getCookieInfoAndMultiPro();
        return view('Setting.importdata.voucherImport',$data);
    }
    public function downloadGeneralVoucherFormate(){
        $filename =  'generalvoucherformat.xlsx';
        $path = 'accounts/' . 'generalvoucherformat.xlsx';

        return response()->download(storage_path('app/' . $path), $filename, [
            'Content-Type' => 'application/vnd.ms-excel',
        ]);
    }
 
    public function storeGeneralVoucher(Request $request){
        $request->validate([
            'multipro_id' => 'required',
            'file_type'  =>
             ['required', 'mimes:xls,xlsx,csv', new GeneralVoucherFormatRule],     
        ]);
       $multipro_id=    decrypt($request->multipro_id);
       $file = $request->file('file_type');
       Excel::import(new GeneralVoucherImport($multipro_id), $file);      
        return redirect()->back()
        ->with([
            'message' => 'File imported successfully.!',
            'alert-type' => 'success',
                ]);  
    }
}
