<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Customer;
use App\Models\Country;

class CustomersController extends Controller
{
    
    public function __construct() {
        //parent::__construct();
      //$this->middleware('permission:customer');
    }
    
    public function index(){
        return View('Customer.index');
    }

    public function ajaxList(Request $request, Customer $customerObj){
        $limit = (int)$request->iDisplayLength;
        $offset = (int)$request->iDisplayStart;

        $searchContents['freetext'] = (string)$request->sSearch;
        if ($request->iSortCol_0 != '') {
            for ($i = 0; $i < $request->iSortingCols; $i++) {
                $iSortCol_ = 'iSortCol_' . $i;
                $sSortDir_ = 'sSortDir_' . $i;
                $sortcol = $request->$iSortCol_;
                $sort[$sortcol] = $request->$sSortDir_;
            }
        } else {
            $sort = null;
        }

        $customerCount = $customerObj->getAllcustomer($searchContents);
        $customerData = $customerObj->getAllcustomer($searchContents, $sort, $limit, $offset);

        $rows = array();
        $iDisplayStart = $request->iDisplayStart;

        $i=1;
        foreach ($customerData as $key => $content) {

            $action = '<div class="dropdown">
                <a href="javascript:void(0)" role="button" id="dropdownMenuLink1" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="ri-more-2-fill"></i>
                </a>

                <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink1">
                    <li><a class="dropdown-item" href="'.route('customers.edit', ['id' => $content->id]).'">Edit</a></li>
                    <li><a class="dropdown-item customers_remove" href="javascript:void(0)" data-id="' . $content->id . '">Delete</a></li>
                </ul>
            </div>';

            $isActive = '';
            if ($content->status == 'Active') {
                $isActive = '<a href="javascript:void(0)" data-id="' . $content->id . '" class="customers_active tooltipped" data-position="top" title="Active"><i class="ri-checkbox-circle-line align-middle text-success fs-16"></i></a>';
            } else {
                $isActive = '<a href="javascript:void(0)" data-id="' . $content->id . '" class="customers_inactive tooltipped" data-position="top" title="Inactive"><i class="ri-checkbox-circle-line align-middle text-danger fs-16"></i></a>';
            }

            $rowData = array(
                ($limit * $offset/$limit) + $i,
                $content->name,
                $content->countrycode->dialing_code,
                $content->mobile_no,
                $content->civil_cr_no,
                $content->nation->nationality,
                $content->address,
                $isActive,
                date("d-m-Y H:i:s",strtotime($content->created_at)),
                $action
            );
            $rows[] = $rowData;
            $i++;
        }

        $json = array(
            'sEcho' => intval($request->sEcho),
            'iTotalRecords' => $customerCount,
            'iTotalDisplayRecords' => $customerCount,
            'aaData' => $rows
        );

        echo json_encode($json);
    }

    public function add(){
        $country = Country::pluck('nationality','id');
        $code = Country::pluck('dialing_code','id');
        
        return View('Customer.add',compact('country','code'));
    }

    public function store(Request $request){
        $this->validate($request, [
            'name'   => 'required',
            'mobile_country_code' => 'required',
            'mobile_no' => 'required|numeric|digits:10|unique:App\Models\Customer,mobile_no',
            'status' => 'required',

        ]);
        $customerObj = new Customer();
        $customerObj->name = $request->name;
        $customerObj->mobile_country_code = $request->mobile_country_code;
        $customerObj->mobile_no = $request->mobile_no;
        $customerObj->status = $request->status;           
        if(!empty($request->civil_cr_no)){
            $customerObj->civil_cr_no = $request->civil_cr_no;
        }
        
        if(!empty($request->nationality)){
            $customerObj->nationality = $request->nationality;
        }
        
        if(!empty($request->address)){
            $customerObj->address = $request->address;
        }

        if($customerObj->save()){   
            return redirect()->route('customer')->with('success', 'customer added successfully.');
        } else {
            return redirect()->back()->with('error', 'customer not added.');
        }
    }

    public function edit($id){
        $customer = Customer::where('id', $id)->first();
        
        if($customer){
            $country = Country::pluck('nationality','id');
            $code = Country::pluck('dialing_code','id');

            return View('Customer.edit', compact('customer','country','code'));
        } else {
            return Redirect::route('customer')->with('error', 'customer not found.');
        }
    }

    public function update($id, Request $request){
        $this->validate($request, [
            'name'   => 'required',
            'mobile_country_code' => 'required',
            'mobile_no' => 'required|numeric|digits:10|unique:App\Models\Customer,mobile_no,'.$id,
            'status' => 'required',
           
        ]);

        $customerObj = Customer::where('id', $id)->first();
        if($customerObj){
            $customerObj->name = $request->name;
            $customerObj->mobile_country_code = $request->mobile_country_code;
            $customerObj->mobile_no = $request->mobile_no;
            $customerObj->civil_cr_no = $request->civil_cr_no;
            $customerObj->nationality = $request->nationality;
            $customerObj->address = $request->address;
            $customerObj->status = $request->status;

            if($customerObj->save()){
                return redirect()->route('customer')->with('success', 'customer updated successfully.');
            } else {
                return redirect()->back()->with('error', 'customer not updated.');
            }
        } else {
            return redirect()->route('customer')->with('success', 'customer not found.');
        }
    }

    public function updateStatus(Request $request){
        if($request->has('id') && $request->has('status')) {
            $customerObj = Customer::where('id', $request->id)->first();
            if(!empty($customerObj)){
                $customerObj->status = $request->status;
                $customerObj->save();
            }
        }
    }

    public function remove(Request $request){
        if($request->has('id')) {
            $customerObj = Customer::where('id', $request->id)->first();
            $customerObj->delete();
        }
    }   
    
    public function mobile(Request $request){
        $valid = TRUE;

        if(!empty($request->mobile_no)){
            $customerObj = Customer::where('mobile_no', $request->mobile_no);
            if(!empty($request->id)){
                $customerObj = $customerObj->where('id', '!=', $request->id);    
            }
            $customerObj = $customerObj->count();
            if($customerObj){
                $valid = FALSE;
            }
        } else {
            $valid = FALSE;
        }

        return json_encode(array('valid' => $valid));
    }

}