<?php

namespace App\Http\Controllers;


use App\Models\AmazonAbuseReport;
use Illuminate\Http\Request;
use Input;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Redirect;
use Validator;
use Yajny\Member\Models\UserSales;


class DataManangeCtrl extends Controller
{
    //

    protected $layout = "";
    protected $data = array();
    protected $model = null;
    protected $modelview = null;
    public $module = '';
    public static $page  = 1;
    public static $per_page = '20';

    public function __construct()
    {
        parent::__construct();

        $this->info = $this->model->makeInfo($this->module);

        static::$per_page = $this->info['setting']['perpage'];


        $this->data = array(
            'pageTitle' => $this->info['title'],
            'pageNote' => $this->info['note'],
            'pageModule' => $this->module,
            'frontendSlug' => $this->info['frontend_slug'],
            'return' => self::returnUrl()

        );

        if ($this->modelview)
            $this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'][0] : array());
    }

     public function getPage(){
        return $this->page;
     }

    public function setPage($page){
        return $this->page=$page;
    }

    public function index(Request $request)
    {
        // Make Sure users Logged
        if (!\Auth::check())
            return redirect('/')->with('status', 'error')->with('message', 'You are not logged in');
        $this->grab($request);
        if ($this->access['is_view'] == 0 && $this->access['is_search'] == 0)
            return redirect('dashboard')->with('message', __('core.note_restric'))->with('status', 'error');
        // Render into template
        return view('manage.' . $this->module . '.index', $this->data);
    }

    public function create(Request $request, $id = 0)
    {

        $this->hook($request);
        if ($this->access['is_add'] == 0)
            return redirect('dashboard')->with('message', __('core.note_restric'))->with('status', 'error');


        if ($request->input('old'))
            $this->data['row'] = session()->getOldInput();
        else
            $this->data['row'] = $this->model->getColumnTable($this->info['table']);

        if ($this->modelview) {
            $relation_key = $this->modelview->makeInfo($this->info['config']['subform']['module']);
            $this->data['accesschild'] = $this->modelview->validAccess($relation_key['id'], session('gid'));
            $this->data['relation_key'] = $relation_key['key'];
            $this->data['detail_rel'] = $this->info['config']['subform'];
            $this->data['subform'] = $this->detailview($this->modelview, $this->info['config']['subform'], $id);
        }

        $this->data['id'] = '';
        return view('manage.' . $this->module . '.form', $this->data);
    }

    function edit(Request $request, $id)
    {
        $this->hook($request, $id);
        if (!isset($this->data['row']))
            return redirect('/manage/' . $this->module)->with('message', 'Record Not Found !')->with('status', 'error');
        if ($this->access['is_edit'] == 0)
            return redirect('dashboard')->with('message', __('core.note_restric'))->with('status', 'error');
        $this->data['row'] = (array)$this->data['row'];

        if ($this->modelview) {

            $relation_key = $this->modelview->makeInfo($this->info['config']['subform']['module']);

            $this->data['accesschild'] = $this->modelview->validAccess($relation_key['id'], session('gid'));
            $this->data['relation_key'] = $relation_key['key'];
            $this->data['detail_rel'] = $this->info['config']['subform'];
            $this->data['subform'] = $this->detailview($this->modelview, $this->info['config']['subform'], $id);
        }

        $this->data['id'] = $id;
        return view('manage.' . $this->module . '.form', $this->data);
    }


    function show(Request $request, $id)
    {
        /* Handle import , export and view */
        $task = $id;
        switch ($task) {
            case 'data':
                $this->grab($request);
                return view('manage.' . $this->module . '.index', $this->data);
                break;
            case 'search':
                return $this->getSearch();
                break;
            case 'lookup':
                return $this->getLookup($request);
                break;
            case 'ajaxselect':
                return $this->getAjaxselect($request);
                break;
            case 'comboselect':
                return $this->getComboselect($request);
                break;
            case 'import':
                return $this->getImport($request);
                break;
            case 'export':
                return $this->getExport($request);
                break;
            case 'export_b':
                return $this->getExportB($request);
                break;
            default:
                $this->hook($request, $id);
                if (!isset($this->data['row']))
                    return redirect('/manage/' . $this->module)->with('message', 'Record Not Found !')->with('status', 'error');

                if ($this->access['is_detail'] == 0)
                    return redirect('dashboard')->with('message', __('core.note_restric'))->with('status', 'error');

                return view('manage.' . $this->module . '.view', $this->data);
                break;
        }
    }


    function store(Request $request)
    {
        if ($this->module=='amazonabusereports'){
            if ($request->hasFile('file')) {
                // Get file
                $file = $request->file('file');
                $filename = $file->getClientOriginalName();
                // Load the Excel file
                $spreadsheet = IOFactory::load($file);

                // Get the second sheet (index starts from 0)
                $sheet = $spreadsheet->getSheet(1);

                // Get the highest row number
                $highestRow = $sheet->getHighestRow();

                // Initialize an array to store data from the third column
                $columnData = [];

                // Loop through each row of the worksheet
                for ($row = 2; $row <= $highestRow; $row++) {
                    // Get value from the third column (C)
                    $cellValue = $sheet->getCellByColumnAndRow(3, $row)->getValue();

                    // Add the cell value to the column data array
                    $columnData[] = $cellValue;
                }
                // Return the Excel data
                for ($i=0;$i<count($columnData);$i++){
                     $ordersList=UserSales::whereIn('click_id',$columnData)->get();
                     if ($ordersList){
                         foreach ($ordersList as $order){
                             $order->status='declined';
                             $order->save();
                         }
                     }
                     $report = new AmazonAbuseReport();
                     $report->report_name =$filename;
                     $report->save();
                    return redirect('/manage/amazonabuse');
                }
            }
        }else{
        $task = $request->input('action_task');
        switch ($task) {
            default:

                $rules = $this->validateForm();
                $validator = Validator::make($request->all(), $rules);
                if ($validator->passes()) {
                    $data = $this->validatePost($request);


                    $id = $this->model->insertRow($data, $request->input($this->info['key']));

                    if ($this->modelview)
                        $this->detailviewsave($this->modelview, $request->all(), $this->info['config']['subform'], $id);

                    /* Insert logs */
                    $this->model->logs($request, $id);
                    if (!is_null($request->input('apply')))
                        return redirect('/manage/' . $this->module . '/' . $id . '/edit?' . $this->returnUrl())->with('message', __('core.note_success'))->with('status', 'success');

                    return redirect('/manage/' . $this->module . '?' . $this->returnUrl())->with('message', __('core.note_success'))->with('status', 'success');
                } else {
                    if ($request->input($this->info['key']) != null)
                        return redirect('/manage/' . $this->module . '/' . $request->input($this->info['key']) . '/edit')
                            ->with('message', __('core.note_error'))->with('status', 'error')
                            ->withErrors($validator)->withInput();
                    else
                        return redirect('/manage/' . $this->module . '/create/' . '?old=true&return=')->withInput()->with('message', __('core.note_error'))->with('status', 'error')
                            ->withErrors($validator)->withInput();
                }
                break;
            case 'public':
                return $this->store_public($request);
                break;

            case 'delete':
                $result = $this->destroy($request);
                return redirect('/manage/' . $this->module . '?' . $this->returnUrl())->with($result);
                break;

            case 'import':
                return $this->PostImport($request);
                break;

            case 'copy':
                $result = $this->copy($request);
                return redirect('/manage/' . $this->module . '?' . $this->returnUrl())->with($result);
                break;
        }
        }
    }

    public function destroy($request)
    {
        // Make Sure users Logged
        if (!\Auth::check())
            return redirect('user/login')->with('status', 'error')->with('message', 'You are not login');

        $this->access = $this->model->validAccess($this->info['id'], session('gid'));
        if ($this->access['is_remove'] == 0)
            return redirect('dashboard')
                ->with('message', __('core.note_restric'))->with('status', 'error');
        // delete multipe rows
        if (is_string($request) && is_int(intval($request))) {
            $this->model->destroy(intval($request));
            return ['message' => __('core.note_success_delete'), 'status' => 'success'];
        } elseif ($request->has('ids') && count($request->input('ids')) >= 1) {
            $this->model->destroy($request->input('ids'));

            // Delete child entries if parent is deleted
            // if($this->modelview)
            // $this->modelview->whereIn('id',$request->input('ids'))->delete();

            \SiteHelpers::auditTrail($request, "ID : " . implode(",", $request->input('ids')) . "  , Has Been Removed Successfull");
            // redirect
            return ['message' => __('core.note_success_delete'), 'status' => 'success'];
        } else {
            return ['message' => __('No Item Deleted'), 'status' => 'error'];
        }
    }
    /*
    public static function display(  )
    {
        $mode  = isset($_GET['view']) ? 'view' : 'default' ;
        $model  = new Vartesttwo();
        $info = $model::makeInfo('vartesttwo');
        $data = array(
            'pageTitle'	=> 	$info['title'],
            'pageNote'	=>  $info['note']
        );
        if($mode == 'view')
        {
            $id = $_GET['view'];
            $row = $model::getRow($id);
            if($row)
            {
                $data['row'] =  $row;
                $data['fields'] 		=  \SiteHelpers::fieldLang($info['config']['grid']);
                $data['id'] = $id;
                return view('vartesttwo.public.view',$data);
            }
        }
        else {

            $page = isset($_GET['page']) ? $_GET['page'] : 1;
            $params = array(
                'page'		=> $page ,
                'limit'		=>  (isset($_GET['rows']) ? filter_var($_GET['rows'],FILTER_VALIDATE_INT) : 10 ) ,
                'sort'		=> $info['key'] ,
                'order'		=> 'asc',
                'params'	=> '',
                'global'	=> 1
            );

            $result = $model::getRows( $params );
            $data['tableGrid'] 	= $info['config']['grid'];
            $data['rowData'] 	= $result['rows'];

            $page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
            $pagination = new Paginator($result['rows'], $result['total'], $params['limit']);
            $pagination->setPath('');
            $data['i']			= ($page * $params['limit'])- $params['limit'];
            $data['pagination'] = $pagination;
            return view('vartesttwo.public.index',$data);
        }

    }
    function store_public( $request)
    {

        $rules = $this->validateForm();
        $validator = Validator::make($request->all(), $rules);
        if ($validator->passes()) {
            $data = $this->validatePost(  $request );
             $this->model->insertRow($data , $request->input('id'));
            return  Redirect::back()->with('message',__('core.note_success'))->with('status','success');
        } else {

            return  Redirect::back()->with('message',__('core.note_error'))->with('status','error')
            ->withErrors($validator)->withInput();

        }

    }
    
    */

}
