<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Testimonial;
use App\Models\Apptitle;
use App\Models\User;
use Auth;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;
use Jenssegers\Agent\Agent;;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;

class TestimonialController extends Controller
{
    public function index(Request $request)
    {
        $this->authorize('Testimonial Access');

        $testimonials = Testimonial::latest();

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

        if ($searchTerm) {
            $testimonials->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('testimonials');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }
        $items = $testimonials->paginate($perPage);
        foreach ($items as $comment) {
            if ($comment->image) {
                $conversionsDisk = $comment->storage_disk ?? 'public';
                $provider = existprovider($conversionsDisk)->provider;
                $imageUrl = $provider::getImageUrl('uploads/testimonial/' . $comment->image);
                // Only set the "profileimage" attribute if it's not already set
                if (!isset($comment['profileimage'])) {
                    $comment['profileimage'] = $imageUrl;
                }
            }
        }
        $data['queryList'] = $items;

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

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

        $setting = response()->json(['FILE_UPLOAD_TYPES' => setting('FILE_UPLOAD_TYPES'), 'FILE_UPLOAD_MAX' => setting('FILE_UPLOAD_MAX'), 'MAX_FILE_UPLOAD' => setting('MAX_FILE_UPLOAD'),]);
        $data['setting'] = $setting;

        return $data;
    }


    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'designation' => 'required|max:255',
            'description' => 'required',

        ]);
        if ($files = $request->file('image')) {

            $this->validate($request, [
                'image' => 'required|mimes:jpg,jpeg,png,svg|max:10240',
            ]);
        }

        $testiId = $request->testimonial_id;
        
        $description = $request->input('description');

        // Trim unwanted tags from the start and end
        $description = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $description);
        $testi =  [
            'name' => $request->name,
            'designation' => $request->designation,
            'description' => $description,
        ];

        if ($request->testimonialimgRemoved) {
            $data = Testimonial::find($request->testimonialimgRemoved);
            $imagepath =   public_path() . "" . '/uploads/testimonial/' . $data->image;
            if (\File::exists($imagepath)) {
                \File::delete($imagepath);
            }
            $data->image = null;
            $data->save();
        }
        if ($files = $request->file('image')) {

            if ($request->testimonial_id) {
                //delete old file
                $testiimage = Testimonial::find($request->testimonial_id);
                $provider  = existprovider($testiimage->storage_disk ?? 'public')->provider;
                $provider::delete('/uploads/testimonial/' . $testiimage->image);
            }

            $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
            $provider = storage()->provider;
            $provider::uploadImage($files, '/uploads/testimonial/', $profileImage);
            $testi['image'] = $profileImage;
            $testi['storage_disk'] = storage()->storage_disk;
        }

        $testimonial = Testimonial::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 Testimonial' : 'created Testimonial';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        $message = $testiId ? 'Testimonial updated successfully.' : 'Testimonial created successfully.';
        return response()->json(['code' => 200, 'success' => $message, 'data' => $testimonial], 200);
    }

    public function show($id)
    {
        $this->authorize('Testimonial Edit');
        $post = Testimonial::find($id);
        if ($post->image != null) {
            $provider = storage()->provider;
            $post['imageurl'] = route('getImage.url', ['imagePath' => 'uploads*testimonial*' . $post->image, 'storage_disk' => $post->storage_disk ?? 'public']);
        } else {
            $post['imageurl'] = null;
        }

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

    public function destroyImage($id)
    {
        $this->authorize('Testimonial Edit');
        $data = Testimonial::find($id);
        $imagepath =   public_path() . "" . '/uploads/testimonial/' . $data->image;
        if (\File::exists($imagepath)) {
            \File::delete($imagepath);
        }
        $data->image = null;
        $data->save();


        return response()->json(['success' => 'Deleted successfully.']);
    }

    public function destroy($id)
    {
        $this->authorize('Testimonial Delete');
        $data = Testimonial::where('id', $id)->first(['image']);
        \File::delete(public_path() . "" . '/uploads/testimonial/' . $data->image);
        $testimonial = Testimonial::find($id);
        $testimonial->delete();

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

    public function imagedelete($id)
    {
        $this->authorize('Testimonial Edit');

        $testimoni = Testimonial::find($id);

        $provider  = existprovider($testimoni->storage_disk ?? 'public')->provider;
        $provider::delete('/uploads/testimonial/' . $testimoni->image);

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

        return response()->json(['success' => lang('The testimonial image was successfully deleted.', 'alerts')]);
    }


    public function alltestimonialdelete(Request $request)
    {
        $id_array = $request->input('id');

        $sendmails = Testimonial::whereIn('id', $id_array)->get();

        foreach ($sendmails as $sendmail) {
            \File::delete(public_path() . "" . '/uploads/testimonial/' . $sendmail->image);
            $sendmail->delete();
        }
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted all testimonials';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'The testimonial to was successfully deleted.']);
    }




    public function testi(Request $request)
    {

        $request->validate([
            'testimonialtitle' => 'required|max:255',

        ]);
        if ($request->testimonialsub) {
            $request->validate([
                'testimonialsub' => 'max:255',

            ]);
        }
        $calID = ['id' => $request->id];
        $calldetails = [
            'testimonialtitle' => $request->testimonialtitle,
            'testimonialsub' => $request->testimonialsub,
            'testimonialcheck'  => $request->has('testimonialcheck') ? 'on' : 'off',

        ];

        $callaction = Apptitle::updateOrCreate(
            ['id' => $calID],
            $calldetails
        );

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

        return response()->json(['success' => 'Updated Successfully']);
    }
}
