<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Session;
use App\Http\Requests;
use App\Libs\PaperLessNgx;


class GeneralDocumentsController extends Controller
{
    public function index(){
        $document_arr = \DB::table('general_documents')
            ->select(\DB::raw('count(*) as docs_count, category'))
            ->groupBy('category')
            ->get();

        $client_docs = \DB::table('client_files')
            ->join('clients', 'clients.id', '=', 'client_files.client_id')
            ->select(\DB::raw('count(*) as docs_count, clients.name, client_files.client_id'))
            ->groupBy('clients.name', 'client_files.client_id')
            ->get();

        $mno_docs = \DB::table('mno_files')
            ->join('network_operators', 'network_operators.id', '=', 'mno_files.mno_id')
            ->select(\DB::raw('count(*) as docs_count, network_operators.name, mno_files.mno_id'))
            ->groupBy('network_operators.name', 'mno_files.mno_id')
            ->get();

        $category_names = [
            'api' => 'API Documents',
            'airtime' => 'Click Airtime',
            'presentations' => 'Presentations',
            'rates' => 'SMS/Voice Rates',
            'scfees' => 'Short Code Fees',
            'vpn_forms' => 'VPN Forms',
            'user_guides' => 'User Guides',
            'sidwl' => 'SID Whitelisting Letter',
            'others' => 'Others'
        ];
        $data = [
            'page_title' => 'All Documents',
            'document_arr' => $document_arr,
            'category_names' => $category_names,
            'current_user' => session('current_user'),
            'client_docs' => $client_docs,
            'mno_docs' => $mno_docs
        ];
        return view('generaldocuments.index', $data);
    }
    public function listcategory($category){
        //$document_arr = new Models\GeneralDocument;
        // dd($category);
        $data = [
            'page_title' => ucfirst($category) .  ' Documents',
            'current_user' => session('current_user'),
            'category' => $category
        ];
        return view('generaldocuments.list-index', $data);
    }

    public function getDocumentsJson(Request $request)
    {
        #$this->log_query();
        $document_arr = \DB::table('general_documents')
            ->join('auth_users', 'auth_users.id', '=', 'general_documents.uploaded_by')
            ->select('general_documents.id', 'general_documents.name', 'general_documents.filename', 'auth_users.name AS UploadedBy', 'general_documents.created_at')
            ->orderBy('general_documents.name', 'ASC')
            ->paginate(15);

        if($request->has('keyword')){
            $keyword = $request->keyword;
            $document_arr = \DB::table('general_documents')
            ->join('auth_users', 'auth_users.id', '=', 'general_documents.uploaded_by')
            ->select('general_documents.id', 'general_documents.name', 'general_documents.filename', 'auth_users.name AS UploadedBy', 'general_documents.created_at')
            ->orderBy('general_documents.name', 'ASC')
            ->whereRaw("general_documents.name LIKE '%$keyword%' OR general_documents.description LIKE '%$keyword%' OR general_documents.filename LIKE '%$keyword%' OR auth_users.name LIKE '%$keyword%'")
            ->paginate(15);
        }
        return response()->json($document_arr);
    }
    public function getDocumentsCategoryJson(Request $request)
    {
        //$this->log_query();
        $category = $request->category;
        $document_arr = \DB::table('general_documents')
            ->join('auth_users', 'auth_users.id', '=', 'general_documents.uploaded_by')
            ->select('general_documents.id', 'general_documents.name', 'general_documents.filename', 'auth_users.name AS UploadedBy', 'general_documents.created_at')
            ->where('general_documents.category', $category)
            ->orderBy('general_documents.name', 'ASC')
            ->paginate(15);

        if($request->has('keyword')){
            $keyword = $request->keyword;
            $document_arr = \DB::table('general_documents')
            ->join('auth_users', 'auth_users.id', '=', 'general_documents.uploaded_by')
            ->select('general_documents.id', 'general_documents.name', 'general_documents.filename', 'auth_users.name AS UploadedBy', 'general_documents.created_at')
            ->orderBy('general_documents.name', 'ASC')
            ->where('general_documents.category', $category)
            ->whereRaw("general_documents.name LIKE '%$keyword%' OR general_documents.description LIKE '%$keyword%' OR general_documents.filename LIKE '%$keyword%' OR auth_users.name LIKE '%$keyword%'")
            ->paginate(15);
        }
        return response()->json($document_arr);
    }
    public function create(){
        $categories = [
            'sidwl' => 'Sender ID Whitelisting Letter',
            'api' => 'API Docs',
            'airtime' => 'Click Airtime',
            'rates' => 'Rates',
            'scfees' => 'Short Code Fees',
            'presentations' => 'presentations',
            'vpn_forms' => 'VPN Forms',
            'user_guides' => 'User Guides',
            'others' => 'Others'
        ];

        $data = [
            'page_title' => 'Upload Document',
            'categories' => $categories
        ];
        return view('generaldocuments.create', $data);
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Requests\GeneralDocumentsRequest $request){
      // dd($request->all());
        $paperless = new PaperLessNgx();
        if ($request->has('document_one') && $request->has('document_one_name') && $request->has('document_one_category')) {
            if ($request->file('document_one')->isValid()) {
              //dd($request->all());
                $filename = "erp_" . time() . str_random(4) . "." . $request->document_one->extension();
                $request->document_one->storeAs('general_files', $filename, 'public');
                $document_arr['filename'] = $filename;
                $document_arr['category'] = $request->document_one_category;

                #sendToPaperLess
                $store_location = "general_files";
                #$top = $paperless->processPaperlessFile($request->document_one_name, $request->document_one_category, $filename, $store_location);

                $document_arr['file_extension'] = $request->document_one->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = $request->document_one_name;
                $document_arr['uploaded_by'] = session('current_user.id');
                $result = Models\GeneralDocument::create($document_arr);
            }
        }
        if ($request->has('document_two') && $request->has('document_two_name') && $request->has('document_two_category')) {
            if ($request->file('document_two')->isValid()) {
                $filename = "erp_" . time() . str_random(4) . "." . $request->document_two->extension();
                $request->document_two->storeAs('general_files', $filename, 'public');
                $document_arr['filename'] = $filename;
                $document_arr['category'] = $request->document_two_category;

                #sendToPaperLess
                $store_location = "general_files";
                #$top = $paperless->processPaperlessFile($request->document_two_name, $request->document_two_category, $filename, $store_location);

                $document_arr['file_extension'] = $request->document_two->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = $request->document_two_name;
                $document_arr['uploaded_by'] = session('current_user.id');
                $result = Models\GeneralDocument::create($document_arr);
            }
        }
        if ($request->has('document_three') && $request->has('document_three_name') && $request->has('document_three_category')) {
            if ($request->file('document_three')->isValid()) {
                $filename = "erp_" . time() . str_random(4) . "." . $request->document_three->extension();
                $request->document_three->storeAs('general_files', $filename, 'public');
                $document_arr['filename'] = $filename;
                $document_arr['category'] = $request->document_three_category;

                #sendToPaperLess
                $store_location = "general_files";
                #$top = $paperless->processPaperlessFile($request->document_three_name, $request->document_three_category, $filename, $store_location);

                $document_arr['file_extension'] = $request->document_three->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = $request->document_three_name;
                $document_arr['uploaded_by'] = session('current_user.id');
                $result = Models\GeneralDocument::create($document_arr);
            }
        }
        Session::flash('success_message', 'Document(s) successfully uploaded');
        return redirect(url('generaldocuments'));
    }
    public function storeBak(Request $request){
        $request->validate([
            'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
        ]);

        $fileName = time().'.'.$request->file->extension();

        $request->file->move(public_path('uploads'), $fileName);

        return back()
            ->with('success','You have successfully uploaded the file.');
    }
    public function edit($id){
        $document = Models\GeneralDocument::findOrFail($id);
        $data = [
            'page_title' => 'Update Document',
            'document' => $document
        ];
        return view('generaldocuments.edit', $data);
    }
    public function update(Request $request, $id){
        $document = Models\GeneralDocument::findOrFail($id);
        if ($request->has('document_one')) {
            if ($request->file('document_one')->isValid()) {
               $filename = "erp_" . time() . str_random(6) . "." . $request->document_one->extension();
                $request->document_one->storeAs('general_files', $filename, 'public');
                $document->filename = $filename;
                $document->file_extension = $request->document_one->extension();
                $document->file_reff = time() . uniqid();
            }
        }
        $document->uploaded_by = session('current_user.id');
        $document->name = $request->name;
        $document->save();
        Session::flash('success_message', 'Document successfully Updated');
        return redirect(url('generaldocuments'));
    }
    public function getDocument($id){
        $general_file = Models\GeneralDocument::find($id);
        if (!$general_file) {
            return redirect(url('generaldocuments'));
        }
        //PDF file is stored under project/public/download/info.pdf
        $file = public_path('documents/general_files/') .  $general_file->filename;

        $headers = [];  //['Content-Type: application/pdf'];
        $filename = $general_file->name; // . "_" . $general_file->file_reff;
        $filename = $this->cleanStr($filename);
        $filename = $filename . "_Click_ERP_FILE" . "." . $general_file->file_extension;
        return \Response::download($file, $filename, $headers);
    }
    public function cleanStr($string){
        // Replaces all spaces with hyphens.
        $string = str_replace(' ', '-', $string);

        // Removes special chars.
        $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
        // Replaces multiple hyphens with single one.
        $string = preg_replace('/-+/', '_', $string);

        return $string;
    }

}
