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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
import os
from flask import Blueprint, render_template, request, jsonify, redirect, url_for, session, current_app
from flask_login import login_required, current_user
import requests
import hashlib
import hmac
import json
from datetime import datetime, timedelta
import uuid
from models.subscription import Subscription

pricing_bp = Blueprint('pricing', __name__)

# SSLCommerce configuration
SSLCOMMERCE_STORE_ID = os.environ.get('SSLCOMMERCE_STORE_ID', 'your_store_id_here')
SSLCOMMERCE_STORE_PASS = os.environ.get('SSLCOMMERCE_STORE_PASS', 'your_store_password_here')
SSLCOMMERCE_API_URL = os.environ.get('SSLCOMMERCE_API_URL', 'https://sandbox.sslcommerz.com/gwprocess/v4/api.php')
SSLCOMMERCE_VALIDATION_URL = os.environ.get('SSLCOMMERCE_VALIDATION_URL', 'https://sandbox.sslcommerz.com/validator/api/validationserverAPI.php')

# Pricing plans
PRICING_PLANS = {
    'basic': {
        'id': 'basic',
        'name': 'Basic Plan',
        'price': 0.00,  # Free plan
        'description': 'Perfect for individuals getting started',
        'features': [
            'Convert up to 100 images per month',
            'Basic math equation recognition',
            'Email support',
            'Standard processing speed'
        ],
        'is_free': True
    },
    'pro': {
        'id': 'pro',
        'name': 'Professional Plan',
        'price': 24.99,
        'description': 'Ideal for professionals and researchers',
        'features': [
            'Unlimited image conversions',
            'Advanced math equation recognition',
            'Handwritten table detection',
            'Priority processing speed',
            '24/7 customer support',
            'Early access to new features'
        ],
        'is_free': False
    },
    'enterprise': {
        'id': 'enterprise',
        'name': 'Enterprise Plan',
        'price': 49.99,
        'description': 'For teams and organizations',
        'features': [
            'Everything in Professional Plan',
            'Team collaboration tools',
            'Custom API access',
            'Dedicated account manager',
            'SLA guarantee',
            'On-premise deployment option'
        ],
        'is_free': False
    }
}

@pricing_bp.route('/pricing')
@login_required
def pricing():
    """Display pricing plans"""
    return render_template('pricing.html', plans=PRICING_PLANS)

@pricing_bp.route('/checkout/<plan_id>')
@login_required
def checkout(plan_id):
    """Display checkout page for a plan"""
    if plan_id not in PRICING_PLANS:
        return jsonify({'error': 'Invalid plan selected'}), 400
    
    plan = PRICING_PLANS[plan_id]
    
    # If it's a free plan, activate it immediately
    if plan.get('is_free', False):
        # Calculate subscription dates (1 month from now)
        start_date = datetime.now()
        end_date = start_date + timedelta(days=30)
        
        # Update user's plan in database
        subscription = Subscription.create_or_update(
            user_id=current_user.id,
            plan_id=plan_id,
            start_date=start_date.isoformat(),
            end_date=end_date.isoformat(),
            is_active=True
        )
        
        # Update current user object
        current_user.subscription = subscription.__dict__ if subscription else {}
        
        return render_template('payment_success.html', plan=plan)
    
    # For paid plans, generate unique transaction ID
    tran_id = str(uuid.uuid4())
    
    # Store transaction info in session
    session['transaction'] = {
        'tran_id': tran_id,
        'plan_id': plan_id,
        'user_id': current_user.id,
        'amount': plan['price'],
        'timestamp': datetime.now().isoformat()
    }
    
    return render_template('checkout.html', plan=plan, transaction=session['transaction'])

@pricing_bp.route('/process-payment/<plan_id>', methods=['POST'])
@login_required
def process_payment(plan_id):
    """Process payment for a plan based on selected payment method"""
    if plan_id not in PRICING_PLANS:
        return jsonify({'error': 'Invalid plan selected'}), 400
    
    plan = PRICING_PLANS[plan_id]
    payment_method = request.form.get('payment_method', 'sslcommerce')
    
    # If it's a free plan, activate it immediately
    if plan.get('is_free', False):
        # Calculate subscription dates (1 month from now)
        start_date = datetime.now()
        end_date = start_date + timedelta(days=30)
        
        # Update user's plan in database
        subscription = Subscription.create_or_update(
            user_id=current_user.id,
            plan_id=plan_id,
            start_date=start_date.isoformat(),
            end_date=end_date.isoformat(),
            is_active=True
        )
        
        # Update current user object
        current_user.subscription = subscription.__dict__ if subscription else {}
        
        return render_template('payment_success.html', plan=plan)
    
    # Generate unique transaction ID
    tran_id = str(uuid.uuid4())
    
    # Store transaction info in session
    session['transaction'] = {
        'tran_id': tran_id,
        'plan_id': plan_id,
        'user_id': current_user.id,
        'amount': plan['price'],
        'timestamp': datetime.now().isoformat(),
        'payment_method': payment_method
    }
    
    if payment_method == 'sslcommerce':
        # Process with SSLCommerce
        return process_sslcommerce_payment(plan, tran_id)
    else:
        # For other payment methods, return instructions
        return process_alternative_payment(plan, tran_id, payment_method)

def process_sslcommerce_payment(plan, tran_id):
    """Process payment through SSLCommerce"""
    # Prepare data for SSLCommerce
    post_data = {
        'store_id': SSLCOMMERCE_STORE_ID,
        'store_passwd': SSLCOMMERCE_STORE_PASS,
        'total_amount': plan['price'],
        'currency': 'USD',
        'tran_id': tran_id,
        'success_url': url_for('pricing.payment_success', _external=True),
        'fail_url': url_for('pricing.payment_failed', _external=True),
        'cancel_url': url_for('pricing.payment_cancelled', _external=True),
        'ipn_url': url_for('pricing.payment_ipn', _external=True),
        'cus_name': current_user.name,
        'cus_email': current_user.email,
        'cus_add1': 'Dhaka',
        'cus_add2': 'Dhaka',
        'cus_city': 'Dhaka',
        'cus_state': 'Dhaka',
        'cus_postcode': '1000',
        'cus_country': 'Bangladesh',
        'cus_phone': '01711111111',
        'cus_fax': '01711111111',
        'ship_name': current_user.name,
        'ship_add1': 'Dhaka',
        'ship_add2': 'Dhaka',
        'ship_city': 'Dhaka',
        'ship_state': 'Dhaka',
        'ship_postcode': '1000',
        'ship_country': 'Bangladesh',
        'product_name': plan['name'],
        'product_category': 'Software',
        'product_profile': 'non-physical-goods',
        'multi_card_name': '',
        'value_a': plan['id'],
        'value_b': current_user.id,
        'value_c': '',
        'value_d': ''
    }
    
    try:
        # Make request to SSLCommerce
        response = requests.post(SSLCOMMERCE_API_URL, data=post_data)
        response_data = response.json()
        
        if response_data.get('status') == 'SUCCESS':
            # Redirect to payment gateway
            return redirect(response_data['GatewayPageURL'])
        else:
            return jsonify({'error': 'Payment gateway error', 'details': response_data}), 500
            
    except Exception as e:
        return jsonify({'error': 'Failed to initiate payment', 'details': str(e)}), 500

def process_alternative_payment(plan, tran_id, payment_method):
    """Process payment through alternative methods (Nagad, Rocket, Bank)"""
    # For alternative payment methods, we return instructions
    # In a real implementation, you would integrate with their APIs or send notifications
    
    instructions = {
        'nagad': {
            'title': 'Nagad Payment Instructions',
            'steps': [
                'Dial *167# from your Nagad registered mobile number',
                'Select "Send Money"',
                'Enter the merchant number: 017XXXXXXXX',
                f'Enter the amount: {plan["price"]} BDT',
                f'Enter reference: {tran_id}',
                'Confirm the transaction with your Nagad PIN',
                'You will receive a confirmation SMS'
            ],
            'confirmation': 'After completing the payment, please click the confirmation button below.'
        },
        'rocket': {
            'title': 'Rocket Payment Instructions',
            'steps': [
                'Dial *322# from your Rocket registered mobile number',
                'Select "Send Money"',
                'Enter the merchant number: 017XXXXXXXX',
                f'Enter the amount: {plan["price"]} BDT',
                f'Enter reference: {tran_id}',
                'Confirm the transaction with your Rocket PIN',
                'You will receive a confirmation SMS'
            ],
            'confirmation': 'After completing the payment, please click the confirmation button below.'
        },
        'bank': {
            'title': 'Bank Transfer Instructions',
            'steps': [
                f'Transfer {plan["price"]} BDT to the following bank account:',
                'Bank: ABC Bank Ltd.',
                'Account Name: TexLab Services',
                'Account Number: 1234567890',
                'Routing Number: 123456789',
                f'Include this reference in the transfer description: {tran_id}',
                'Email the transaction receipt to payments@texlab.com'
            ],
            'confirmation': 'After completing the payment, please click the confirmation button below.'
        }
    }
    
    instruction_data = instructions.get(payment_method, {})
    return render_template('manual_payment.html', 
                         instructions=instruction_data, 
                         plan=plan, 
                         tran_id=tran_id, 
                         method=payment_method,
                         plan_id=plan['id'])

@pricing_bp.route('/payment/manual-confirm')
@login_required
def manual_payment_confirm():
    """Confirm manual payment (Nagad, Rocket, Bank)"""
    payment_method = request.args.get('method')
    plan_id = request.args.get('plan_id')
    
    if not payment_method or not plan_id:
        return redirect(url_for('pricing.pricing'))
    
    if 'transaction' not in session:
        return redirect(url_for('pricing.pricing'))
    
    transaction = session['transaction']
    
    # For demo purposes, we'll assume the payment is successful
    # In a real implementation, you would verify the payment with the payment provider
    
    # Calculate subscription dates (1 month from now)
    start_date = datetime.now()
    end_date = start_date + timedelta(days=30)
    
    # Update user's plan in database
    subscription = Subscription.create_or_update(
        user_id=transaction['user_id'],
        plan_id=transaction['plan_id'],
        start_date=start_date.isoformat(),
        end_date=end_date.isoformat(),
        is_active=True
    )
    
    # Update current user object
    current_user.subscription = subscription.__dict__ if subscription else {}
    
    # Clear transaction from session
    session.pop('transaction', None)
    
    return render_template('payment_success.html', plan=PRICING_PLANS[transaction['plan_id']])

@pricing_bp.route('/payment/success')
@login_required
def payment_success():
    """Handle successful payment"""
    # Verify the payment with SSLCommerce
    if 'transaction' not in session:
        return redirect(url_for('pricing.pricing'))
    
    transaction = session['transaction']
    
    # Get parameters from SSLCommerce
    params = request.args.to_dict()
    
    # Verify payment with SSLCommerce
    if verify_payment(params):
        # Calculate subscription dates (1 month from now)
        start_date = datetime.now()
        end_date = start_date + timedelta(days=30)
        
        # Update user's plan in database
        subscription = Subscription.create_or_update(
            user_id=transaction['user_id'],
            plan_id=transaction['plan_id'],
            start_date=start_date.isoformat(),
            end_date=end_date.isoformat(),
            is_active=True
        )
        
        # Update current user object
        current_user.subscription = subscription.__dict__ if subscription else {}
        
        # Clear transaction from session
        session.pop('transaction', None)
        
        return render_template('payment_success.html', plan=PRICING_PLANS[transaction['plan_id']])
    else:
        return redirect(url_for('pricing.payment_failed'))

@pricing_bp.route('/payment/failed')
@login_required
def payment_failed():
    """Handle failed payment"""
    session.pop('transaction', None)
    return render_template('payment_failed.html')

@pricing_bp.route('/payment/cancelled')
@login_required
def payment_cancelled():
    """Handle cancelled payment"""
    session.pop('transaction', None)
    return render_template('payment_cancelled.html')

@pricing_bp.route('/payment/ipn', methods=['POST'])
def payment_ipn():
    """Handle IPN (Instant Payment Notification) from SSLCommerce"""
    # This endpoint should handle payment notifications from SSLCommerce
    # In a production environment, you would update your database here
    data = request.form.to_dict()
    
    # Verify the payment notification
    if verify_payment(data):
        # Update database with payment status
        # This is where you would update your user's subscription status
        pass
    
    return jsonify({'status': 'success'})

def verify_payment(params):
    """Verify payment with SSLCommerce"""
    if 'val_id' not in params:
        return False
    
    validation_url = f"{SSLCOMMERCE_VALIDATION_URL}?val_id={params['val_id']}&store_id={SSLCOMMERCE_STORE_ID}&store_passwd={SSLCOMMERCE_STORE_PASS}&v=1&format=json"
    
    try:
        response = requests.get(validation_url)
        data = response.json()
        
        if data.get('status') == 'VALID' or data.get('status') == 'VALIDATED':
            return True
        else:
            return False
    except Exception:
        return False

def update_user_plan(user_id, plan_id):
    """Update user's subscription plan in database"""
    # Calculate subscription dates (1 month from now)
    start_date = datetime.now()
    end_date = start_date + timedelta(days=30)
    
    # Update user's plan in database
    subscription = Subscription.create_or_update(
        user_id=user_id,
        plan_id=plan_id,
        start_date=start_date.isoformat(),
        end_date=end_date.isoformat(),
        is_active=True
    )
    
    return subscription

@pricing_bp.route('/current-plan')
@login_required
def current_plan():
    """Get current user's plan"""
    subscription = Subscription.get_by_user_id(current_user.id)
    if subscription and subscription.is_active:
        return jsonify({
            'plan': subscription.plan_id,
            'expires': subscription.end_date
        })
    else:
        return jsonify({
            'plan': 'basic',  # Default to basic plan
            'expires': None
        })