<?php
namespace App\Http\Controllers\Project;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Models\Project\Products;
use App\Models\Project\Categories;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Response;
use Session;
use DataTables;

use Spatie\Activitylog\Models\Activity;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ProductsImport;

class ProductController extends Controller
{
  var $url;
  public function __construct()
  {
      $this->middleware('auth');
      $this->url = request()->path();
  }

  public function index(Request $request)
  {
    if ($request->ajax()) :
      $record = Products::select('*')->where('vendor_id', Auth::id())->where('status', '!=', -1)->orderBy('id', 'desc');
      return DataTables::of($record)
      ->setRowId(function ($row) {
          return $row->id;
      })
      ->addColumn('status',function ($row) {
          $checked = "";
            if ($row->status == 1) { $checked = "checked"; }
            $swtich = '
            <div class="ps-5 text-center">
                <label class="switch">
                    <input class="" type="checkbox" id="togBtn" onClick="state_switch('.$row->id.')" '.$checked.'>
                    <div class="slider round">
                        <span class="on">ON</span>
                        <span class="off">OFF</span>
                    </div>
                </label>
            </div>
            ';
            return $swtich;
      })
      ->addColumn('actions',function($row){
          $btn =  '
              <span class="px-2">
                  <a class="text-decoration-none px-1" href="'.url('/manage_product/edit/'.$row->id).'">
                      <span class="edit_icon">
                          <i class="bi bi-pen"></i>
                      </span>
                      <span class="px-1 e-text">Edit</span>
                  </a>
              </span>
              <span>
                  <a class="text-decoration-none px-1" onClick="destroy('.$row->id.')">
                      <span class="delete_icon fw-bold"><i class="bi bi-backspace"></i></span>
                      <span class="px-1 tcancel e-text">Delete</span>
                  </a>
              </span>
          ';
          return $btn;
      })
      ->filter(function ($record) use ($request) {
        $input="";
        if ($request->has('search_new') && $request->search_new != "") {
            $input=$request->get("search_new");
            $record->where('name_en', 'like', '%' . $input . '%');
        }
        
        if ($request->has('status_filter') && $request->status_filter != "") {
            $record->where('status', '=', $request->get('status_filter'));
        }
      })
      ->rawColumns(['status','actions'])
      ->make(true);
    endif;
    activity('Product Page Browsed')
      ->causedBy(Auth::user())
        ->performedOn(new Products())
        // ->withProperties(['old'  => [], 'modified'=>$data])
        ->tap(function (Activity $activity) {
            $activity->route_link = $this->url;
        })
        ->log('Product Page visited by ' . Auth::user()->name);
      return view('sarf/pos/manage_products.index');
  }

  public function add()
  {
    $category_list = Categories::where('vendor_id',Auth::id())->where('status',1)->get();
    return view('sarf/pos/manage_products.add', compact('category_list'));
  }

  public function save(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'name' => 'required|max:255',
      'price' => 'required',
      'barcode' => 'required|max:255',
      'category_id' => 'required',
    ]);
  
    if ($validator->fails()) {
        return redirect()->back()->withErrors($validator)->withInput();
    } else {
      if(isset($request->status)){ $status = '1'; }else{ $status = '0'; }
      $data = [
          'name' => $request->name,
          'price' => $request->price,
          'barcode' => $request->barcode,
          'category_id' => $request->category_id,
          'vendor_id' => Auth::id(),
          'status' => $status,
          'updated_at' => Date('Y-m-d H:m:i'),
      ];
      $post = Products::insert($data);
      activity('Product Added')
        ->causedBy(Auth::user())
          ->performedOn(new Products())
          // ->withProperties(['old'  => [], 'modified'=>$data])
          ->tap(function (Activity $activity) {
              $activity->route_link = $this->url;
          })
          ->log('Product Added by ' . Auth::user()->name);           
      if ($post) {
          return redirect()->back()->with('success','Added successfuly')->withInput();
      } else {
          return redirect()->back()->with('error','Somthing went wrong')->withInput();
      }
    }
  }

  function edit($id)
  {
    $category_list = Categories::where('vendor_id',Auth::id())->where('status',1)->get();
    $post = Products::find($id);
    return view('sarf/pos/manage_products.edit', compact('post','category_list'));
  }

  function update(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'name' => 'required|max:255',
      'price' => 'required',
      'barcode' => 'required|max:255',
      'category_id' => 'required',
    ]);
    
    if ($validator->fails()) {
        return redirect()->back()->withErrors($validator)->withInput();
    } else {
      if(isset($request->status)){ $status = '1'; }else{ $status = '0'; }
      $data = [
        'name' => $request->name,
        'price' => $request->price,
        'barcode' => $request->barcode,
        'category_id' => $request->category_id,
        'status' => $status,
        'updated_at' => Date('Y-m-d H:m:i'),
      ];
      $old = Products::where('id', $request->id)->first();
      $post = Products::where('id', $request->id)->update($data);
      activity('Product updated')
      ->causedBy(Auth::user())
        ->performedOn(new Products())
        ->withProperties(['old'  => $old, 'modified' => $data])
        ->tap(function (Activity $activity) {
            $activity->route_link = $this->url;
        })
        ->log('Product updated by ' . Auth::user()->name);
      if ($post) {
          return redirect()->back()->with('success','Updated successfuly')->withInput();
      } else {
          return redirect()->back()->with('error','Somthing went wrong')->withInput();
      }
    }
  }

  function status(Request $request)
  {
    $state = getAny("status", "products", "id", $request->id);
    if ($state == 1) {
        $update_state = 0;
    }else{
        $update_state = 1;
    }
    $post = Products::find($request->id);
    $post->status = $update_state;
    $msg = $post->save();
    if ($msg) {
      echo  json_encode(array('text' => 'Modified', 'cls' => 'success'));
    } else {
      echo  json_encode(array('text' => 'Error', 'cls' => 'error'));
    }
  }

  function destroy(Request $request)
  {
    $post = Products::find($request->id);
    $post->status = '-1';
    $msg = $post->save();
    if ($msg) {
    echo  json_encode(array('text' => 'Delete successfully', 'cls' => 'warning'));
    } else {
    echo  json_encode(array('text' => 'Error', 'cls' => 'error'));
    }
  }

  public function import(Request $request) 
  {
    $this->validate($request, [
      'file' => 'required|file|mimes:xls,xlsx'
    ]);
    $file = $request->file('file');
    //ddd($file);
    $excel = Excel::import(new ProductsImport, $file);
    if ($excel) {
      return redirect()->back()->with('success', 'All data successfully imported!');
    } else {
      return redirect()->back()->with('error', 'not imported!');
    }
  }
}
