<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\File;
use App\Models\Subscription;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class FileController extends Controller
{
    public function index()
    {
        $pageTitle = 'Files';
        $user = auth()->user();
        $pendingFiles = File::where('user_id', $user->id)->where('status', 0)->with(['reviewer', 'category'])->latest()->paginate(10);
        $publishedFiles = File::where('user_id', $user->id)->where('status', 1)->with(['reviewer', 'category'])->latest()->paginate(10);
        $rejectedFiles = File::where('user_id', $user->id)->where('status', 2)->with(['reviewer', 'category'])->latest()->paginate(10);
        $onReviewingFiles = File::where('user_id', $user->id)->where('status', 3)->with(['reviewer', 'category'])->latest()->paginate(10);
        $pendingFilesCount = File::where('user_id', $user->id)->where('status', 0)->count();
        $publishedFilesCount = File::where('user_id', $user->id)->where('status', 1)->count();
        $rejectedFilesCount = File::where('user_id', $user->id)->where('status', 2)->count();
        $onReviewingFilesCount = File::where('user_id', $user->id)->where('status', 3)->count();
        return view($this->activeTemplate . 'user.file.index', compact(
            'pageTitle',
            'pendingFiles',
            'publishedFiles',
            'rejectedFiles',
            'onReviewingFiles',
            'pendingFilesCount',
            'publishedFilesCount',
            'rejectedFilesCount',
            'onReviewingFilesCount',
        ));
    }

    public function fileStore(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'category_id' => 'required',
            'tags' => 'required',
            'description' => 'required',
            'file' => 'required|image|mimes:jpeg,png,jpg'
        ], [
            'title.required' => 'Please enter a title to submit.',
            'category_id.required' => 'Please select a category to submit.',
            'tags.required' => 'Please select desired tags.',
            'description.required' => 'Please write a description to submit.',
            'file.required' => 'Please select a file to submit.',
            'file.mimes' => 'File type must be jpeg, png or jpg.'
        ]);

        $file = $request->file('file');

        // save main image
        $fileName = time() . '.' . $file->getClientOriginalExtension();
        $file->move(getFilePath('file'), $fileName);

        // save watermark image original size and preview size 
        $image = Image::make(getFilePath('file') . '/' . $fileName);
        $watermark = Image::make(getFilePath('others') . '/' . 'watermark.png');

        $imageWidth = $image->width();
        $imageHeight = $image->height();

        if ($imageHeight > $imageWidth) {
            $percentage = 40;
        } else {
            $percentage = 30;
        }

        $watermarkWidth = $imageWidth * $percentage / 100;
        $watermarkHeight = $watermarkWidth * ($watermark->height() / $watermark->width());
        $watermark->resize($watermarkWidth, $watermarkHeight);

        $positionX = ($imageWidth - $watermarkWidth) / 2;
        $positionY = ($imageHeight - $watermarkHeight) / 2;

        // Ensure the position values are integers
        $positionX = (int) round($positionX);
        $positionY = (int) round($positionY);

        // inserting watermark
        $image->insert($watermark, 'top-left', $positionX, $positionY);

        // preview size
        $preview = getFilePath('preview');
        $image->resize(800, null, function ($constraint) {
            $constraint->aspectRatio();
        });
        $image->save($preview . $fileName);

        // Create a thumbnail while maintaining aspect ratio
        $imagePath = getFilePath('file') . '/' . $fileName;
        $thumbnailPath = getFilePath('media');
        $thumbnail = Image::make($imagePath);
        $thumbnail->resize(300, null, function ($constraint) {
            $constraint->aspectRatio();
        });
        $thumbnail->save($thumbnailPath . $fileName);

        $file = new File();
        $file->user_id = auth()->user()->id;
        $file->category_id = $request->category_id;
        $file->title = $request->title;
        $file->width = $imageWidth;
        $file->height = $imageHeight;
        $file->file = $fileName;
        $file->tags =  $request->tags;
        $file->description =  $request->description;
        $file->status =  0;
        $file->is_premium = isset($request->isPremium) ? 1 : null;
        $file->save();

        return ['upload' => true];
    }


    public function edit($id)
    {
        $pageTitle = 'Edit File';
        $file = File::find($id);
        return view($this->activeTemplate . 'user.file.edit', compact('pageTitle', 'file'));
    }

    public function fileEdit(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required',
            'category_id' => 'required',
            'tags' => 'required',
            'description' => 'required',
        ], [
            'title.required' => 'Please enter a title to submit.',
            'category_id.required' => 'Please select a category to submit.',
            'tags.required' => 'Please select desired tags.',
            'description.required' => 'Please write a description to submit.',
        ]);


        $file = File::find($id);
        $file->category_id = $request->category_id;
        $file->title = $request->title;
        $file->tags =  $request->tags;
        $file->description =  $request->description;
        $file->is_premium = isset($request->isPremium) ? 1 : null;
        $file->save();

        $notify[] = ['success', 'Your Image has been updated successfully.'];
        return to_route('user.file.index')->withNotify($notify);
    }

    public function fileDelete($id)
    {
        $file = File::find($id);
        $filePath = getFilePath('file');
        $thumbPath = getFilePath('media');
        $previewPath = getFilePath('preview');
        $watermarkPath = getFilePath('watermark');

        fileManager()->removeFile($filePath . '/' . $file->file);
        fileManager()->removeFile($thumbPath . '/' . $file->file);
        fileManager()->removeFile($previewPath . '/' . $file->file);
        fileManager()->removeFile($watermarkPath . '/' . $file->file);

        $file->delete();

        $notify[] = ['success', 'File has been successfully deleted'];
        return back()->withNotify($notify);
    }

    public function download($id)
    {
        $file = File::where('status', 1)->find($id);
        $file->download_count += 1;
        $file->save();

        $path = getFilePath('file') . '/' . $file->file;

        if (file_exists($path)) {
            return response()->download($path, 'downloaded_image.jpg');
        } else {
            $notify[] = ['error', 'Sorry, Image not found.'];
            return back()->withNotify($notify);
        }
    }

    public function downloadBySubscription($id)
    {
        $user = auth()->user();
        if ($user->image_count == 0) {
            $subscription = Subscription::where('user_id', $user->id)->first();
            $subscription->delete();

            $user->image_count = null;
            $user->save();

            $notify[] = ['error', 'Sorry, Your have finished your download limit.'];
            return back()->withNotify($notify);
        }

        $file = File::where('status', 1)->find($id);
        $file->download_count += 1;
        $file->save();

        $user->image_count -= 1;
        $user->save();

        $path = getFilePath('file') . '/' . $file->file;

        if (file_exists($path)) {
            return response()->download($path, 'downloaded_image.jpg');
        } else {
            $notify[] = ['error', 'Sorry, Image not found.'];
            return back()->withNotify($notify);
        }
    }
}
