<?php

namespace App\Http\Controllers;

use App\DataTables\MyDataTable;
use App\dev\extras;
use App\PubDate;
use Illuminate\Http\Request;
use App\advert;
use App\payment;
use App\Mail\pingAdmin;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{

    use extras;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return redirect('myservice/create');
    }

    public function create(MyDataTable $dataTable)
    {
        $size = DB::table('pub_sizes')->select('*')->get();
        $cat  = DB::table('categories')->select('*')->get();
        $get  = DB::table('adverts')
            ->join('pub_sizes', 'adverts.size', 'pub_sizes.id')
            ->join('categories', 'adverts.cat_id', 'categories.cat_id')
            ->select('adverts.*', 'pub_sizes.p_size', 'pub_sizes.location', 'pub_sizes.cost', 'categories.cat_name')
            ->where('adverts.belong', Auth::user()->id)->paginate(4);
        $dates = PubDate::query()->where('state',1)->get();
        return $dataTable->render('users.advert', compact('get', 'size', 'cat','dates'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'media' => 'file|max:2000',
        ]);


        $newDate = date_create($request->pub_date);

        $ad = new advert;
        $ad->belong  = Auth::user()->id;
        $ad->cat_id  = $request->cat_id;
        $ad->format  = $request->p_type;
        $ad->size    = $request->size;
        $ad->amt_tbp =$request->cost;
        $ad->date1   = $newDate;

//        dd($request->cost);

        if ($request->hasFile('media')) {
            $mime = $request->file('media')->getMimeType();
            if ($mime == 'image/jpeg' || $mime == 'application/pdf' || $mime == 'image/jpg' || $mime == 'image/png') {
                $filename = Auth::user()->phone . '_' . $request->media->hashName();
                $request->media->storePubliclyAs('public/avatars', $filename);
                $ad->media = $filename;
            } else {
                return redirect()->back()->with('error', 'File must be either jpeg jpg png or pdf !!!');
            }
        }


        $msg = ('A new request has been made on Kwik Advertizer');  //body of the message
//        $userphone  = '0203450921'; // must be replaced with the admins phone number
        $num ='0261701321'; // must be replaced with the admins phone number

        $name = Auth::user()->name;
        $email = Auth::user()->email;
        $message = 'You have a new request to attend to from ' . $name;
        $subject = "New Request";
        
        try{
            mail::send(new pingAdmin($name, $email, $message, $subject));
            session()->flash('message', 'Mail Successfully Sent');
        }
        catch(\Exception $e){}

        $ad->save();

        $this->sendSms($num,$msg);

        return redirect()->back()->with('data', 'Request Successfully');

    }


    private function sendSms($userphone,$msg)
    {
        $message = urlencode($msg);
        $num = urlencode($userphone);

        $url = "https://deywuro.com/api/sms?username=sammy&password=password&source=KwikAd&destination=" . $num . "&message=" . $message;

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_exec($curl);
        curl_close($curl);
    }

        //fecthing results for editing for the user
    public function edit($id)
    {
        $size = DB::table('pub_sizes')->select('*')->get();
        $cat = DB::table('categories')->select('*')->get();
        $get = advert::query()
            ->where([['adverts.belong', Auth::user()->id], ['adverts.id', $id]])->first();

        $dates = PubDate::query()->where('state',1)->get();
        return view('users.edit', compact('size', 'get', 'cat','dates'));
    }


    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'media' => 'file|max:2000',
        ]);
//        $money = DB::table('pub_sizes')->where('id',$request->size)->select('cost')->first();

        $newDate = date_create($request->pub_date);

        $update = advert::query()->find($id);

        $update->cat_id = $request->cat_id;
        $update->size = $request->size;
        $update->format  = $request->p_type;
        $update->date1 = $newDate;
        $update->amt_tbp = $request->cost;;
        $update->pay_code = 'pending';
        $update->clear = '0';
        $update->status = 'pending';
        $oldImage = $update->media;



        if ($request->hasFile('media')) {
            $mime = $request->file('media')->getMimeType();
            if ($mime == 'image/jpeg' || $mime == 'application/pdf' || $mime == 'image/jpg' || $mime == 'image/png') {
                $media = $request->file('media');
                $filename = Auth::user()->phone . '_' . $media->hashName();
                $media->storePubliclyAs('public/avatars', $filename);
                $update->media = $filename;
                Storage::delete('public/avatars/' . $oldImage);
            } else {
                return redirect()->back()->with('error', 'File must be either jpeg jpg  png or pdf !!!');
            }
        }
      // toastr["error"]("I was launched via jQuery!");
        $update->save();
        return redirect()->back()->with('response', 'Update Captured');
    }

    public function pay_check(Request $request)
    {
        $get = DB::table('adverts')->join('users', 'adverts.belong', 'users.id')
            ->select('adverts.*')
            ->where([
                ['users.email', Auth::user()->email],
                ['adverts.pay_code', $request->pay_code],
                ['adverts.pay_code', '!=', '0000'],
                ['adverts.pay_code', '!=', 'pending'],
                ['adverts.clear', '=', '0']
            ])->first();
        return response()->json($get);
    }

    //payment controller
    public function mm_money(Request $request)
    {
        $length = 5;
        $ss = substr(str_shuffle(str_repeat($x = 'ABCDEFGHabcdefghijklmnopIJKLMNOPQRSTUVWXYZ123456789', ceil($length / strlen($x)))), 1, $length);
        $pay_code = $request->hashed_id;
        $tran_id = $request->hashed_id . '' . $ss;  //the unique code
        $vendor = $request->vendor;     //vendor
        $endpoint = $request->endpoint;   //mobile number
        $amount = $request->cost;        //amount debiting

        //insert into  the payments table before processing the transaction
         $updatePayment = new payment;
         $updatePayment->p_code      =  $pay_code;
         $updatePayment->mm_number   =  $endpoint;
         $updatePayment->amount      =  $amount;
         $updatePayment->trans_id    =  $tran_id;
         $updatePayment->user_id     =  Auth::user()->id;
         $updatePayment->save();

        $paymentEndpoint =
            "http://pay.npontu.com/api/pay";
        $callbackResponseUrl = "http://kwikadvertiser.npontu.com/api/payment/post";
        $request = array(
            'number' => $endpoint,
            'vendor' => $vendor,
            'uid' => 'kwikadvertizer',
            'pass' => '5b507721cc073',
            'tp' => $tran_id,
            'cbk' => $callbackResponseUrl,
            'amt' => $amount,
            'msg' => 'KWIK ADVERTIZER',
            'vou' => '',
            'trans_type' => 'Debit'
        );
        $ch = curl_init($paymentEndpoint);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        $decode = json_decode($output);
    }

    public function api_response(Request $request)
    {
        //update the payment table with any response fetched from the call back api, this determines whether or not the
        //transaction was successfull or failed

        $api_update = payment::where('trans_id', $request->transaction_id)->first();
        $api_update->p_status = $request->status;
        $api_update->res_mes =  $request->responseMessage;
        $api_update->save();

        $mm_number = $api_update->mm_number;
        $amount    = $api_update->amount;
        $pcode    = $api_update->p_code;


        if ($request->status != 'Failed') {
            $updated_at = date("Y-m-d h:i:s", strtotime('1 day'));
            DB::table('adverts')->join('payments', 'adverts.pay_code', 'payments.p_code')
                ->where('payments.trans_id', $request->transaction_id)
                ->update(['adverts.clear' => '1', 'adverts.updated_at' => $updated_at]);

            $message = "The number " .$mm_number . " has made a payment of " . $amount. " with payment code " .$pcode;

        } else if ($request->status == 'Failed') {
            DB::table('adverts')->join('payments', 'adverts.pay_code', 'payments.p_code')
                ->where('payments.trans_id', $request->transaction_id)
                ->update(['adverts.clear' => '0']);

            $message = "The number " .$mm_number . " initiated payment with payment code " .$pcode. " and amount " . $amount. " but was not successful";
        }



        $num  = urlencode('0261701321'); // must be replaced with the admins phone number

        try {
            $client = new Client();
            $response = $client->request('GET', 'http://api.deywuro.com/bulksms', [

                'query' => [
                    'username' => 'sammy',
                    'password' => 'password',
                    'type' => '0',
                    'dlr' => '1',
                    'destination' => $num,
                    'source' => 'Kwik Pay',
                    'message' => $message
                ]
            ]);
        } catch (\Exception $e) {}

        $name = "KWIK ADVERTIZER";
        $email = "support@npontu.com";
        $subject = 'KWIK PAY ALERT';
        mail::send(new pingAdmin($name, $email, $message, $subject));
    }

    public function pay()
    {
        return view('users.payment');
    }

    public function ping_admin(Request $request)
    {
        $name = $request->user;
        $email = $request->email;
        $message = $request->message;
        $subject = $request->subject;

        mail::send(new pingAdmin($name, $email, $message, $subject));
        session()->flash('message', 'Mail Successfully Sent');
        return redirect()->back();

    }

}








 





