<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Projects;
use App\Models\Ticket\Category;
use App\Models\Apptitle;
use App\Models\Footertext;
use App\Models\Seosetting;
use App\Models\Pages;
use App\Imports\ProjectImport;
use Auth;
use Illuminate\Support\Facades\Validator;
use Response;
use DB;
use App\Models\Projects_category;
use App\Models\User;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;
use Jenssegers\Agent\Agent;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;

class ProjectsController extends Controller
{
    public function allprojects()
    {
        $data['projects'] = Projects::all();
        return $data;
    }
    public function index(Request $request)
    {
        $projectss = Projects::latest();

        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;

        if ($searchTerm) {
            $projectss->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('projects');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }
        $items = $projectss->paginate($perPage);
        $data['queryList'] = $items;

        $basic = Apptitle::first();
        $data['basic'] = $basic;

        $projects = Projects::all();
        $data['project'] = $projects;

        $categories = Category::whereIn('display', ['ticket', 'all'])->where('status', '1')->get();
        $data['categories'] = $categories;

        $check_category = Projects_category::pluck('category_id')->toArray();
        $data['check_category'] = $check_category;

        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }

        return $data;
    }


    public function store(Request $request)
    {
        $this->authorize('Project Create');

        $testiId = $request->projects_id;
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',

        ]);

        if ($testiId) {
            $project = Projects::find($testiId);
            if ($project->name != $request->name) {
                $validator = Validator::make($request->all(), [
                    'name' => 'required|string|max:255|unique:projects',

                ]);
            }
        } else {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255|unique:projects',

            ]);
        }


        if ($validator->passes()) {
            $testiId = $request->projects_id;


            $testi =  [
                'name' => $request->name,
            ];

            $project = Projects::updateOrCreate(['id' => $testiId], $testi);

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = $testiId ? 'Updated project' : 'created project';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

            $message = $testiId ? 'Project updated successfully.' : 'Project created successfully.';
            return response()->json(['code' => 200, 'success' => $message, 'data' => $project], 200);
        } else {
            return Response::json(['errors' => $validator->errors()], 500);
        }
    }

    public function show($id)
    {
        $this->authorize('Project Edit');
        $post = Projects::find($id);

        $cat = DB::table("category_category_user")->where("category_category_user.category_id", $id)
            ->pluck('category_category_user.category_user_id', 'category_category_user.category_user_id')
            ->all();
        $output = '';
        $data = Category::all();
        $total_row = $data->count();
        if ($total_row > 0) {
            foreach ($data as $row) {
                $output .= '


                    <option  value="' . $row->id . '" >' . $row->name . '</option>

                    ';
            }
        }


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

    public function destroy(Request $request)
    {
        $this->authorize('Project Delete');
        $testimonial = Projects::find($request->input('id'));
        $testimonial->delete();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted a project';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'The project was successfully deleted.']);
    }

    public function projectmassdestroy(Request $request)
    {
        $student_id_array = $request->input('id');

        $projects = Projects::whereIn('id', $student_id_array)->get();

        foreach ($projects as $project) {
            $project->delete();
        }
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted Multiple projects';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'The project was successfully deleted.']);
    }

    public function projectlist()
    {

        $category = Category::all();

        $project = Projects::all();

        return response()->json(['category' => $category, 'project' => $project]);
    }

    public function projectassignee(Request $r)
    {
        $this->authorize('Project Assign');
        $projects = Projects::find($r->projected);
        if (!empty($projects)) {
            foreach ($projects as $project) {
                $project->updated_at = now();
                $project->update();

                if ($r->input('category_id') == null) {
                    $project->projectscategory()->detach($r->input(['category_id']));
                } else {
                    foreach ($r->input('category_id') as $value) {
                        $category_id[] = $value;
                    }
                    $project->projectscategory()->sync($r->input(['category_id']));
                }
            }
            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Assigned projects';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
            return response()->json(['success' => 'The projects were successfully assigned.']);
        } else {
            return response()->json(['error' => 'Projects have not been assigned.']);
        }
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function projetcsv(Request $req)
    {
        $this->authorize('Project Importlist');
        if ($req->hasFile('file')) {
            $validator = Validator::make(
                $req->all(),
                [

                    'file' => 'required|file|mimes:xlsx,csv,txt',
                ],
                [
                    'file.mimes' => 'The file must be a file of type: xlsx, csv.',

                ]
            );
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator)->withInput();
            }

            $file = $req->file('file')->store('import');

            $import = new ProjectImport;
            $import->import($file);
            if ($import->hasData) {
                $geolocation = GeoIP::getLocation(request()->getClientIp());
                $agent = new Agent();
                $activity = new EmployeeActivity();
                $activity->user_id = Auth::user()->id;
                $activity->activity_type = 'Imported the projects list';
                $activity->ip_address = $geolocation->ip;
                $activity->browser = $agent->browser();
                $activity->device = $agent->device();
                $activity->save();
                return response()->json(['success' => 'The project list was imported successfully.']);
            } else {
                return response()->json(['error' => 'The imported file does not contain any data.']);
            }
            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Imported the projects list';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
            return response()->json(['success' => 'The project list was imported successfully.']);
        } else {
            return response()->json(['error' => 'Please select file to import data of Project.']);
        }
    }

    public function notificationpage(Request $request)
    {
        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $data['authname'] = $user->name;
        $data['authtimezone'] = $user->timezone;
        $data['timezonedata'] = Auth::user()->timezone ?? setting('default_timezone');

        $notifications = auth()->user()->notifications();
        $status = json_decode($request->status);
        if (count($status)) {
            $notifications->whereIn('data->status', $status);
        }
        $searchterm = $request->notifysearch;
        if ($searchterm != "null") {
            $notifications->where(function ($query) use ($searchterm) {
                $query->where('data->title', 'LIKE', "%{$searchterm}%")
                    ->orWhere('data->ticket_id', 'LIKE', "%{$searchterm}%")
                    ->orWhere('data->mailsubject', 'LIKE', "%{$searchterm}%")
                    ->orWhere('data->mailtext', 'LIKE', "%{$searchterm}%");
            });
        }

        $item = $notifications->select('*', \DB::raw('DATE(created_at) as created_date'))
            ->orderBy('created_at', 'desc')
            ->paginate(6);
        $item->getCollection()->transform(function ($groups) {
            if (isset($groups->data['ticket_id'])) {
                $groups->enc_ticket_id = encrypt($groups->data['ticket_id']);
            }
            return $groups;
        });

        $data['notifications'] = $item;

        $data['setting'] = response()->json(['date_format' => setting('date_format'), 'default_timezone' => setting('default_timezone')]);

        return $data;
    }
}
