# All files / controllers PaymentGatewayController.js

0% Statements 0/299
0% Branches 0/192
0% Functions 0/10
0% Lines 0/298

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    900
    901
    902
    903
    904
    905
    906
    907
    908
    909
    910
    911
    912
    913
    914
    915
    916
    917
    918
    919
    920
    921
    922
    923
    924
    925
    926
    927
    928
    929
    930
    931
    932

     /**
     * Payment Gateway Controller
     * Manages payment gateway configurations
     */

    const BaseController = require('./BaseController');
    const { pool } = require('../config/database');
    const { logger } = require('../config/logger');

    class PaymentGatewayController extends BaseController {
      /**
       * Get all payment gateways configuration
       * GET /api/superadmin/payment-gateways
       */
      static async getAllGateways(req, res) {
        try {
          const [gateways] = await pool.execute(
            'SELECT * FROM payment_gateway_settings'
          );

          const gatewaysMap = {
            stripe: null,
            paypal: null,
            cash: null
          };

          gateways.forEach(gateway => {
            gatewaysMap[gateway.gateway_name] = gateway;
          });

          return res.json({
            success: true,
            data: gatewaysMap
          });
        } catch (error) {
          logger.error('Error getting payment gateways', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error loading payment gateways'
          });
        }
      }

      /**
       * Update gateway settings
       * PUT /api/superadmin/payment-gateways/:gateway
       */
      static async updateGateway(req, res) {
        try {
          const { gateway } = req.params;
          const updates = req.body;

          logger.info('Update gateway request', { gateway, updates });

          // Validate gateway name
          if (!gateway || !['stripe', 'paypal', 'cash'].includes(gateway)) {
            return res.status(400).json({
              success: false,
              message: 'Invalid gateway name'
            });
          }

          // Check if gateway exists
          const [existing] = await pool.execute(
            'SELECT id FROM payment_gateway_settings WHERE gateway_name = ?',
            [gateway]
          );

          logger.info('Gateway exists check for update', { gateway, exists: existing.length > 0 });

          if (existing.length === 0) {
            // Insert new gateway - use INSERT with all fields
            const fields = ['gateway_name'];
            const values = [gateway];
            const placeholders = ['?'];

            if (gateway === 'stripe') {
              if (updates.stripe_secret_key !== undefined) {
                fields.push('stripe_secret_key');
                values.push(updates.stripe_secret_key);
                placeholders.push('?');
              }
              if (updates.stripe_publishable_key !== undefined) {
                fields.push('stripe_publishable_key');
                values.push(updates.stripe_publishable_key);
                placeholders.push('?');
              }
              if (updates.stripe_webhook_secret !== undefined) {
                fields.push('stripe_webhook_secret');
                values.push(updates.stripe_webhook_secret);
                placeholders.push('?');
              }
              if (updates.stripe_mode !== undefined) {
                fields.push('stripe_mode');
                values.push(updates.stripe_mode);
                placeholders.push('?');
              }
            } else if (gateway === 'paypal') {
              if (updates.paypal_client_id !== undefined) {
                fields.push('paypal_client_id');
                values.push(updates.paypal_client_id);
                placeholders.push('?');
              }
              if (updates.paypal_client_secret !== undefined) {
                fields.push('paypal_client_secret');
                values.push(updates.paypal_client_secret);
                placeholders.push('?');
              }
              if (updates.paypal_mode !== undefined) {
                fields.push('paypal_mode');
                values.push(updates.paypal_mode);
                placeholders.push('?');
              }
              if (updates.paypal_webhook_id !== undefined) {
                fields.push('paypal_webhook_id');
                values.push(updates.paypal_webhook_id);
                placeholders.push('?');
              }
            } else if (gateway === 'cash') {
              if (updates.cash_instructions !== undefined) {
                fields.push('cash_instructions');
                values.push(updates.cash_instructions);
                placeholders.push('?');
              }
              if (updates.cash_contact_email !== undefined) {
                fields.push('cash_contact_email');
                values.push(updates.cash_contact_email);
                placeholders.push('?');
              }
              if (updates.cash_contact_phone !== undefined) {
                fields.push('cash_contact_phone');
                values.push(updates.cash_contact_phone);
                placeholders.push('?');
              }
            }

            const insertQuery = `INSERT INTO payment_gateway_settings (${fields.join(', ')}) VALUES (${placeholders.join(', ')})`;
            logger.info('Executing INSERT', { query: insertQuery, values });

            await pool.execute(insertQuery, values);
            logger.info('Gateway inserted successfully', { gateway });
          } else {
            // Update existing gateway
            const updateFields = [];
            const values = [];

            if (gateway === 'stripe') {
              if (updates.stripe_secret_key !== undefined) {
                updateFields.push('stripe_secret_key = ?');
                values.push(updates.stripe_secret_key);
              }
              if (updates.stripe_publishable_key !== undefined) {
                updateFields.push('stripe_publishable_key = ?');
                values.push(updates.stripe_publishable_key);
              }
              if (updates.stripe_webhook_secret !== undefined) {
                updateFields.push('stripe_webhook_secret = ?');
                values.push(updates.stripe_webhook_secret);
              }
              if (updates.stripe_mode !== undefined) {
                updateFields.push('stripe_mode = ?');
                values.push(updates.stripe_mode);
              }
            } else if (gateway === 'paypal') {
              if (updates.paypal_client_id !== undefined) {
                updateFields.push('paypal_client_id = ?');
                values.push(updates.paypal_client_id);
              }
              if (updates.paypal_client_secret !== undefined) {
                updateFields.push('paypal_client_secret = ?');
                values.push(updates.paypal_client_secret);
              }
              if (updates.paypal_mode !== undefined) {
                updateFields.push('paypal_mode = ?');
                values.push(updates.paypal_mode);
              }
              if (updates.paypal_webhook_id !== undefined) {
                updateFields.push('paypal_webhook_id = ?');
                values.push(updates.paypal_webhook_id);
              }
            } else if (gateway === 'cash') {
              if (updates.cash_instructions !== undefined) {
                updateFields.push('cash_instructions = ?');
                values.push(updates.cash_instructions);
              }
              if (updates.cash_contact_email !== undefined) {
                updateFields.push('cash_contact_email = ?');
                values.push(updates.cash_contact_email);
              }
              if (updates.cash_contact_phone !== undefined) {
                updateFields.push('cash_contact_phone = ?');
                values.push(updates.cash_contact_phone);
              }
            }

            if (updateFields.length === 0) {
              logger.warn('No fields to update', { gateway, updates });
              return res.status(400).json({
                success: false,
                message: 'No valid fields to update'
              });
            }

            values.push(gateway);
            const updateQuery = `UPDATE payment_gateway_settings SET ${updateFields.join(', ')} WHERE gateway_name = ?`;
            logger.info('Executing UPDATE', { query: updateQuery, values });

            await pool.execute(updateQuery, values);
            logger.info('Gateway updated successfully', { gateway });
          }

          return res.json({
            success: true,
            message: 'Gateway settings updated successfully'
          });
        } catch (error) {
          logger.error('Error updating payment gateway', {
            error: error.message,
            stack: error.stack,
            code: error.code,
            sqlMessage: error.sqlMessage,
            gateway: req.params.gateway,
            body: req.body
          });
          return res.status(500).json({
            success: false,
            message: 'Error updating gateway settings',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
          });
        }
      }

      /**
       * Toggle gateway enabled status
       * PUT /api/superadmin/payment-gateways/:gateway/toggle
       */
      static async toggleGateway(req, res) {
        try {
          const { gateway } = req.params;
          const { enabled } = req.body;

          logger.info('Toggle gateway request', { gateway, enabled, body: req.body });

          // Validate gateway name
          if (!gateway || !['stripe', 'paypal', 'cash'].includes(gateway)) {
            logger.warn('Invalid gateway name', { gateway });
            return res.status(400).json({
              success: false,
              message: 'Invalid gateway name'
            });
          }

          // Validate enabled value
          if (typeof enabled !== 'boolean') {
            logger.warn('Invalid enabled value', { enabled, type: typeof enabled });
            return res.status(400).json({
              success: false,
              message: 'Invalid enabled value'
            });
          }

          // Check if gateway exists
          const [existing] = await pool.execute(
            'SELECT id, enabled FROM payment_gateway_settings WHERE gateway_name = ?',
            [gateway]
          );

          logger.info('Gateway exists check', { gateway, exists: existing.length > 0, current: existing[0] });

          if (existing.length === 0) {
            // Insert new gateway with enabled status and default instructions
            logger.info('Inserting new gateway', { gateway, enabled });

            const defaultInstructions = gateway === 'cash'
              ? 'Contact via WhatsApp to complete cash payment.'
              : null;

            await pool.execute(
              'INSERT INTO payment_gateway_settings (gateway_name, enabled, cash_instructions) VALUES (?, ?, ?)',
              [gateway, enabled, defaultInstructions]
            );

            logger.info('Gateway inserted successfully', { gateway, enabled });
          } else {
            // Update enabled status
            logger.info('Updating gateway status', { gateway, enabled, currentEnabled: existing[0].enabled });
            await pool.execute(
              'UPDATE payment_gateway_settings SET enabled = ? WHERE gateway_name = ?',
              [enabled, gateway]
            );

            logger.info('Gateway updated successfully', { gateway, enabled });
          }

          return res.json({
            success: true,
            message: `Gateway ${enabled ? 'enabled' : 'disabled'} successfully`
          });
        } catch (error) {
          logger.error('Error toggling payment gateway', {
            error: error.message,
            stack: error.stack,
            code: error.code,
            sqlMessage: error.sqlMessage,
            gateway: req.params.gateway,
            body: req.body
          });
          return res.status(500).json({
            success: false,
            message: 'Error toggling gateway',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
          });
        }
      }

      /**
       * Get enabled gateways (for public use)
       * GET /api/public/payment-gateways
       */
      static async getEnabledGateways(req, res) {
        try {
          const { plan_id } = req.query;

          logger.info('Getting enabled gateways', { plan_id });

          // Get globally enabled gateways
          const [gateways] = await pool.execute(
            'SELECT gateway_name, enabled FROM payment_gateway_settings WHERE enabled = TRUE'
          );

          logger.info('Globally enabled gateways', { count: gateways.length, gateways });

          // If plan_id is provided, filter gateways based on plan configuration
          if (plan_id) {
            const [plans] = await pool.execute(
              'SELECT cash_enabled, stripe_price_id, paypal_plan_id FROM subscription_plans WHERE id = ? AND active = TRUE',
              [plan_id]
            );

            logger.info('Plan configuration', { plan_id, found: plans.length > 0, plan: plans[0] });

            if (plans.length > 0) {
              const plan = plans[0];

              // Filter gateways based on plan configuration
              const filteredGateways = gateways.filter(gateway => {
                let allowed = false;

                if (gateway.gateway_name === 'cash') {
                  allowed = plan.cash_enabled === 1 || plan.cash_enabled === true;
                  logger.info('Cash gateway check', { cash_enabled: plan.cash_enabled, allowed });
                }
                if (gateway.gateway_name === 'stripe') {
                  allowed = plan.stripe_price_id && plan.stripe_price_id.trim() !== '';
                  logger.info('Stripe gateway check', { stripe_price_id: plan.stripe_price_id, allowed });
                }
                if (gateway.gateway_name === 'paypal') {
                  allowed = plan.paypal_plan_id && plan.paypal_plan_id.trim() !== '';
                  logger.info('PayPal gateway check', { paypal_plan_id: plan.paypal_plan_id, allowed });
                }

                return allowed;
              });

              logger.info('Filtered gateways', { count: filteredGateways.length, gateways: filteredGateways });

              return res.json({
                success: true,
                data: filteredGateways
              });
            }
          }

          // Return all enabled gateways if no plan_id provided
          logger.info('Returning all enabled gateways (no plan filter)');
          return res.json({
            success: true,
            data: gateways
          });
        } catch (error) {
          logger.error('Error getting enabled gateways', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error loading enabled gateways'
          });
        }
      }

      /**
       * Create payment session for new tenant
       * POST /api/public/create-payment-session
       */
      static async createPaymentSession(req, res) {
        try {
          const { tenant_id, plan_id, gateway } = req.body;

          logger.info('Create payment session request', { tenant_id, plan_id, gateway });

          // Validate required fields
          if (!tenant_id || !plan_id || !gateway) {
            logger.warn('Missing required fields', { tenant_id, plan_id, gateway });
            return res.status(400).json({
              success: false,
              message: 'Missing required fields'
            });
          }

          // Validate gateway
          if (!['stripe', 'paypal', 'cash'].includes(gateway)) {
            logger.warn('Invalid gateway', { gateway });
            return res.status(400).json({
              success: false,
              message: 'Invalid gateway'
            });
          }

          logger.info('Gateway validation passed', { gateway });

          // Get plan details
          const [plans] = await pool.execute(
            'SELECT * FROM subscription_plans WHERE id = ? AND active = TRUE',
            [plan_id]
          );

          if (plans.length === 0) {
            return res.status(404).json({
              success: false,
              message: 'Plan not found'
            });
          }

          const plan = plans[0];

          // Ensure price is a number
          plan.price = parseFloat(plan.price) || 0;

          // Validate price
          if (plan.price <= 0 && !plan.is_free) {
            return res.status(400).json({
              success: false,
              message: 'Invalid plan price'
            });
          }

          // Get tenant details
          const [tenants] = await pool.execute(
            'SELECT * FROM tenants WHERE id = ?',
            [tenant_id]
          );

          if (tenants.length === 0) {
            return res.status(404).json({
              success: false,
              message: 'Tenant not found'
            });
          }

          const tenant = tenants[0];

          // Handle different gateways
          if (gateway === 'stripe') {
            // Get Stripe configuration
            const [stripeConfig] = await pool.execute(
              'SELECT * FROM payment_gateway_settings WHERE gateway_name = ? AND enabled = TRUE',
              ['stripe']
            );

            if (stripeConfig.length === 0 || !stripeConfig[0].stripe_secret_key) {
              return res.status(400).json({
                success: false,
                message: 'Stripe is not configured. Please configure Stripe in the Super Admin panel first.'
              });
            }

            // Validate Stripe key format
            if (!stripeConfig[0].stripe_secret_key.startsWith('sk_')) {
              return res.status(400).json({
                success: false,
                message: 'Invalid Stripe secret key. It should start with "sk_"'
              });
            }

            // Initialize Stripe
            const stripe = require('stripe')(stripeConfig[0].stripe_secret_key);

            try {
              // Create Stripe Checkout Session
              const session = await stripe.checkout.sessions.create({
                payment_method_types: ['card'],
                line_items: [
                  {
                    price_data: {
                      currency: plan.currency.toLowerCase(),
                      product_data: {
                        name: plan.name,
                        description: `${plan.name} - Monthly Subscription`,
                      },
                      unit_amount: Math.round(plan.price * 100), // Convert to cents
                      recurring: {
                        interval: 'month',
                      },
                    },
                    quantity: 1,
                  },
                ],
                mode: 'subscription',
                success_url: `${process.env.BASE_URL || 'http://localhost:3000'}/payment-success?session_id={CHECKOUT_SESSION_ID}&tenant=${tenant_id}`,
                cancel_url: `${process.env.BASE_URL || 'http://localhost:3000'}/checkout?plan=${plan_id}&tenant=${tenant_id}&cancelled=true`,
                client_reference_id: tenant_id.toString(),
                metadata: {
                  tenant_id: tenant_id.toString(),
                  plan_id: plan_id.toString(),
                },
              });

              // Save session info
              await pool.execute(
                `INSERT INTO payments (tenant_id, plan_id, amount, currency, status, payment_method, external_id, created_at)
                 VALUES (?, ?, ?, ?, 'pending', 'stripe', ?, NOW())`,
                [tenant_id, plan_id, plan.price, plan.currency, session.id]
              );

              return res.json({
                success: true,
                data: {
                  gateway: 'stripe',
                  checkout_url: session.url,
                  session_id: session.id
                }
              });
            } catch (stripeError) {
              logger.error('Stripe error', { error: stripeError.message });
              return res.status(400).json({
                success: false,
                message: `Stripe error: ${stripeError.message}`
              });
            }

          } else if (gateway === 'paypal') {
            // Get PayPal configuration
            const [paypalConfig] = await pool.execute(
              'SELECT * FROM payment_gateway_settings WHERE gateway_name = ? AND enabled = TRUE',
              ['paypal']
            );

            if (paypalConfig.length === 0 || !paypalConfig[0].paypal_client_id || !paypalConfig[0].paypal_client_secret) {
              return res.status(400).json({
                success: false,
                message: 'PayPal is not configured. Please configure PayPal in the Super Admin panel first.'
              });
            }

            try {
              const paypal = require('@paypal/checkout-server-sdk');

              // Configure PayPal environment
              const environment = paypalConfig[0].paypal_mode === 'live'
                ? new paypal.core.LiveEnvironment(
                    paypalConfig[0].paypal_client_id,
                    paypalConfig[0].paypal_client_secret
                  )
                : new paypal.core.SandboxEnvironment(
                    paypalConfig[0].paypal_client_id,
                    paypalConfig[0].paypal_client_secret
                  );

              const client = new paypal.core.PayPalHttpClient(environment);

              // Create PayPal order
              const request = new paypal.orders.OrdersCreateRequest();
              request.prefer("return=representation");
              request.requestBody({
                intent: 'CAPTURE',
                purchase_units: [{
                  reference_id: tenant_id.toString(),
                  description: `${plan.name} - Monthly Subscription`,
                  amount: {
                    currency_code: plan.currency,
                    value: plan.price.toFixed(2)
                  }
                }],
                application_context: {
                  brand_name: 'Misayan SaaS',
                  landing_page: 'BILLING',
                  user_action: 'PAY_NOW',
                  return_url: `${process.env.BASE_URL || 'http://localhost:3000'}/payment-success?gateway=paypal&tenant=${tenant_id}`,
                  cancel_url: `${process.env.BASE_URL || 'http://localhost:3000'}/checkout?plan=${plan_id}&tenant=${tenant_id}&cancelled=true`
                }
              });

              const order = await client.execute(request);

              // Get approval URL
              const approvalUrl = order.result.links.find(link => link.rel === 'approve').href;

              // Save order info
              await pool.execute(
                `INSERT INTO payments (tenant_id, plan_id, amount, currency, status, payment_method, external_id, created_at)
                 VALUES (?, ?, ?, ?, 'pending', 'paypal', ?, NOW())`,
                [tenant_id, plan_id, plan.price, plan.currency, order.result.id]
              );

              return res.json({
                success: true,
                data: {
                  gateway: 'paypal',
                  checkout_url: approvalUrl,
                  order_id: order.result.id
                }
              });
            } catch (paypalError) {
              logger.error('PayPal error', { error: paypalError.message });
              return res.status(400).json({
                success: false,
                message: `PayPal error: ${paypalError.message}`
              });
            }

          } else if (gateway === 'cash') {
            logger.info('Processing cash payment', { tenant_id, plan_id });

            // Handle cash payment - set tenant to pending status
            // Get cash configuration
            const [cashConfig] = await pool.execute(
              'SELECT * FROM payment_gateway_settings WHERE gateway_name = ? AND enabled = TRUE',
              ['cash']
            );

            logger.info('Cash config retrieved', { found: cashConfig.length > 0, config: cashConfig[0] });

            // Get superadmin WhatsApp contact (optional)
            const [whatsappSettings] = await pool.execute(
              `SELECT setting_value FROM system_settings_kv
               WHERE setting_key = 'superadmin_whatsapp_phone'`
            );

            const whatsappPhone = whatsappSettings[0]?.setting_value || '';
            const contactEmail = cashConfig[0]?.cash_contact_email || '';
            const contactPhone = cashConfig[0]?.cash_contact_phone || whatsappPhone;

            logger.info('Contact info', { whatsappPhone, contactEmail, contactPhone });

            // Update tenant status to pending
            await pool.execute(
              'UPDATE tenants SET status = ? WHERE id = ?',
              ['pending', tenant_id]
            );

            logger.info('Tenant status updated to pending', { tenant_id });

            // Create payment record
            await pool.execute(
              `INSERT INTO payments (tenant_id, plan_id, amount, currency, status, payment_method, created_at)
               VALUES (?, ?, ?, ?, 'pending', ?, NOW())`,
              [tenant_id, plan_id, plan.price, plan.currency, gateway]
            );

            // Get cash instructions
            const instructions = cashConfig[0]?.cash_instructions || 'Contact support to complete cash payment.';

            // Create WhatsApp URL only if phone is configured
            let whatsappUrl = '';
            if (contactPhone) {
              const message = encodeURIComponent(
                `Hello! I just registered on the platform.\n\n` +
                `📧 Email: ${tenant.email}\n` +
                `🏢 Company: ${tenant.company_name || tenant.name}\n` +
                `📦 Plan: ${plan.name}\n` +
                `💰 Amount: ${plan.currency} ${plan.price.toFixed(2)}\n` +
                `💳 Method: Cash\n\n` +
                `I would like to complete the payment to activate my account.`
              );
              whatsappUrl = `https://wa.me/${contactPhone.replace(/\D/g, '')}?text=${message}`;
            }

            // Build redirect URL to payment pending page
            const redirectUrl = `${process.env.BASE_URL || 'http://localhost:3000'}/payment-pending.html?` +
              `email=${encodeURIComponent(tenant.email)}&` +
              `plan=${encodeURIComponent(plan.name)}&` +
              `amount=${plan.price.toFixed(2)}&` +
              `currency=${plan.currency}&` +
              `method=Cash` +
              (whatsappUrl ? `&whatsapp=${encodeURIComponent(whatsappUrl)}` : '') +
              (contactEmail ? `&contact_email=${encodeURIComponent(contactEmail)}` : '');

            return res.json({
              success: true,
              data: {
                gateway: gateway,
                payment_method: 'Cash',
                status: 'pending',
                instructions: instructions,
                whatsapp_url: whatsappUrl || null,
                whatsapp_phone: contactPhone || null,
                contact_email: contactEmail || null,
                redirect_url: redirectUrl,
                tenant_email: tenant.email,
                plan_name: plan.name,
                amount: plan.price,
                currency: plan.currency
              }
            });
          }

          return res.status(400).json({
            success: false,
            message: 'Invalid gateway'
          });

        } catch (error) {
          logger.error('Error creating payment session', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error creating payment session'
          });
        }
      }

      /**
       * Get payment instructions for tenant
       * GET /api/public/payment-instructions
       */
      static async getPaymentInstructions(req, res) {
        try {
          const { tenant } = req.query;

          if (!tenant) {
            return res.status(400).json({
              success: false,
              message: 'Tenant ID is required'
            });
          }

          // Get cash payment configuration
          const [cashConfig] = await pool.execute(
            'SELECT * FROM payment_gateway_settings WHERE gateway_name = ? AND enabled = TRUE',
            ['cash']
          );

          if (cashConfig.length === 0) {
            return res.status(404).json({
              success: false,
              message: 'Payment instructions not found'
            });
          }

          return res.json({
            success: true,
            data: {
              instructions: cashConfig[0].cash_instructions,
              contact_email: cashConfig[0].cash_contact_email,
              contact_phone: cashConfig[0].cash_contact_phone
            }
          });

        } catch (error) {
          logger.error('Error getting payment instructions', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error loading payment instructions'
          });
        }
      }

      /**
       * Verify payment after redirect from gateway
       * POST /api/public/verify-payment
       */
      static async verifyPayment(req, res) {
        try {
          const { session_id, order_id, tenant_id, gateway } = req.body;

          if (!tenant_id || !gateway) {
            return res.status(400).json({
              success: false,
              message: 'Missing required fields'
            });
          }

          if (gateway === 'stripe' && session_id) {
            // Verify Stripe payment
            const [stripeConfig] = await pool.execute(
              'SELECT * FROM payment_gateway_settings WHERE gateway_name = ? AND enabled = TRUE',
              ['stripe']
            );

            if (stripeConfig.length === 0) {
              return res.status(400).json({
                success: false,
                message: 'Stripe is not configured'
              });
            }

            const stripe = require('stripe')(stripeConfig[0].stripe_secret_key);

            try {
              const session = await stripe.checkout.sessions.retrieve(session_id);

              if (session.payment_status === 'paid') {
                // Update payment status
                await pool.execute(
                  'UPDATE payments SET status = ?, updated_at = NOW() WHERE external_id = ? AND tenant_id = ?',
                  ['completed', session_id, tenant_id]
                );

                // Update tenant status to active
                await pool.execute(
                  'UPDATE tenants SET status = ?, updated_at = NOW() WHERE id = ?',
                  ['active', tenant_id]
                );

                // Get plan details
                const [payments] = await pool.execute(
                  'SELECT p.*, sp.name as plan_name FROM payments p LEFT JOIN subscription_plans sp ON p.plan_id = sp.id WHERE p.external_id = ? AND p.tenant_id = ?',
                  [session_id, tenant_id]
                );

                return res.json({
                  success: true,
                  data: {
                    plan_name: payments[0]?.plan_name,
                    amount: payments[0]?.amount,
                    currency: payments[0]?.currency,
                    status: 'completed'
                  }
                });
              } else {
                return res.status(400).json({
                  success: false,
                  message: 'Payment not completed'
                });
              }
            } catch (stripeError) {
              logger.error('Stripe verification error', { error: stripeError.message });
              return res.status(400).json({
                success: false,
                message: `Stripe error: ${stripeError.message}`
              });
            }

          } else if (gateway === 'paypal' && order_id) {
            // Verify PayPal payment
            const [paypalConfig] = await pool.execute(
              'SELECT * FROM payment_gateway_settings WHERE gateway_name = ? AND enabled = TRUE',
              ['paypal']
            );

            if (paypalConfig.length === 0) {
              return res.status(400).json({
                success: false,
                message: 'PayPal is not configured'
              });
            }

            try {
              const paypal = require('@paypal/checkout-server-sdk');

              const environment = paypalConfig[0].paypal_mode === 'live'
                ? new paypal.core.LiveEnvironment(
                    paypalConfig[0].paypal_client_id,
                    paypalConfig[0].paypal_client_secret
                  )
                : new paypal.core.SandboxEnvironment(
                    paypalConfig[0].paypal_client_id,
                    paypalConfig[0].paypal_client_secret
                  );

              const client = new paypal.core.PayPalHttpClient(environment);
              const request = new paypal.orders.OrdersGetRequest(order_id);
              const order = await client.execute(request);

              if (order.result.status === 'COMPLETED' || order.result.status === 'APPROVED') {
                // Update payment status
                await pool.execute(
                  'UPDATE payments SET status = ?, updated_at = NOW() WHERE external_id = ? AND tenant_id = ?',
                  ['completed', order_id, tenant_id]
                );

                // Update tenant status to active
                await pool.execute(
                  'UPDATE tenants SET status = ?, updated_at = NOW() WHERE id = ?',
                  ['active', tenant_id]
                );

                // Get plan details
                const [payments] = await pool.execute(
                  'SELECT p.*, sp.name as plan_name FROM payments p LEFT JOIN subscription_plans sp ON p.plan_id = sp.id WHERE p.external_id = ? AND p.tenant_id = ?',
                  [order_id, tenant_id]
                );

                return res.json({
                  success: true,
                  data: {
                    plan_name: payments[0]?.plan_name,
                    amount: payments[0]?.amount,
                    currency: payments[0]?.currency,
                    status: 'completed'
                  }
                });
              } else {
                return res.status(400).json({
                  success: false,
                  message: 'Payment not completed'
                });
              }
            } catch (paypalError) {
              logger.error('PayPal verification error', { error: paypalError.message });
              return res.status(400).json({
                success: false,
                message: `PayPal error: ${paypalError.message}`
              });
            }

          } else {
            return res.status(400).json({
              success: false,
              message: 'Invalid payment verification request'
            });
          }

        } catch (error) {
          logger.error('Error verifying payment', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error verifying payment'
          });
        }
      }
    }

    module.exports = PaymentGatewayController;