<?php

namespace Wave\Http\Controllers\User;
use App\Models\BookkeepingDocumentCategory;
use App\Models\BookkeepingDocument;
use App\Models\CompanySubscription;
use App\Models\Subscription;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

class BookKeepingController extends Controller
{
    public function accountOverview()
    {
        $current_user = \Auth::user();
        $subscription = CompanySubscription::where('company_id', $current_user->company_id)->first();
        if (! $subscription) {
            return redirect(route('wave.user.book-keeping.packages'));
        }
        return view('theme::user.book-keeping.account-overview');
    }

    public function list()
    {
        $current_user = \Auth::user();
        $document_category = BookkeepingDocumentCategory::all();
        $documents_list = BookkeepingDocument::with('category')->where('company_id', $current_user->company_id)->where('status', '<>', 'completed')->get();
        $documents_complete = BookkeepingDocument::with('category')->where('company_id', $current_user->company_id)->where('status', 'completed')->get();

        return view('theme::user.book-keeping.list',[
            'document_category' => $document_category,
            'documents_list' => $documents_list,
            'documents_complete' => $documents_complete,
        ]);
    }

    public function documentLibrary(Request $request)
    {
        $current_user = \Auth::user();
        $documents = BookkeepingDocument::with('category')->where('company_id', $current_user->company_id);
        if (! is_null($request->get('s'))) {
            $search = $request->get('s');
            $documents->where(function($q) use($search){
                $q->where('file_name', 'LIKE', '%' . $search . '%')
                ->orWhere('batch_name', 'LIKE', '%' . $search . '%')
                ->orWhere('description', 'LIKE', '%' . $search . '%');
            });
        }

        if (! is_null($request->get('status'))) {
            $status = $request->get('status');
            if ($status !== 'all') {
                $documents->where('status', $status);
            }
        }

        if (! is_null($request->get('category_id'))) {
            $category_id = $request->get('category_id');
            if ($category_id !== 'all') {
                $documents->where('bookkeeping_document_category_id', $category_id);
            }
        }

        if (! is_null($request->get('fix_date'))) {
            $fix_date = $request->get('fix_date');
            if ($fix_date !== 'all' && $fix_date !== 'custom') {
                if ($fix_date === 'today') {
                    $date = \Carbon\Carbon::today();
                } else {
                    $date = \Carbon\Carbon::today()->subDays($fix_date);
                }
                $documents->where('created_at','>=',$date);
            }
            if ($fix_date === 'custom') {
                if (! is_null($request->get('data_from')) && ! is_null($request->get('date_to'))) {
                    $documents->whereBetween('created_at', [
                        Carbon::parse($request->get('data_from'))->format('Y-m-d'),
                        Carbon::parse($request->get('date_to'))->format('Y-m-d'),
                    ]);
                }
            }
        }

        $documents = $documents->paginate(10);

        $document_category = BookkeepingDocumentCategory::all();

        return view('theme::user.book-keeping.document-library', [
            'documents' => $documents,
            'document_category' => $document_category,
            'search' => is_null($request->get('s')) ? '' : $request->get('s'),
        ]);
    }

    public function packages()
    {
        return view('theme::user.book-keeping.packages');
    }

    public function checkout($package_id)
    {
        $subscription = Subscription::where('id', $package_id)->firstOrFail();
        return view('theme::user.book-keeping.checkout', [
            'subscription' => $subscription,
        ]);
    }

    public function checkoutPaymentSuccess()
    {
        $current_user = \Auth::user();
        $subscription = CompanySubscription::where('company_id', $current_user->company_id)->first();
        if (! $subscription) {
            CompanySubscription::create([
                'company_id'=> $current_user->company_id,
                'subscription_id'=> 1,
                'stripe_subscription_id'=> 1,
                'status'=> 1,
            ]);
        }
        return view('theme::user.book-keeping.checkout-payment-success');
    }

    public function addBookkeepingDocument(Request $request)
    {
        $request->validate([
            'document' => 'required',
            'name' => 'required',
            'description' => 'required',
            'bookkeeping_document_category_id' => 'required',
        ]);

        $current_user = $request->user();

        $file = $request->file('document');
        $file_name = $request->file('document')->getClientOriginalName();
        $sanitizedFileName = str_replace(' ', '_', $file_name); // Replac
        $fileName = time() . '_' . $sanitizedFileName;

        $bookkeepingDocument = BookkeepingDocument::create([
            'user_id' => $current_user->id,
            'company_id' => $current_user->company_id,
            'batch_name' => $request->name,
            'remark' => $request->description,
            'file_name' => $fileName,
            'bookkeeping_document_category_id' => $request->bookkeeping_document_category_id,
        ]);

        $filePath = $bookkeepingDocument->file_path;
        \Storage::disk('s3')->put($filePath, file_get_contents($file), 'public');
        $url = env('AWS_ENDPOINT').env('AWS_BUCKET').'/'.$filePath;
        $file_size = convertToReadableSize(\Storage::disk('s3')->size($filePath));

        $bookkeepingDocument->update([
            'url' => $url,
            'file_size' => $file_size,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'document successfully added',
        ]);
    }

    public function getDocumentList(Request $request)
    {
        $current_user = $request->user();

        $documents_list = BookkeepingDocument::with('category')->where('company_id', $current_user->company_id)->where('status', '<>', 'completed')->get();
        $documents_complete = BookkeepingDocument::with('category')->where('company_id', $current_user->company_id)->where('status', 'completed')->get();

        return response()->json([
            'success' => true,
            'documents_in_queue' => $documents_list,
            'documents_completed' => $documents_complete,
        ]);
    }

    public function getDocumentCategories(Request $request)
    {
        $current_user = $request->user();

        $document_category = BookkeepingDocumentCategory::all();

        return response()->json([
            'success' => true,
            'categories' => $document_category,
        ]);
    }

    public function viewBookkeepingDocument(Request $request, $document_id)
    {
        $document = BookkeepingDocument::with('category')->where('id', $document_id)->first();

        return response()->json([
            'success' => true,
            'document' => $document,
        ]);
    }

    public function downloadDocument($document_id)
    {
        $asset = BookkeepingDocument::find($document_id);

        return response()->streamDownload(function () use ($asset) {
            echo file_get_contents(\Storage::disk('s3')->url($asset->url));
        } , $asset->file_name);
    }

    public function getDocumentLibrary(Request $request)
    {
        $current_user = $request->user();
        $documents = BookkeepingDocument::with('category')->where('company_id', $current_user->company_id);
        if (! is_null($request->get('s'))) {
            $search = $request->get('s');
            $documents->where(function($q) use($search){
                $q->where('file_name', 'LIKE', '%' . $search . '%')
                ->orWhere('name', 'LIKE', '%' . $search . '%')
                ->orWhere('remark', 'LIKE', '%' . $search . '%');
            });
        }

        if (! is_null($request->get('status'))) {
            $status = $request->get('status');
            if ($status !== 'all') {
                $documents->where('status', $status);
            }
        }

        if (! is_null($request->get('category_id'))) {
            $category_id = $request->get('category_id');
            if ($category_id !== 'all') {
                $documents->where('bookkeeping_document_category_id', $category_id);
            }
        }

        if (! is_null($request->get('fix_date'))) {
            $fix_date = $request->get('fix_date');
            if ($fix_date !== 'all' && $fix_date !== 'custom') {
                if ($fix_date === 'today') {
                    $date = \Carbon\Carbon::today();
                } else {
                    $date = \Carbon\Carbon::today()->subDays($fix_date);
                }

                $documents->where('created_at','>=',$date);
            }
            if ($fix_date === 'custom') {
                if (! is_null($request->get('data_from')) && ! is_null($request->get('date_to'))) {
                    $documents->whereBetween('created_at', [
                        Carbon::parse($request->get('data_from'))->format('Y-m-d'),
                        Carbon::parse($request->get('date_to'))->format('Y-m-d'),
                    ]);
                }
            }
        }

        $documents = $documents->paginate(10);

        return response()->json([
            'success' => true,
            'documents' => $documents,
        ]);
    }
}
