#!/usr/bin/env python3
"""
===============================================================================
   ⚡ EMAIL SENDER DASHBOARD - STANDALONE VERSION ⚡
===============================================================================
 Standalone web dashboard for email sender system.
 Designed for cPanel hosting deployment.

── Email Sender Dashboard v1.0 by MEGA GROK MARKETING LABS ──
"""

import os
import sys
import json
import time
import threading
import logging
from datetime import datetime
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash
from werkzeug.utils import secure_filename
import yaml
from pathlib import Path

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('dashboard.log', encoding='utf-8'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

app = Flask(__name__)
app.secret_key = 'your-secret-key-change-this-in-production'

# Global variables
campaign_status = {
    'running': False,
    'started_at': None,
    'emails_sent': 0,
    'emails_failed': 0,
    'current_email': None,
    'logs': []
}

class DashboardLogger:
    """Custom logger for dashboard logs."""
    
    def __init__(self):
        self.logs = []
        self.max_logs = 1000
    
    def log(self, level, message):
        """Add log entry."""
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        log_entry = {
            'timestamp': timestamp,
            'level': level,
            'message': message
        }
        self.logs.append(log_entry)
        
        # Keep only recent logs
        if len(self.logs) > self.max_logs:
            self.logs = self.logs[-self.max_logs:]
        
        # Also log to file
        logger.info(f"[DASHBOARD] {message}")
    
    def get_logs(self, limit=50):
        """Get recent logs."""
        return self.logs[-limit:]

dashboard_logger = DashboardLogger()

# Sample configuration for demo
sample_config = {
    'smtp_config': {
        'host': 'smtp.gmail.com',
        'port': 587,
        'secure': False,
        'auth': {
            'user': 'your-email@gmail.com',
            'pass': 'your-app-password'
        }
    },
    'email_settings': {
        'email_list_file': 'emails.txt'
    },
    'subject_settings': {
        'subject': 'Security Alert - Action Required'
    },
    'custom_sender_options': {
        'from_mail': 'your-email@gmail.com',
        'sender_alias_template': 'Security Team'
    },
    'timer_thread_settings': {
        'threads': 1,
        'sleep_time': 2000
    },
    'feature_toggles': {
        'enable_pdf': False,
        'enable_qr': False,
        'enable_logo': False
    }
}

@app.route('/')
def index():
    """Main dashboard page."""
    return render_template('dashboard.html', 
                         campaign_status=campaign_status,
                         logs=dashboard_logger.get_logs())

@app.route('/api/status')
def api_status():
    """Get current campaign status."""
    return jsonify(campaign_status)

@app.route('/api/logs')
def api_logs():
    """Get recent logs."""
    limit = request.args.get('limit', 50, type=int)
    return jsonify(dashboard_logger.get_logs(limit))

@app.route('/api/start_campaign', methods=['POST'])
def api_start_campaign():
    """Start email campaign (demo mode)."""
    global campaign_status
    
    if campaign_status['running']:
        return jsonify({'success': False, 'message': 'Campaign is already running'})
    
    try:
        campaign_status['running'] = True
        campaign_status['started_at'] = datetime.now().isoformat()
        campaign_status['emails_sent'] = 0
        campaign_status['emails_failed'] = 0
        campaign_status['current_email'] = None
        
        dashboard_logger.log('INFO', 'Starting email campaign...')
        dashboard_logger.log('INFO', 'DEMO MODE: This is a demonstration dashboard')
        dashboard_logger.log('INFO', 'To use with real email sender, integrate with your email system')
        
        # Start demo campaign in separate thread
        campaign_thread = threading.Thread(target=run_demo_campaign)
        campaign_thread.daemon = True
        campaign_thread.start()
        
        return jsonify({'success': True, 'message': 'Demo campaign started successfully'})
        
    except Exception as e:
        campaign_status['running'] = False
        dashboard_logger.log('ERROR', f'Failed to start campaign: {e}')
        return jsonify({'success': False, 'message': str(e)})

@app.route('/api/stop_campaign', methods=['POST'])
def api_stop_campaign():
    """Stop email campaign."""
    global campaign_status
    
    if not campaign_status['running']:
        return jsonify({'success': False, 'message': 'No campaign is running'})
    
    campaign_status['running'] = False
    dashboard_logger.log('INFO', 'Campaign stopped by user')
    
    return jsonify({'success': True, 'message': 'Campaign stopped successfully'})

def run_demo_campaign():
    """Run demo campaign in separate thread."""
    global campaign_status
    
    try:
        # Demo email list
        demo_emails = [
            'demo1@example.com',
            'demo2@example.com', 
            'demo3@example.com',
            'demo4@example.com',
            'demo5@example.com'
        ]
        
        dashboard_logger.log('INFO', f'Starting demo campaign with {len(demo_emails)} recipients')
        
        for i, email in enumerate(demo_emails):
            if not campaign_status['running']:
                break
                
            campaign_status['current_email'] = email
            dashboard_logger.log('INFO', f'Processing email: {email}')
            
            # Simulate email sending
            time.sleep(2)  # Simulate processing time
            
            # Randomly succeed or fail for demo
            import random
            if random.random() > 0.2:  # 80% success rate
                campaign_status['emails_sent'] += 1
                dashboard_logger.log('SUCCESS', f'Email sent successfully to {email}')
            else:
                campaign_status['emails_failed'] += 1
                dashboard_logger.log('ERROR', f'Failed to send email to {email}: Connection timeout')
        
        campaign_status['running'] = False
        campaign_status['current_email'] = None
        dashboard_logger.log('INFO', f'Demo campaign completed. Sent: {campaign_status["emails_sent"]}, Failed: {campaign_status["emails_failed"]}')
        
    except Exception as e:
        campaign_status['running'] = False
        campaign_status['current_email'] = None
        dashboard_logger.log('ERROR', f'Campaign failed: {e}')

@app.route('/config')
def config_page():
    """Configuration management page."""
    return render_template('config.html', config=sample_config)

@app.route('/api/config', methods=['GET', 'POST'])
def api_config():
    """Get or update configuration."""
    if request.method == 'GET':
        return jsonify(sample_config)
    
    elif request.method == 'POST':
        try:
            new_config = request.json
            sample_config.update(new_config)
            
            dashboard_logger.log('INFO', 'Configuration updated successfully')
            return jsonify({'success': True, 'message': 'Configuration updated successfully'})
            
        except Exception as e:
            dashboard_logger.log('ERROR', f'Failed to update configuration: {e}')
            return jsonify({'success': False, 'message': str(e)})

@app.route('/files')
def files_page():
    """File management page."""
    files_info = {}
    
    # Check email files
    email_files = ['emails.txt', 'subjects.txt', 'fromnames.txt', 'fromemails.txt', 'links.txt']
    for filename in email_files:
        file_path = Path(filename)
        if file_path.exists():
            files_info[filename] = {
                'exists': True,
                'size': file_path.stat().st_size,
                'modified': datetime.fromtimestamp(file_path.stat().st_mtime).isoformat(),
                'lines': len(open(filename, 'r', encoding='utf-8').readlines())
            }
        else:
            files_info[filename] = {'exists': False}
    
    return render_template('files.html', files_info=files_info)

@app.route('/api/files/<filename>', methods=['GET', 'POST'])
def api_files(filename):
    """Get or update file content."""
    allowed_files = ['emails.txt', 'subjects.txt', 'fromnames.txt', 'fromemails.txt', 'links.txt']
    
    if filename not in allowed_files:
        return jsonify({'success': False, 'message': 'File not allowed'})
    
    if request.method == 'GET':
        try:
            if os.path.exists(filename):
                with open(filename, 'r', encoding='utf-8') as f:
                    content = f.read()
                return jsonify({'success': True, 'content': content})
            else:
                return jsonify({'success': False, 'message': 'File not found'})
        except Exception as e:
            return jsonify({'success': False, 'message': str(e)})
    
    elif request.method == 'POST':
        try:
            content = request.json.get('content', '')
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(content)
            
            dashboard_logger.log('INFO', f'File {filename} updated successfully')
            return jsonify({'success': True, 'message': f'File {filename} updated successfully'})
            
        except Exception as e:
            dashboard_logger.log('ERROR', f'Failed to update file {filename}: {e}')
            return jsonify({'success': False, 'message': str(e)})

@app.route('/logs')
def logs_page():
    """Logs page."""
    return render_template('logs.html', logs=dashboard_logger.get_logs(100))

@app.route('/demo')
def demo_page():
    """Demo information page."""
    return render_template('demo.html')

if __name__ == '__main__':
    dashboard_logger.log('INFO', 'Standalone Dashboard starting...')
    dashboard_logger.log('INFO', 'This is a demonstration version for cPanel hosting')
    dashboard_logger.log('INFO', 'To integrate with real email sender, modify the email sending functions')
    
    # For cPanel hosting, use port 5000 or let the server decide
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=False)
