<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Session;
use Illuminate\Support\Facades\File;


class SupportTicketsController extends Controller
{
    //
    public function index(){
        $data = [
            'page_title' => 'Support Tickets Home',
            'current_user' => session('current_user')
        ];
        return view('support-ticket.landing', $data);
    }
    public function ticketlist(){
        $data = [
            'page_title' => 'Support Tickets List',
            'current_user' => session('current_user')
        ];
        return view('support-ticket.index', $data);
    }
    public function getSuppoerTicketJson(Request $request)
    {
        #$this->log_query();
        $supportticket_arr = \DB::table('support_tickets')
            ->join('staff_members AS staffcreate', 'staffcreate.id', '=', 'support_tickets.created_by_id')
            ->join('staff_members AS assignedTo', 'assignedTo.id', '=', 'support_tickets.assigned_to_id')
            // ->join('network_operators', 'network_operators.id', '=', 'support_tickets.network_id')
            // ->join('clients', 'clients.id', '=', 'support_tickets.client_id')
            ->select('support_tickets.id', 'support_tickets.case_number',  'support_tickets.subject', 'support_tickets.body', 'support_tickets.created_by_id', 'support_tickets.status', 'support_tickets.created_at', 'support_tickets.assigned_to_id', 'staffcreate.name As createdBy', 'assignedTo.name AS assignedToName')
            ->orderBy('support_tickets.id', 'ASC')
            ->paginate(15);

        if($request->has('keyword')){
            $queries = [];
            $keyword = $request->keyword;
            $queries['keyword'] = $keyword;

            $supportticket_arr = \DB::table('support_tickets')
            ->join('staff_members AS staffcreate', 'staffcreate.id', '=', 'support_tickets.created_by_id')
            ->join('staff_members AS assignedTo', 'assignedTo.id', '=', 'support_tickets.assigned_to_id')
            ->select('support_tickets.id', 'support_tickets.case_number', 'support_tickets.subject', 'support_tickets.body', 'support_tickets.created_by_id', 'support_tickets.status', 'support_tickets.created_at', 'support_tickets.assigned_to_id', 'staffcreate.name As createdBy', 'assignedTo.name AS assignedToName')
            ->whereRaw("support_tickets.case_number LIKE '%$keyword%' OR assignedTo.name LIKE '%$keyword%' OR support_tickets.status LIKE '%$keyword%' OR support_tickets.body LIKE '%$keyword%' OR staffcreate.name LIKE '%$keyword%' OR support_tickets.created_at LIKE '%$keyword%'")
            ->orderBy('support_tickets.id', 'ASC')
            ->paginate(15)->appends($queries);
        }
        return response()->json($supportticket_arr);
    }
    public function create()
    {
        #$network_arr = Models\NetworkOps::pluck('name','country');

        $networks = \DB::table('network_operators')->Select(\DB::raw('concat(name, " (", country, ")") AS networkvalue, concat(name, " (", country, ")") AS network'))->orderBy('network')->get()->toArray();
        $network_arr = array_pluck($networks, 'network', 'networkvalue');
        $direct_mno_arr = ['YES' => 'YES', 'NO' => 'NO'];

        // dd($network_arr);
        #$network_arr = array_combine($network_arr, $network_arr);


        // $clients = Models\Client::pluck('name', 'name');
        $clients = \DB::table('clients')->Select(\DB::raw('concat(name, " (", country, ")") AS clientvalue, concat(name, " (", country, ")") AS client'))->orderBy('client')->get()->toArray();
        $client_arr = array_pluck($clients, 'client', 'clientvalue');
        $staffmembers = Models\StaffMember::pluck('name', 'id');
        #$status = ['Pending' => 'Pending', 'Inactive' => 'Inactive', 'Approved' => 'Approved'];
        #$status = ['Applied to MNO', 'Applied to Aggregator', 'Approved on MNO', 'Approved on Aggregator', 'Active', 'InActive'];
        $status = [
            'Applied to MNO' => 'Applied to MNO', 
            'Applied to Aggregator' => 'Applied to Aggregator', 
            'Approved on MNO' => 'Approved on MNO', 
            'Approved on Aggregator' => 'Approved on Aggregator', 
            'Active' => 'Active', 
            'Inactive' => 'InActive'
        ];

        $data = [
            'page_title' => 'Create Sender ID',
            'network_arr' => $network_arr,
            'status' => $status,
            'clients' => $client_arr,
            'direct_mno_arr' => $direct_mno_arr,
            'staffmembers' => $staffmembers
        ];
        // dd($data);
        return view('support-ticket.create', $data);
    }
    public function store(Request $request)
    {
        $request->validate([
            'subject' => 'sometimes',
            'body' => 'required',
            'attachment' => 'sometimes',
            //max:10240|mimes:png,jpg,jpeg,bmp,pdf,doc,docx,xlx,xlsx,pptx,ppt
        ]);
        // dd($request->all());
        //Generate case number here
        $case_number = "ERP-" . date('Y-m-d-') . time();  
        $ticket_arr = $request->except('_token');
        $ticket_arr['case_number'] = $case_number;
        $ticket_arr['assigned_to_id'] = 1; // change this
        $ticket_arr['created_by_id'] = session('current_user.id'); // change this

        $result = Models\SupportTicket::create($ticket_arr);

        if ($request->attachment !== null) {
            if ($request->file('attachment')->isValid()) {
              //dd($request->all());
                $filename = "erp_" . time() . str_random(4) . "." . $request->attachment->extension();
                $request->attachment->storeAs('supportticket_files', $filename, 'public');
                $document_arr['filename'] = $filename;
                
                $document_arr['file_extension'] = $request->document_one->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['case_number'] = $case_number;
                $document_arr['uploaded_by'] = session('current_user.id');

                $result = Models\SupportTicketsDocument::create($document_arr);
            }
        }
        Session::flash('success_message', 'Support Ticket successfully created');
        return redirect(url('supporttickets/list'));
    }
    public function edit($id){
        $support_ticket = Models\SupportTicket::findOrFail($id);      
    
        $data = [
            'page_title' => 'Edit Support',
            'support_ticket' => $support_ticket,
        ];
        return view('support-ticket.edit', $data);
    }
    public function update(Request $request, $id)
    {

        $request->validate([
            'subject' => 'sometimes',
            'body' => 'required',
            'attachment' => 'sometimes',
        ]);
        
        $support_ticket = Models\SupportTicket::findOrFail($id);
        
        $support_ticket->body = $request->body;
        $support_ticket->body = $request->subject;

        $support_ticket->save();

        Session::flash('success_message', 'Support Ticket successfully Updated');
        return redirect(url('supporttickets/list'));
    }
    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('supporttickets/list'));
    }
    public function filesUpdate(Request $request)
    {
        $request->validate([
            'document_one_name' => 'required',
            'id' => 'required',
            'validity_period_one' => 'sometimes',
            '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;
        $document->validity_period = $request->validity_period_one;
        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('supporttickets/list'));
    }

    public function show_edit_files_form($id){
        $document = Models\BranchFile::findOrFail($id);
        $data = [
            'page_title' => 'Update Document',
            'document' => $document
        ];
        return view('supporttickets.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;
    }
}
