<?php

namespace Wave\Http\Controllers\CMS;

use App\Exports\BookkeepingDocumentLibraryExport;
use App\Models\BookkeepingDocument;
use App\Models\BookkeepingDocumentCategory;
use App\Models\DocumentActionLogs;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;
use Storage;

class BookkeepingDocumentLibraryController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $categories = BookkeepingDocumentCategory::where('status', 'active')
            ->orderBy('name')
            ->get();

        return view('theme::cms.bookkeepings.document-libraries.index', [
            'categories' => $categories,
        ]);
    }

    public function table(Request $request)
    {
        $documents = BookkeepingDocument::query()
            ->select(
                'bookkeeping_documents.id',
                'bookkeeping_documents.file_name',
                'companies.name_english',
                'companies.name_chinese',
                'bookkeeping_document_categories.name as category_name',
                'users.name as user_name',
                'bookkeeping_documents.created_at',
            )
            ->leftJoin('companies', 'bookkeeping_documents.company_id', '=', 'companies.id')
            ->leftJoin('users', 'bookkeeping_documents.user_id', '=', 'users.id')
            ->leftJoin('bookkeeping_document_categories', 'bookkeeping_documents.bookkeeping_document_category_id', '=', 'bookkeeping_document_categories.id')
            ->when($request->bookkeeping_document_category_id, function ($query) use ($request) {
                $query->where('bookkeeping_documents.bookkeeping_document_category_id', $request->bookkeeping_document_category_id);
            })
            ->when($request->status, function ($query) use ($request) {
                $query->where('bookkeeping_documents.status', $request->status);
            })
            ->when($request->file_name, function ($query) use ($request) {
                $query->where('bookkeeping_documents.file_name', 'like', '%' . $request->file_name . '%');
            })
            ->when($request->date_uploaded, function ($query) use ($request) {
                $dateFrom = date('Y-m-d 00:00:00');
                $dateTo = date('Y-m-d 23:59:59');

                if ($request->date_uploaded == 'yesterday') {
                    $dateFrom = date('Y-m-d 00:00:00', strtotime('-1 days'));
                    $dateTo = date('Y-m-d 23:59:59', strtotime('-1 days'));
                } else if ($request->date_uploaded == 'last_7_days') {
                    $dateFrom = date('Y-m-d 00:00:00', strtotime('-7 days'));
                    $dateTo = date('Y-m-d 23:59:59');
                } else if ($request->date_uploaded == 'last_30_days') {
                    $dateFrom = date('Y-m-d 00:00:00', strtotime('-30 days'));
                    $dateTo = date('Y-m-d 23:59:59');
                } else if ($request->date_uploaded == 'last_90_days') {
                    $dateFrom = date('Y-m-d 00:00:00', strtotime('-90 days'));
                    $dateTo = date('Y-m-d 23:59:59');
                } else if ($request->date_uploaded == 'custom') {
                    $dateFrom = date('Y-m-d 00:00:00', strtotime($request->date_uploaded_from));
                    $dateTo = date('Y-m-d 23:59:59', strtotime($request->date_uploaded_to));
                }

                $query->where('bookkeeping_documents.created_at', '>=', $dateFrom);
                $query->where('bookkeeping_documents.created_at', '<=', $dateTo);
            });

        return Datatables::of($documents)
            ->escapeColumns(['id'])
            // ->addColumn('checkbox', function ($document) {
            //     return '<input type="checkbox">';
            // })
            ->addColumn('file_name', function ($document) {
                $ext = pathinfo($document->file_name, PATHINFO_EXTENSION);

                return '
                    <div class="flex justify-start">
                        <img class="max-25" src="' . ( $ext == 'pdf' ? asset('themes/tailwind/images/pdf.svg') : asset('themes/tailwind/images/jpg.svg')) . '">
                        <span class="fix-text">' . $document->file_name . '</span>
                    </div>
                ';
            })
            ->addColumn('document_size', function ($document) {
                if (Storage::exists($document->file_path)) {
                    return '<span class="primary-text">' . round(Storage::size($document->file_path) / 1000) . 'KB</span>';
                }
                return '-';
            })
            ->addColumn('created_at', function ($document) {
                return date('Ymd-H:i', strtotime($document->created_at));
            })
            ->addColumn('actions', function ($document) {
                $viewAction = '<a class="primary-text" href="#">' . __("View") . '</a>';
                $propertiesAction = '<a class="primary-text" href="#">' . __("Properties") . '</a>';
                $downloadAction = '<a class="primary-text download-file" data-id="' . $document->id . '" href="' . $document->file_url . '" download>' . __("Download") . '</a>';
                $actions = $viewAction . '<span class="long-pipe">|</span>' . $propertiesAction . '<span class="long-pipe">|</span>' . $downloadAction;

                return $actions;
            })
            ->make(true);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'company_id' => 'required',
            'uploaded_file' => 'required',
            'bookkeeping_document_category_id' => 'required',
            'batch_name' => 'required',
            'remark' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }
        else {
            $bookkeepingDocument = BookkeepingDocument::create([
                'company_id' => $request->company_id,
                'user_id' => $request->user()->id,
                'batch_name' => $request->batch_name,
                'remark' => $request->remark,
                'bookkeeping_document_category_id' => $request->bookkeeping_document_category_id,
            ]);

            $fileName = '';
            if ($request->hasFile('uploaded_file')) {
                $file = $request->file('uploaded_file');
                $fileName = $request->file('uploaded_file')->getClientOriginalName();
                $file->storePubliclyAs($bookkeepingDocument->folder_path, $fileName);

                $bookkeepingDocument->file_name = $fileName;
                $bookkeepingDocument->save();
            }

            DocumentActionLogs::create([
                'user_id' => $request->user()->id,
                'event' => 'Upload',
                'description' => 'Upload [' . $fileName . '] from local file.',
                'status' => 'success',
            ]);
    
            return response()->json([
                'success' => true,
                'message' => __("Document has successfully uploaded!"),
            ]);
        }
    }

    public function export()
    {
        $documents = BookkeepingDocument::query()
            ->select(
                'bookkeeping_documents.id',
                'bookkeeping_documents.file_name',
                'companies.name_english',
                'companies.name_chinese',
                'bookkeeping_document_categories.name as category_name',
                'users.name as user_name',
                'bookkeeping_documents.created_at',
            )
            ->leftJoin('companies', 'bookkeeping_documents.company_id', '=', 'companies.id')
            ->leftJoin('users', 'bookkeeping_documents.user_id', '=', 'users.id')
            ->leftJoin('bookkeeping_document_categories', 'bookkeeping_documents.bookkeeping_document_category_id', '=', 'bookkeeping_document_categories.id')
            ->get();
        $fileName = 'bookkeeping-documents-' . date('mdY') . '.xls';
        return Excel::download(new BookkeepingDocumentLibraryExport($documents), $fileName, \Maatwebsite\Excel\Excel::XLS);
    }

    public function download(BookkeepingDocument $document)
    {
        DocumentActionLogs::create([
            'user_id' => auth()->user()->id,
            'event' => 'Download',
            'description' => 'Download [' . $document->file_name . '] to local.',
            'status' => 'success',
        ]);
    
        return response()->json([
            'success' => true,
        ]);
    }
}
