<?php

namespace App\Http\Controllers\Accounts\Accounts\Expenses;

use App\Traits\Uploads;
use Date;
use Illuminate\Http\Request;
use App\Utilities\ImportFile;
use App\Http\Controllers\Controller;
use App\Models\Accounts\Income\Terms;
use App\Models\Accounts\Expense\Vendor;
use Illuminate\Support\Facades\Session;
use App\Models\Accounts\Setting\Currency;

class Vendors extends Controller
{
    use Uploads;

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $vendors = Vendor::get();

        return view('accounts.expenses.vendors.index', compact('vendors'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
           $terms = Terms::pluck('name','id');

        return view('accounts.expenses.vendors.create', compact('terms'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     *
     * @return Response
     */
    public function store(Request $request)
    {
        if (empty($request['vendor_email'])) {
            $request['vendor_email'] = '';
        }

        if($request->same_as_billing){
            $request['shipping_address'] = $request->address;
            $request['same_as_billing'] = '1';
        }

        $request['company_id'] = session('company_id');
        $request['currency_code'] = 'USD';

        $vendor = Vendor::create($request->all());

        // Upload logo
        if ($request->file('logo')) {
            $media = $this->getMedia($request->file('logo'), 'vendors');

            $vendor->attachMedia($media, 'logo');
        }

        $message = trans('messages.success.added', ['type' => trans_choice('general.vendors', 1)]);

        Session::flash('success',$message);

        return redirect('expenses/vendors');
    }
    /**
     * Import the specified resource.
     *
     * @param  ImportFile  $import
     *
     * @return Response
     */
    public function import(ImportFile $import)
    {
        $rows = $import->all();

        foreach ($rows as $row) {
            $data = $row->toArray();

            $data['company_id']         = session('company_id');
            $data['enabled']            = ($row['active_status'] == 'Active') ?'1':'0';
            $data['currency_code']      = 'USD';
            $data['name']               = $row['vendor'] . $row['first_name'] . $row['m.i.'] . $row['last_name'];
            $data['address']            = $row['bill_from_1'].$row['bill_from_2']. $row['bill_from_3']. $row['bill_from_4']. $row['bill_from_5'];
            $data['shipping_address']   =  $row['ship_from_1'].$row['ship_from_2'].$row['ship_from_3'].$row['ship_from_4'].$row['ship_from_5'];
            $data['phone']              =  $row['main_phone'];
            $data['mobile']              =  $row['alt._phone'];

            if (empty($data['vendor_email'])) {
                $data['vendor_email'] = '';
            }
            
            Vendor::create($data);
        }

        $message = trans('messages.success.imported', ['type' => trans_choice('general.vendors', 2)]);

        Session::flash('success',$message);

        return redirect('expenses/vendors');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  Vendor  $vendor
     *
     * @return Response
     */
    public function edit(Vendor $vendor)
    {
        $currencies = Currency::whereEnabled(1)->pluck('name', 'code');

        $terms = Terms::pluck('name','id');

        return view('accounts.expenses.vendors.edit', compact('vendor', 'currencies','terms'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Vendor  $vendor
     * @param  Request  $request
     *
     * @return Response
     */
    public function update(Vendor $vendor, Request $request)
    {
        if (empty($request['vendor_email'])) {
            $request['vendor_email'] = '';
        }

        if($request->same_as_billing){
            $request['shipping_address'] = $request->address;
            $request['same_as_billing'] = '1';
        }else{
              $request['same_as_billing'] = '0';
        }   

        $vendor->update($request->all());

        // Upload logo
        if ($request->file('logo')) {
            $media = $this->getMedia($request->file('logo'), 'vendors');

            $vendor->attachMedia($media, 'logo');
        }

        $message = trans('messages.success.updated', ['type' => trans_choice('general.vendors', 1)]);

        Session::flash('success',$message);

        return redirect('expenses/vendors');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  Vendor  $vendor
     *
     * @return Response
     */
    public function destroy(Vendor $vendor)
    {
        $relationships = $this->countRelationships($vendor, [
            'bills' => 'bills',
            'payments' => 'payments',
        ]);

        if (empty($relationships)) {
            $vendor->delete();

            $message = trans('messages.success.deleted', ['type' => trans_choice('general.vendors', 1)]);

            Session::flash('success',$message);
        } else {
            $message = trans('messages.warning.deleted', ['name' => $vendor->name, 'text' => implode(', ', $relationships)]);

            Session::flash('warning',$message);
        }

        return redirect('expenses/vendors');
    }

    public function currency()
    {
        $vendor_id = request('vendor_id');

        $vendor = Vendor::find($vendor_id);

        return response()->json($vendor);
    }

    public function vendor(Request $request)
    {
        if (empty($request['vendor_email'])) {
            $request['vendor_email'] = '';
        }

        $request['currency_code'] = 'USD';
        $vendor = Vendor::create($request->all());

        return response()->json($vendor);
    }

    public function show($id){

         $vendor = Vendor::find($id);
       
      return response()->json($vendor);
    }

    public function autocompletevendor()
    {
        $vendor_id = request('vendor_id');

        $vendor = Vendor::with(['terms'])->find($vendor_id);
       
        return response()->json($vendor);
    }

    public function billcenter()
    {
        $date = Date::today()->format('Y-m-d');
        $tenth = strtotime("+10 day");
        $tenthday = date('Y-m-d',$tenth);


        $vendors = Vendor::with(['bills' => function($query) use ($date) {
                $query->whereDate('bills.due_at', '<=', $date); 
                $query->where('bills.bill_status_code', '!=', 'paid'); 
        }])->get();
        
        $vendors_almostdue = Vendor::with(['bills' => function($q) use($date , $tenthday) {
            $q->whereDate('bills.due_at', '>=', $date);
            $q->whereDate('bills.due_at', '<=', $tenthday);
            $q->where('bills.bill_status_code', '!=', 'paid');   
        }])->get();


       return view('accounts.expenses.vendors.billcenter',compact('vendors','vendors_almostdue'));     
    }
}
