<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util\CodeGeneratorService;
use App\Models\RegisterPractitioner;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use PHPMailer\PHPMailer\PHPMailer;

class RegPaymentController extends Controller
{

    private $createdStatusCode = 201;
    private $successStatusCode = 200;
    private $errorStatusCode = 422;

    public function __construct() {
        $this->middleware('auth:api', ['except' => ['paystackWebhook']]);
    }

    public function paystackWebhook(Request $request) {
      Log::info("This is to check Paystack");
         // only a post with paystack signature header gets our attention
      if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) )
          exit();

      // Retrieve the request's body
      $input = @file_get_contents("php://input");
        define('PAYSTACK_SECRET_KEY', getenv('PAYSTACK_TEST_SECRET_KEY')); //Test Secret key
 //       define('PAYSTACK_SECRET_KEY', getenv('PAYSTACK_LIVE_SECRET_KEY')); //Live secret key


      // validate event do all at once to avoid timing attack
      if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
          exit();

      http_response_code(200);

      // parse event (which is json string) as object
      // Do something - that will not take long - with $event
      $event = json_decode($input);
        //Log::info(json_encode($event));

      if($event->data->status == "success") {

          if($event->data->metadata->paymentFor == "Registration") {

              $getUserId = $event->data->metadata->userId;
              $userObj = User::find($getUserId);
              $reference = $event->data->reference;
              $amount = ($event->data->amount) / 100;

              $registerPay = new RegisterPractitioner();
              $registerPay->payment_for = $event->data->metadata->paymentFor;
              $registerPay->reg_pay_status = "paid";
              $registerPay->reference_id = $reference;
              $registerPay->reg_price = $amount;
              $userObj->registerPractitioner()->save($registerPay);
              $registerNumber = CodeGeneratorService::generateRegisterV2();
              User::where('id', $getUserId)->update(['registration_number' => $registerNumber]);

              $templateData = [
                  'name' => $userObj->first_name,
                  'register' => $registerNumber
              ];
              $templateContent = view('registertemplate', $templateData)->render();
              $this->composeEmailV2('Confirmation of Registration!', $userObj->email,  $templateContent);
          }
      }

      exit();

    }

    public function getUserPayment(Request $request) {

        $userId = Auth::user()->id;
        $keyword = $request->input('search');

        $getUserPayment = RegisterPractitioner::where('user_id', (string)$userId)
                        ->where(function ($query) use ($keyword) {
                            $query->where('payment_for', 'like', '%' . $keyword . '%')
                                ->orWhere('reference_id', 'like', '%' . $keyword . '%');
        })->orderBy('created_at', 'desc')->paginate(5);

        if($getUserPayment->isEmpty()) {
            return response()->json(['data' => 'No data available' ], $this->errorStatusCode);
        } else {
            return response()->json(['data' => $getUserPayment], $this->successStatusCode);
        }
    }

//    private static function generateRegister() {
//
//        $static = 'LASWARCO';
//        $datepart = Carbon::now()->format('Ymd');
//        $autopart = Carbon::now()->format('His');
//        return $static.'/'.$autopart.'/'.$datepart;
//    }

    public function composeEmailV2($subject, $userEmail, $emailContent) {

        require base_path('vendor/autoload.php');


        $mail = new PHPMailer(true);
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = 'ssl://business74.web-hosting.com'; //ssl://smtp.gmail.com
        $mail->SMTPAuth = true;
        $mail->Username = 'noreply@laswarco.lg.gov.ng';
        $mail->Password = 'SH7ZL,&^^pCL';
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;
        $mail->setFrom('noreply@laswarco.lg.gov.ng', 'Laswarco');
        $mail->addAddress($userEmail);
        $mail->addReplyTo('noreply@laswarco.lg.gov.ng', 'Laswarco');

        $mail->isHTML(true);

        $mail->Subject = $subject;
        $mail->Body = $emailContent;
        $mail->send();
    }
}
