<?php

namespace App\Http\Controllers;

use App\DataTables\DivisionDataTable;
use App\DataTables\SubAdminDataTable;
use App\DataTables\WhatsappsDataTable;
use App\Models\Admin;
use App\Models\AssignDivisionAdmin;
use App\Models\AssignDivisionTeamMember;
use App\Models\Division;
use Illuminate\Support\Facades\Auth;
use Alert;
use DB;
use Illuminate\Support\Facades\Hash;
use Validator;
use App\Models\Event;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\region;
use App\Models\region_country;
use App\DataTables\RegionDataTable;
use App\Models\QuotationConfiguration;

class SettingController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->event = new Event();
        $this->user = new User();
    }


    public function whatsappmsg(Request $request)
    {
        $data = DB::table('whatsapp_msg')->first();

        return view('settings.whatsapp_msg', compact('data'));
    }

    public function editwhatsapp_msg(Request $request)
    {
        $data = [
            'message' => $request->message
        ];
        //dd($request->id);
        if (isset($request->id) && $request->id !=  null) {
            $update = DB::table('whatsapp_msg')->where('id', $request->id)->update($data);
        } else {
            $data = [
                'message' => $request->message,
                'created_date' => date('Y-m-d H:i:s')
            ];
            $update = DB::table('whatsapp_msg')->insert($data);
        }


        Alert::success('Congrats', 'You have Successfully Data Updated');

        return redirect('setting/whatsapp_msg');
    }

    public function change_password(Request $request)
    {
        return view('settings.changepassword');
    }

    public function update_password(Request $request)
    {
        $this->validate($request, [
            'password' => 'required|confirmed|min:6',
        ]);

        $data['admin'] = DB::table('admin')->where('id', Auth::user()->id)->update(['password' => Hash::make($request->password)]);
        Alert::success('Congrats', 'You have Successfully Password Change');

        return redirect('setting/change_password');
    }
    public function update_email(Request $request)
    {
        $this->validate($request, [
            'email' => 'required',
        ]);

        $data['admin'] = DB::table('admin')->where('id', Auth::user()->id)->update(['email' => $request->email]);
        Alert::success('Congrats', 'You have Successfully Updated Email');

        return redirect('setting/change_password');
    }
    public function martkey(Request $request)
    {
        $keyname = DB::table('configs')->where('id', '1')->first();
        $tradKey = DB::table('configs')->where('id', '2')->first();
        $zoho_crm = DB::table('zoho_crm')->where('id', '1')->first();
        $templates =  DB::table('templates')->get();
        $user_emailconfig = DB::table('email_config')->first();

        return view('settings.indiamartkey', compact('keyname', 'tradKey', 'user_emailconfig','zoho_crm','templates'));
    }
    public function updatekey(Request $request)
    {

        if ($request->has('indiamartkey')) {

            $type = 'india_mart';
            if ($request->action == 'update') {

                $data = [
                    'indiamartkey' => $request->indiamartkey,
                    'whatsapp_template_id' => $request->whatsapp_template_id ?? null,
                ];
                $update = DB::table('configs')->where('id', '1')->update($data);
                Alert::success('Congrats', 'You have Successfully Data Update');
            } else {
                $this->event::insert_event_with_martkey($type, $request->indiamartkey);
                $eventid = DB::getPdo()->lastInsertId();
                $userid = $this->user::insert_user_with_martkey($type, $request->indiamartkey, $eventid);
                // $userid = DB::getPdo()->lastInsertId();
                $customerid = DB::table('users')->select('CustomerID')->where('user_id', $userid)->first();
                $data = [
                    'id' => "1",
                    'indiamartkey' => $request->indiamartkey,
                    'indiamartkey_url' => "https://mapi.indiamart.com/wservce/crm/crmListing/v2/?glusr_crm_key=mR27FLlp5HnFQPej5X2K7liLolHHnzVi",
                    'indiamart_event_id' => $eventid,
                    'indiamart_user_id' => $customerid->CustomerID,
                    'whatsapp_template_id' => $request->whatsapp_template_id ?? null,
                ];
                $insert = DB::table('configs')->insert($data);
                Alert::success('Congrats', 'You have Successfully Data Insert');
            }
        } elseif ($request->has('tradindiakey')) {
            $type = 'trad_india';
            if ($request->action == 'update') {
                $data = [
                    'indiamartkey' => 'tradindiakey',
                    'user_id' => $request->user_id,
                    'profile_id' => $request->profile_id,
                    'key' => $request->key
                ];
                $update = DB::table('configs')->where('id', '2')->update($data);
                Alert::success('Congrats', 'You have Successfully Data Update');
            } else {
                $this->event::insert_event_with_martkey($type, $request->tradindiakey);
                $eventid = DB::getPdo()->lastInsertId();
                $userid = $this->user::insert_user_with_martkey($type, $request->tradindiakey, $eventid);
                // $userid = DB::getPdo()->lastInsertId();
                $customerid = DB::table('users')->select('CustomerID')->where('user_id', $userid)->first();
                $data = [
                    'id' => "2",
                    'indiamartkey' => 'tradindiakey',
                    'indiamartkey_url' => "https://www.tradeindia.com/utils/my_inquiry.html",
                    'indiamart_event_id' => $eventid,
                    'indiamart_user_id' => $customerid->CustomerID,
                    'user_id' => $request->user_id,
                    'profile_id' => $request->profile_id,
                    'key' => $request->key
                ];
                $insert = DB::table('configs')->insert($data);
                Alert::success('Congrats', 'You have Successfully Data Insert');
            }

        }


        return redirect('setting/indiamart');
    }
    public function upload_image(Request $request)
    {
        $id = Auth::user()->id;
        $image['imagesdata'] = DB::table('upload_images')->where('fk_user_id', $id)->get();
        return view('settings.uploadimage', $image);
    }
    public function store_image(Request $request)
    {
        $id = Auth::user()->id;
        if ($files = $request->file('images')) {

            foreach ($files as $key => $file) {

                $name  = str_replace(' ', '_', $file->getClientOriginalName());
                $ext   = $file->getClientOriginalExtension();
                $attachment = md5(microtime() . $name) . "." . $ext;
                $path = public_path(UPLOAD_IMAGE);
                $path_all = $file->move($path, $attachment);

                $data = ([
                    'fk_user_id' => $id,
                    'image' => $attachment,
                    'created_at' => date('Y-m-d H:i:s'),
                ]);
                DB::table('upload_images')->insert($data);
            }
        }
        Alert::success('Congrats', 'created successfully!');
        return redirect('setting/upload_image');
    }
    public function delete_image($id)
    {
        DB::table('upload_images')->where('id', $id)->delete();

        return response()->json(['status' => true, 'message' => 'deleted successfully']);
    }
    public function update_emailconfig(Request $request)
    {
        if ($request->action == 'update') {
            $user_emailconfig = DB::table('email_config')->first();
            $data = [
                'host' => isset($request->host) ? $request->host : $user_emailconfig->host,
                'username' => isset($request->username) ? $request->username : $user_emailconfig->username,
                'password' => isset($request->password) ? $request->password : $user_emailconfig->password,
                'smtp_port' => isset($request->smtp_port) ? $request->smtp_port : $user_emailconfig->smtp_port,
                'smtp_transport' => isset($request->smtp_transport) ? $request->smtp_transport : $user_emailconfig->smtp_transport,
                'smtp_encryption' => isset($request->smtp_encryption) ? $request->smtp_encryption : $user_emailconfig->smtp_encryption,
            ];
            $update = DB::table('email_config')->update($data);
            Alert::success('Congrats', 'You have Successfully Data Update');
        } else {
            $data = [
                'host' => $request->host,
                'username' => $request->username,
                'password' => $request->password,
                'smtp_port' => $request->smtp_port,
                'smtp_transport' => $request->smtp_transport,
                'smtp_encryption' => $request->smtp_encryption,
            ];
            $insert = DB::table('email_config')->insert($data);
            Alert::success('Congrats', 'You have Successfully Data Insert');
        }
        return redirect('setting/indiamart');
    }

    public function region_list(Request $request, RegionDataTable $dataTable)
    {
        return $dataTable->render('settings.region_list');
    }
    public function add(Request $request)
    {
        $allCountry = DB::table('countries')->get(['id', 'name'])->toArray();

        return view('settings.add', compact('allCountry'));
    }
    public function add_store(Request $request)
    {
        //    dd($request->all());
        $region = new region();
        $region->name = $request->name;
        $region->save();

        if (isset($request->Country)) {
            foreach ($request->Country as $countryId) {
                $region_country =  new region_country();
                $region_country->fk_country_id  = $countryId;
                $region_country->fk_region_id   = $region->id;
                $region_country->save();
            }
        }
        Alert::success('Congrats', 'You have Successfully Data Insert');
        return redirect()->back();
    }
    public function region_delete($id)
    {
        try {
            region::where('id', $id)->delete();

            region_country::where('fk_region_id', $id)->delete();

            return response()->json([
                "status" => true,
            ]);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
    public function region_edit(Request $request)
    {
        $data_region = region::where('id', $request->id)->first();
        $selectedCountryIdsString = DB::table('region_country')
            ->select('countries.id as id')
            ->leftJoin('countries', 'countries.id', 'region_country.fk_country_id')
            ->where('region_country.fk_region_id', $request->id)
            ->get()->pluck('id')->toArray();

        $allCountries = DB::table('countries')->get()->toArray();
        $encodedCountries = [];

        foreach ($allCountries as $country) {
            $country->name = htmlspecialchars($country->name, ENT_QUOTES);
            $encodedCountries[] = $country;
        }
        $allCountry = json_encode($encodedCountries);

        return view('settings.region_edit', compact('data_region', 'allCountry', 'selectedCountryIdsString'));
    }
    public function edit_store(Request $request)
    {
        $region = region::find($request->id);
        $region->name = isset($request->name) ? $request->name : $region->name;
        $region->save();

        region_country::where('fk_region_id', $request->id)->delete();
        if (isset($request->Country)) {

            foreach ($request->Country as $countryId) {
                $region_country =  new region_country();
                $region_country->fk_country_id  = $countryId;
                $region_country->fk_region_id   = $request->id;
                $region_country->save();
            }
        }
        Alert::success('Congrats', 'You have Successfully Data Update');
        return redirect()->back();
    }

    // Division Module

    public function divisionList(Request $request, DivisionDataTable $dataTable)
    {
        return $dataTable->render('settings.division.list');
    }
    public function divisionAdd(Request $request)
    {
        return view('settings.division.add');
    }
    public function divisionInsert(Request $request)
    {
        $division = new Division();
        $division->name = $request->name;
        $division->save();
        Alert::success('Congrats', 'Division added successfully');
        return redirect()->back();
    }
    public function divisionDelete($id)
    {
        try {
            AssignDivisionAdmin::where('division_id', $id)->delete();
            AssignDivisionTeamMember::where('division_id', $id)->delete();
            Division::where('id', $id)->delete();

            return response()->json([
                "status" => true,
            ]);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
    public function divisionEdit(Request $request)
    {
        $division = Division::where('id', $request->id)->first();
        return view('settings.division.edit', compact('division'));
    }
    public function divisionUpdate(Request $request)
    {
        $division = Division::find($request->id);
        $division->name = isset($request->name) ? $request->name : $division->name;
        $division->save();
        Alert::success('Congrats', 'Division updated successfully');
        return redirect()->back();
    }

    public function subAdminList(Request $request, SubAdminDataTable $dataTable)
    {
        return $dataTable->render('settings.sub-admin.list');
    }
    public function subAdminAdd(Request $request)
    {
        $divisions = DB::table('divisions')->get(['id', 'name'])->toArray();
        return view('settings.sub-admin.add', compact('divisions'));
    }
    public function subAdminInsert(Request $request)
    {
        $subAdmin = new Admin();
        $subAdmin->type = 'sub-admin';
        $subAdmin->name = $request->name;
        $subAdmin->email = $request->email;
        $subAdmin->password = Hash::make($request->password);
        $subAdmin->save();

        if (isset($request->divisions)) {
            foreach ($request->divisions as $divisionId) {
                $assignDivisionAdmin =  new AssignDivisionAdmin();
                $assignDivisionAdmin->division_id  = $divisionId;
                $assignDivisionAdmin->admin_id   = $subAdmin->id;
                $assignDivisionAdmin->save();
            }
        }

        Alert::success('Congrats', 'SubAdmin added successfully');
        return redirect()->back();
    }
    public function subAdminDelete($id)
    {
        try {
            $subAdmin = Admin::where('id', $id)->where('type', 'sub-admin')->first();
            if (!$subAdmin) {
                Alert::error('Sorry', 'SubAdmin not found!');
                return redirect()->route('setting.subAdminList');
            }
            $subAdmin->delete();

            return response()->json([
                "status" => true,
            ]);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
    public function subAdminEdit(Request $request)
    {
        $subAdmin = Admin::where('id', $request->id)->where('type', 'sub-admin')->first();
        if (!$subAdmin) {
            Alert::error('Sorry', 'SubAdmin not found!');
            return redirect()->route('setting.subAdminList');
        }
        $selectedDivisionIdsString = DB::table('assign_division_admins')
            ->select('divisions.id as id')
            ->leftJoin('divisions', 'divisions.id', 'assign_division_admins.division_id')
            ->where('assign_division_admins.admin_id', $request->id)
            ->get()->pluck('id')->toArray();

        $allDivisions = DB::table('divisions')->get()->toArray();
        $encodedDivisions = [];

        foreach ($allDivisions as $division) {
            $division->name = htmlspecialchars($division->name, ENT_QUOTES);
            $encodedDivisions[] = $division;
        }
        $divisions = json_encode($encodedDivisions);
        return view('settings.sub-admin.edit', compact('subAdmin', 'divisions', 'selectedDivisionIdsString'));
    }
    public function subAdminUpdate(Request $request)
    {
        $subAdmin = Admin::find($request->id);
        $subAdmin->name = isset($request->name) ? $request->name : $subAdmin->name;
        $subAdmin->email = isset($request->email) ? $request->email : $subAdmin->email;
        $subAdmin->password = isset($request->password) ? Hash::make($request->password) : $subAdmin->password;
        $subAdmin->save();

        if (isset($request->divisions)) {
            AssignDivisionAdmin::where('admin_id', $request->id)->delete();
            foreach ($request->divisions as $divisionId) {
                $assignDivisionAdmin =  new AssignDivisionAdmin();
                $assignDivisionAdmin->division_id  = $divisionId;
                $assignDivisionAdmin->admin_id   = $subAdmin->id;
                $assignDivisionAdmin->save();
            }
        }
        Alert::success('Congrats', 'Sub-Admin updated successfully');
        return redirect()->back();
    }

    public function quotationconfig(Request $request)
    {
        $quotationconfig = QuotationConfiguration::first();
        return view('settings.editquotationconfig', compact('quotationconfig'));
    }
    public function editquotationconfig(Request $request)
    {

        if($request->id != ""){
            $addeditdata = QuotationConfiguration::find($request->id);
        }else{
            $addeditdata = new QuotationConfiguration();
        }
        if ($request->file('header_image')) {

            $name  = str_replace(' ', '_', $request->file('header_image')->getClientOriginalName());
            $ext   = $request->file('header_image')->getClientOriginalExtension();
            $attachment = md5(microtime() . $name) . "." . $ext;
            $path = public_path(UPLOAD_IMAGE);
            $path_all = $request->file('header_image')->move($path, $attachment);
            $addeditdata->header_image = url('uploads/images').'/'.$attachment;
            
        }
        if ($request->file('footer_image')) {

            $name  = str_replace(' ', '_', $request->file('footer_image')->getClientOriginalName());
            $ext   = $request->file('footer_image')->getClientOriginalExtension();
            $attachment = md5(microtime() . $name) . "." . $ext;
            $path = public_path(UPLOAD_IMAGE);
            $path_all = $request->file('footer_image')->move($path, $attachment);
            $addeditdata->footer_image = url('uploads/images').'/'.$attachment;
        }
        $addeditdata->term_condition = $request->term_condition;
        $addeditdata->save();

        Alert::success('Congrats', 'Quotation Configuration updated successfully');
        return redirect()->back();
    }
    public function deletequotationconfigimage(Request $request)
    {
        $quotationconfig = QuotationConfiguration::find($request->id);
        if($request->type == 'header_image'){
            $quotationconfig->header_image = null;
            $quotationconfig->save();
        }
        if($request->type == 'footer_image'){
            $quotationconfig->footer_image = null;
            $quotationconfig->save();
        }
        return response()->json([
            "status" => true,
        ]);
    }

   
}
