<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Aws\S3\S3Client;
use App\Models\SliderImages;
use Illuminate\Support\Facades\Auth;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    public function s3Bucket()
    {
        try {
            $s3 = S3Client::factory([
                'credentials' => [
                    'key' => config('app.AWS_KEY'),
                    'secret' => config('app.AWS_SECRET'),
                ],
                'version' => 'latest',
                'region' => config('app.AWS_REGION'),
            ]);
            return $s3;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    function deleteS3Item($path)
    {
        try {
            $s3 = $this->s3Bucket();
            $bucketName = config('app.AWS_BUCKET');
            if ($path != 'default_images/default.jpg') {
                $s3->deleteObject([
                    'Bucket' => $bucketName,
                    'Key' => "$path",
                ]);
            }
            return 1;
        } catch (\Exception $e) {
            error_log($e->getMessage());
            return 0;
        }
    }

    public function uploadFile($file, $folder = '', $originalFileName = '', $user_id = 0, $product_id = 0, $subFolder = '')
    {
        $s3 = $this->s3Bucket();
        try {
            $s3Url = config('app.AWS_S3_URL');
            $bucketName = config('app.AWS_BUCKET');
            $awsType = config('app.AWS_TYPE');
            $fileName = '';
            $fileExtension = '';
            $fileMimeType = '';
            $filePath = '';
            $base64Data = null;
            $sanitizeFileName = function ($name, $extension) {
                $name = preg_replace('/[^a-zA-Z0-9_-]/', '_', $name);
                $name = str_replace('_' . $extension, '', $name);
                return trim($name, '_') . '.' . $extension;
            };
            if (is_string($file)) {
                [$type, $file] = explode(';', $file);
                [, $file] = explode(',', $file);
                $fileExtension = explode('/', $type)[1];
                $fileMimeType = $type;
                $base64Data = base64_decode($file);
            } else {
                $filePath = $file->getRealPath();
                $fileExtension = $file->getClientOriginalExtension();
                $fileMimeType = $file->getMimeType();
            }
            if (!empty($originalFileName)) {
                $fileName = pathinfo($originalFileName, PATHINFO_FILENAME);
                $fileName = time().'_'.$fileName;
            } else {
                $fileName = !is_string($file) ? time().'_'.$file->getClientOriginalName() : uniqid(time(), true);
            }
            $fileName = str_replace(['_jpg', '_jpeg', '_png', '_gif', '_mp4', '_svg', '_pdf'], ' ', $fileName);
            $fileNameWithExtension = $sanitizeFileName($fileName, $fileExtension);
            $key = $folder ? $folder . '/' : '';
            if (!empty($user_id)) {
                $key .= $user_id . '/';
            }
            if (!empty($product_id)) {
                $key .= $product_id . '/';
            }
            if (!empty($subFolder)) {
                $key .= $subFolder . '/';
            }
            $key .= $fileNameWithExtension;
            if ($awsType == "local") {
                $key = $awsType . '/' . $key;
            }
            $result = $s3->putObject([
                'ACL' => 'private',
                'Bucket' => $bucketName,
                'Key' => $key,
                'ContentType' => $fileMimeType,
                'Body' => isset($base64Data) ? $base64Data : fopen($filePath, 'r'),
            ]);
            return $key;
        } catch (\Exception $e) {
            error_log($e->getMessage());
            return 0;
        }
    }

    public function removeSpecialCharacter($link)
    {
        $pageLink = preg_replace('/[^a-zA-Z0-9_ -]/s', '-', $link);
        $pageLink = str_replace(' ', '-', strtolower($pageLink));
        $pageLink = preg_replace("/(-)\\1+/", "$1", $pageLink);
        return $pageLink;
    }

    public function removeSpecialCharactersFromFileName($filename)
    {
        $filename = str_replace(' ', '_', $filename);
        $filename = preg_replace('/[^A-Za-z0-9_\-]/', '_', $filename);
        $filename = preg_replace('/_+/', '_', $filename);
        $filename = trim($filename, '_');
        return $filename;
    }

    public function handleSliderImages($files, $fileState, $page)
    {
        try {
            $dataArray = [];
            $isDelete = 0;            
            if ($fileState == 'upload') {
                foreach ($files as $key => $value) {
                    $fileName = !empty($value['fileName']) ? preg_replace('/[^A-Za-z0-9\-]/', '_', $value['fileName']) : '';
                    $newImage = $this->uploadFile($value['filePath'], 'sliderMedia', $fileName);
                    if (!empty($newImage)) {
                        $dataArray[] = [
                            'user_id' => Auth::user()->id,
                            'page' => $page,
                            'filePath' => $newImage,
                            'created_at' => time(),
                        ];
                    }
                }
                if (!empty($dataArray)) {
                    SliderImages::insert($dataArray);
                }
            } else {
                foreach ($files as $key => $value) {
                    if (!empty($value['record_id'])) {
                        $path = (string)$value['filePath'];
                        $isDelete = $this->deleteS3Item($path);
                        if ($isDelete == 1) {
                            $dataArray[] = $value['record_id'];
                        }
                    }
                }
                if (!empty($dataArray)) {
                    SliderImages::whereIn('id', $dataArray)->where('page', $page)->delete();
                }
            }  
            return 1;          
        } catch (\Throwable $th) {            
            return 0;
        }
    }
}
