<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\ControlAccount;
use App\GeneralJournalEntry;
use Carbon\Carbon;
use App\ChartOfAccount;
use App\MultiProject;
use App\VendorCertificate;
use Illuminate\Support\Facades\Auth;
use App\Traits\MultiProjectCookie;

class ControlAccountController extends Controller {

    use MultiProjectCookie;
    //show the add new Control Account  form
    public function addControlAccountForm($type) {

        $data['type'] = $type;

        return view('account/control.add-account',$data);
    }

    //insert new Account Class record
    public function insertControlAccount(Request $request) {

        $validator = Validator::make($request->all(), [
                    'name' => 'required',
                    'type' => 'required',
                    'cnic' => 'required',
        ]);

        if ($validator->fails()) {
             return redirect('/control-account/add/'.$request->type)
                            ->withErrors($validator)
                            ->withInput()
                            ->with([
                                'message' => 'Invalid Inputs!',
                                'alert-type' => 'error',
            ]);
        }

        //create new Account Class
        //$account = ControlAccount::create(Input::all());
        $input=$request->all();
        $account = ControlAccount::create($input);

        if ($request->hasfile('file')) {
            $file = $request->file('file');

            $name = $account->id . '-' . $file->getClientOriginalName();
            $file->move(public_path() . '/uploads/', $name);

            ControlAccount::where('id',$account->id)->update(['file' => $name, 'updated_at' => date('Y-m-d H:i:s')]);
        }

        return redirect()->route('control-account.detail',['id'=>$account->id])
                        
                        ->with([
                            'message' => 'ControlAccount created successfully!',
                            'alert-type' => 'info'
        ]);
    }

    

    //show the edit AccountClass form
    public function editControlAccountForm($id) {

        $data['account'] = ControlAccount::where('id', $id)->first();

        return view('account/control.edit-account', $data);
    }

    //update the Account Class
    public function updateControlAccount(Request $request) {


        $validator = Validator::make($request->all(), [
                     'name' => 'required',
                    'type' => 'required',
                    'cnic' => 'required',
                    
        ]);

        if ($validator->fails()) {
            return redirect('/control-account/edit/' . $request->id)
                            ->withErrors($validator)
                            ->withInput()
                            ->with([
                                'message' => 'Invalid Inputs!',
                                'alert-type' => 'error',
            ]);
        }

        //update Account Class
        ControlAccount::where('id',$request->id)->update($request->except('_token','file'));

        if ($request->hasfile('file')) {
            $file = $request->file('file');

            $name = $request->id . '-' . $file->getClientOriginalName();
            $file->move(public_path() . '/uploads/', $name);

            ControlAccount::where('id',$request->id)->update(['file' => $name, 'updated_at' => date('Y-m-d H:i:s')]);
        }

        return redirect()->route('control-account.detail',['id'=>$request->id])
                        
                        ->with([
                            'message' => 'Control Account updated successfully!',
                            'alert-type' => 'info'
        ]);
    }
    
    public  function getCookieInfomation(){
        $data = array();
        
        $request = app(Request::class);
        $project_id = request()->cookie('current_project_id');
        $user = Auth::user();
        if (!empty($project_id)) {
            $p_id = decrypt($project_id);
            $multi = MultiProject::where('id', $p_id)->first();
            $multiProjectId = $multi->id;
            if ($multi->name == "Super Admin") {
                $roles = $user
                    ->roles()
                    ->where('name', 'like', 'admin')
                    ->whereHas('projects', function ($query) use ($multiProjectId) {
                        $query->where('multi_project_id', $multiProjectId);
                    })
                    ->first();
                if (!empty($roles)) {
                    $data['multi_projects']  = MultiProject::where('name', 'NOT like', 'Super Admin')->get()->pluck('id')->toArray() // Flatten the collection of IDs into a single array
                    ;
                    return   $data;
                } 
                else {
                    // $request = app(Request::class);
           
                $permission=decrypt($request->permission);
                // dd($permission);
                
                $project_ids=       $user->roles()
                // ->where('name', 'NOT like', 'admin')
               ->whereHas('projects', function ($query)   {
               $query->where('name', 'NOT like', 'Super Admin');
               })
               ->get()
               ->filter(function ($r) use ($permission) {
               return $r->hasPermission($permission);
               })
               ->pluck('projects.*.id') // Pluck the 'id' column from the remaining 'projects' models
               ->flatten() // Flatten the collection of IDs into a single array
               ->unique()
               ->toArray()
               ;
            //    dd( $project_ids);
               if(sizeof($project_ids) == 0)
               {
                   $data['status'] = 'error';
                   return  $data; 
               }
                     
                    $data['multi_projects'] = MultiProject::whereIn('id',  $project_ids)->where('name', 'NOT like', 'Super Admin')->get();
                    $data['project'] = $multi->name;
                    $data['role'] = 'other';
                    $data['project_ids'] =  $project_ids;
                    if(isset( $data['multipro_id'])){
                        if($data['multipro_id'] != 'all'){
                        $data['project_ids'] = $data['multipro_id'];
                        }
                     
                    }
                    $data['status'] = 'success';
                    return $data;
                }
            }
            else{
                $roles = $user
                    ->roles()
                    
                    ->whereHas('projects', function ($query) use ($multiProjectId) {
                        $query->where('multi_project_id', $multiProjectId);
                    })
                    ->first(); 
    
                    if (!empty($roles)) {
                        $data['multi_projects']  = $multi->id;
                        
                        return   $data;
                        
    
                    }
            }
        }
    }
    public function detailControlAccount($id) {

        $project_ids=   $this->getCookieInfomation();
       
        $ids=[];
        if(is_array($project_ids['multi_projects'])){
            $ids= $project_ids['multi_projects']; 
        }
        else
        $ids[]= $project_ids['multi_projects'];


        $from = date(date('Y') . '-' . ChartOfAccount::FISCAL_YEAR_START . '-01');
        $to  = date((date('Y') + 1) . '-' . ChartOfAccount::FISCAL_YEAR_END . '-30');

        $data['openingBalance'] = GeneralJournalEntry::where('date','<',$from)->where([['is_post',true],['name',$id]])
        ->whereIn('multi_project_id', $ids)
        ->sum('amount');

        $data['accountEntries'] = ControlAccount::where('id',$id)->whereHas('entry',function($query) use($from,$to,$ids) {
            $query->whereBetween('date',[$from,$to])->whereIn('multi_project_id', $ids);
        })->first();

        $data['account'] = ControlAccount::where('id',$id)->first();

        $data['from'] = $from;
        $data['to'] = $to;

        

        return view('general-entry.control-account-detail',$data);
    }
    
    public function getCertificateDetail(Request $request)
    {
        $account = ControlAccount::where('id',$request->vender_id)->first();
        if($account == true)
        {
            echo json_encode(array('response' => 'yes' , 'output' => $account));
        }
        else
        {
             echo json_encode(array('response' => 'no' , 'output' => []));
        }
    }
    
    public function updateDetailControlAccount(Request $request) {
        $project_ids=   $this->getCookieInfomation();
       
        $ids=[];
        if(is_array($project_ids['multi_projects'])){
            $ids= $project_ids['multi_projects']; 
        }
        else
        $ids[]= $project_ids['multi_projects'];

        
        $date = explode('-',$request->date_range);
        $from = Carbon::parse($date[0])->startOfDay();
        $to = Carbon::parse($date[1])->endOfDay();

        $data['openingBalance'] = GeneralJournalEntry::where('date','<',$from)->
        where([['is_post',true],['name',$request->account_id]])
        ->whereIn('multi_project_id', $ids)
        ->sum('amount');

        $data['accountEntries'] = ControlAccount::where('id',$request->account_id)->whereHas('entry',function($query) use($from,$to,$ids) {
            $query->whereBetween('date',[$from,$to])->whereIn('multi_project_id', $ids);
        })->first();

        $data['account'] = ControlAccount::where('id',$request->account_id)->first();

        $data['from'] = $from;
        $data['to'] = $to;

        return view('general-entry.update-control-account-detail',$data);
    }



public function insertVendorCertificate(Request $request) {

        //create new Account Class
        //$account = VendorCertificate::create(Input::all());
        $input=$request->all();
        $account = VendorCertificate::create($input);

        return redirect()->back()->with([
                            'message' => 'Certificate created successfully!',
                            'alert-type' => 'info'
        ]);
    }
    
    function getVendorCertificateDetail($id=null)
    {
        $data['vendor_certificate'] = VendorCertificate::where('id',$id)->first();
        
        $digit = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);

        $data['total_tax'] = $digit->format($data['vendor_certificate']->total_tax_amount);

        $data['total_amount'] = $digit->format($data['vendor_certificate']->total_amount);
        
        return view('general-entry.vendor-certificate-detail',$data);
    }
    
    
   

}
