<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models;
use App\Http\Requests;
use Session;

class OfficeLocationsController extends Controller
{
    public function index(){
        // $offices_arr = new Models\OfficeLocation;
        $offices_arr = Models\OfficeLocation::with( 'created_by_info', 'country_manager_info')->orderBy('country', 'ASC')->paginate(15);
        $data = [
            'page_title' => 'Office Locations',
            'offices_arr' => $offices_arr,
            'current_user' => session('current_user')
        ];
        // dd($offices_arr->isEmpty());
        return view('officelocations.index', $data);
    }
    public function showfiles($id){
        $branch_files = Models\BranchFile::where('branch_id', $id)->get();
        $data = [
            'page_title' => 'Branch Documents',
            'current_user' => session('current_user'),
            'branch_id' => $id
        ];
        return view('officelocations.documents', $data);
    }
    public function getBranchFilesJson(Request $request)
    {
        $id = $request->branch_id;
        $document_arr = \DB::table('branch_files')
            ->join('auth_users', 'auth_users.id', '=', 'branch_files.uploaded_by')            
            ->select('branch_files.id', 'branch_files.name', 'branch_files.validity_period','branch_files.file_reff', 'auth_users.name AS UploadedBy', 'branch_files.created_at')
            ->orderBy('branch_files.name', 'ASC')
            ->where('branch_files.branch_id', $id)
            ->paginate(15);

        if($request->has('keyword')){
            $keyword = $request->keyword;
            $document_arr = \DB::table('branch_files')
            ->join('auth_users', 'auth_users.id', '=', 'branch_files.uploaded_by')            
            ->select('branch_files.id', 'branch_files.name', 'branch_files.validity_period', 'branch_files.file_reff', 'auth_users.name AS UploadedBy', 'branch_files.created_at')
            ->orderBy('branch_files.name', 'ASC')
            ->where('branch_files.branch_id', $id)
            ->whereRaw("branch_files.name LIKE '%$keyword%' OR branch_files.description LIKE '%$keyword%' OR branch_files.filename LIKE '%$keyword%' OR auth_users.name LIKE '%$keyword%'")
            ->paginate(15);         
        }
        return response()->json($document_arr);
    }
    public function create()
    {
        $countries = Models\Country::pluck('en_short_name','en_short_name');
        $staffmembers = Models\StaffMember::pluck('name', 'id');        
        $data = [
            'page_title' => 'Add Office Location',
            'countries' => $countries,
            'staffmembers' => $staffmembers
        ];
        return view('officelocations.create', $data);
    }
    public function createfiles($id)
    {
        //$auth_users = Models\SystemUser::pluck('name', 'id');         
        $data = [
            'page_title' => 'Upload Document',           
            'branch_id' => $id
        ];
        // dd($data);
        return view('officelocations.filescreate', $data);
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'street_name' => 'sometimes',
            'physical_address' => 'required',
            'postal_address' => 'required',
            'block_number' => 'sometimes',
            'city_town' => 'required',
            'country' => 'required|unique:office_locations,country',
            'country_manager_id' => 'required',
            'office_phone' => 'required'
        ]);
        $flag = Models\CountryFlag::where('country', $request->country)->first();
        if ($flag) {
            $flag_url = $flag->url;
        }
        else{
            $flag_url = "https://via.placeholder.com/100x60";
        }
        $office_arr = $request->except('_token');
        $office_arr['user_id'] = session('current_user.id');

        $office_arr['flag_url'] = $flag_url;
        $result = Models\OfficeLocation::create($office_arr);
        Session::flash('success_message', 'Office Location successfully added');
        return redirect(url('officelocations'));
    }
    public function edit($id){
        $office = Models\OfficeLocation::findOrFail($id);

        $countries = Models\Country::pluck('en_short_name','en_short_name');
        $staffmembers = Models\StaffMember::pluck('name', 'id');      
    
        $data = [
            'page_title' => 'Edit Office Location',
            'countries' => $countries,
            'staffmembers' => $staffmembers,
            'officelocation' => $office
        ];
        return view('officelocations.edit', $data);
    }
    public function update(Request $request, $id)
    {

        $request->validate([
            'street_name' => 'sometimes',
            'physical_address' => 'required',
            'postal_address' => 'required',
            'block_number' => 'sometimes',
            'country' => 'sometimes',
            'city_town' => 'required',
            'country_manager_id' => 'required',
            'office_phone' => 'required'
        ]);
        
        $office = Models\OfficeLocation::findOrFail($id);
        
        $office->street_name = $request->street_name ?? "";
        $office->physical_address = $request->physical_address;
        $office->postal_address = $request->postal_address;
        $office->block_number = $request->block_number;
        $office->country = $request->country;
        $office->country_manager_id = $request->country_manager_id;
        $office->office_phone = $request->office_phone;

        $office->save();

        Session::flash('success_message', 'Office Location details successfully Updated');
        return redirect(url('officelocations'));
    }
    public function fileStore(Requests\BranchFilesRequest $request)
    {
        
        if ($request->has('document_one') && $request->has('document_one_name')) {
            if ($request->file('document_one')->isValid()) {
                $filename = "erp_" . time() . str_random(6) . "." . $request->document_one->extension();
                $request->document_one->storeAs('branch_files', $filename, 'public');
                $document_arr['filename'] = $filename;
                $document_arr['branch_id'] = $request->branch_id;
                $document_arr['file_path'] = $filename;

                $document_arr['file_extension'] = $request->document_one->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = $request->document_one_name;
                $document_arr['validity_period'] = $request->validity_period_one;
                $document_arr['uploaded_by'] = session('current_user.id');
                $result = Models\BranchFile::create($document_arr);
            }
        }
        if ($request->has('document_two') && $request->has('document_two_name')) {
            if ($request->file('document_two')->isValid()) {
               $filename = "erp_" . time() . str_random(6) . "." . $request->document_two->extension();
                $request->document_two->storeAs('branch_files', $filename, 'public');
                $document_arr['filename'] = $filename;
                $document_arr['branch_id'] = $request->branch_id;
                $document_arr['file_path'] = $filename;

                $document_arr['file_extension'] = $request->document_two->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = $request->document_two_name;
                $document_arr['validity_period'] = $request->validity_period_two;
                $document_arr['uploaded_by'] = session('current_user.id');
                $result = Models\BranchFile::create($document_arr);
            }
        }
        if ($request->has('document_three') && $request->has('document_three_name')) {
            if ($request->file('document_three')->isValid()) {
               $filename = "erp_" . time() . str_random(6) . "." . $request->document_three->extension();
                $request->document_three->storeAs('branch_files', $filename, 'public');
                $document_arr['filename'] = $filename;
                $document_arr['branch_id'] = $request->branch_id;
                $document_arr['file_path'] = $filename;

                $document_arr['file_extension'] = $request->document_three->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = $request->document_three_name;
                $document_arr['validity_period'] = $request->validity_period_third;
                $document_arr['uploaded_by'] = session('current_user.id');
                $result = Models\BranchFile::create($document_arr);
            }
        }              
        Session::flash('success_message', 'Document(s) successfully uploaded');
        return redirect(url('officelocations'));
    }
    public function filesUpdate(Request $request)
    {
        $request->validate([
            'document_one_name' => 'required',
            'id' => 'required',
            'document_one' => 'max:10240|mimes:png,jpg,jpeg,bmp,pdf,doc,docx,xlx,xlsx,pptx,ppt',
        ]);
        $document = Models\BranchFile::findOrFail($request->id);
        $document->name = $request->document_one_name;
        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('branch_files', $filename, 'public');
                $document->file_path = $filename;          

                $document->file_extension = $request->document_one->extension();
                $document->file_reff = time() . uniqid();
                //$document->name = $request->document_one_name;
                $document->uploaded_by = session('current_user.id');
            }   
        }        
        $result = $document->save();
        Session::flash('success_message', 'Document(s) successfully updated');
        return redirect(url('officelocations'));
    }

    public function show_edit_files_form($id){
        $document = Models\BranchFile::findOrFail($id);
        $data = [
            'page_title' => 'Update Document',
            'document' => $document
        ];
        return view('officelocations.filesedit', $data);
    }
    
    public function getDocument($id)
    {
        $branch_file = Models\BranchFile::with('branch_info')->findOrFail($id);
        
        $file = public_path('documents/branch_files/') .  $branch_file->file_path;
        
        $headers = [];  //['Content-Type: application/pdf'];
        $filename = $branch_file->branch_info->name . "_" . $branch_file->name;
        $filename = $this->cleanStr($filename);
        $filename = $filename  . "." . $branch_file->file_extension;

        // $filename = str_replace(' ', '_', $filename);
        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;
    }
}
