<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// Include required files
require_once '../config/database.php';
require_once '../config/config.php';
require_once '../includes/auth.php';
require_once '../includes/admin-functions.php';
require_once '../includes/functions.php';

// Initialize classes
$auth = new Auth();
$adminFunctions = new AdminFunctions();
$functions = new InvestmentFunctions();

// Check if admin is logged in
if (!$auth->isAdminLoggedIn()) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit;
}

// Get the action from POST data
$action = $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'get_dashboard_stats':
            $stats = $adminFunctions->getDashboardStats();
            echo json_encode([
                'success' => true,
                'data' => $stats
            ]);
            break;

        case 'get_users':
            $page = (int)($_POST['page'] ?? 1);
            $limit = (int)($_POST['limit'] ?? 20);
            $filters = $_POST['filters'] ?? [];
            $result = $adminFunctions->getUsers($page, $limit, $filters);
            echo json_encode([
                'success' => true,
                'data' => $result
            ]);
            break;

        case 'update_user_status':
            $user_id = (int)($_POST['user_id'] ?? 0);
            $status = $_POST['status'] ?? '';
            if (!$user_id || !$status) {
                throw new Exception('User ID and status are required');
            }
            $result = $adminFunctions->updateUserStatus($user_id, $status);
            echo json_encode($result);
            break;

        case 'update_user_kyc':
            $user_id = (int)($_POST['user_id'] ?? 0);
            $status = $_POST['status'] ?? '';
            $notes = $_POST['notes'] ?? '';
            if (!$user_id || !$status) {
                throw new Exception('User ID and status are required');
            }
            $result = $adminFunctions->updateUserKYC($user_id, $status, $notes);
            echo json_encode($result);
            break;

        case 'get_investments':
            $page = (int)($_POST['page'] ?? 1);
            $limit = (int)($_POST['limit'] ?? 20);
            $filters = $_POST['filters'] ?? [];
            $result = $adminFunctions->getInvestments($page, $limit, $filters);
            echo json_encode([
                'success' => true,
                'data' => $result
            ]);
            break;

        case 'get_transactions':
            $page = (int)($_POST['page'] ?? 1);
            $limit = (int)($_POST['limit'] ?? 20);
            $filters = $_POST['filters'] ?? [];
            $result = $adminFunctions->getTransactions($page, $limit, $filters);
            echo json_encode([
                'success' => true,
                'data' => $result
            ]);
            break;

        case 'process_withdrawal':
            $transaction_id = (int)($_POST['transaction_id'] ?? 0);
            $action_type = $_POST['action_type'] ?? '';
            $notes = $_POST['notes'] ?? '';
            if (!$transaction_id || !in_array($action_type, ['approve', 'reject'])) {
                throw new Exception('Transaction ID and valid action are required');
            }
            $result = $adminFunctions->processWithdrawal($transaction_id, $action_type, $notes);
            echo json_encode($result);
            break;

        case 'get_settings':
            $settings = $adminFunctions->getSettings();
            echo json_encode([
                'success' => true,
                'data' => $settings
            ]);
            break;

        case 'update_setting':
            $key = $_POST['key'] ?? '';
            $value = $_POST['value'] ?? '';
            if (!$key) {
                throw new Exception('Setting key is required');
            }
            $result = $adminFunctions->updateSetting($key, $value);
            echo json_encode($result);
            break;

        case 'clear_old_logs':
            $days = (int)($_POST['days'] ?? 30);
            $result = $adminFunctions->clearOldLogs($days);
            echo json_encode($result);
            break;

        case 'get_system_info':
            $info = $adminFunctions->getSystemInfo();
            echo json_encode([
                'success' => true,
                'data' => $info
            ]);
            break;

        case 'manual_investment':
            $user_id = (int)($_POST['user_id'] ?? 0);
            $plan_id = (int)($_POST['plan_id'] ?? 0);
            $amount = (float)($_POST['amount'] ?? 0);
            $start_date = $_POST['start_date'] ?? date('Y-m-d');
            
            if (!$user_id || !$plan_id || $amount <= 0) {
                throw new Exception('Invalid input parameters');
            }
            
            // Get plan
            $plan = $functions->getPlanById($plan_id);
            if (!$plan) {
                throw new Exception('Plan not found');
            }
            
            // Calculate details
            $daily_profit = ($amount * $plan['daily_return']) / 100;
            $end_date = date('Y-m-d H:i:s', strtotime($start_date . " +{$plan['duration_days']} days"));
            
            $db = Database::getInstance()->getConnection();
            $db->beginTransaction();
            
            // Check user has sufficient balance
            $stmt = $db->prepare("SELECT balance FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user || $user['balance'] < $amount) {
                $db->rollBack();
                throw new Exception('Insufficient user balance');
            }
            
            // Deduct amount from user balance
            $stmt = $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
            $stmt->execute([$amount, $user_id]);
            
            // Create investment
            $stmt = $db->prepare("INSERT INTO investments (user_id, plan_id, amount, daily_profit, start_date, end_date, status, created_at) VALUES (?, ?, ?, ?, ?, ?, 'running', NOW())");
            $stmt->execute([$user_id, $plan_id, $amount, $daily_profit, $start_date, $end_date]);
            $investment_id = $db->lastInsertId();
            
            $db->commit();
            
            echo json_encode(['success' => true, 'message' => 'Investment created successfully']);
            break;

        case 'manual_deposit':
            $user_id = (int)($_POST['user_id'] ?? 0);
            $amount = (float)($_POST['amount'] ?? 0);
            $description = $_POST['description'] ?? 'Manual Deposit';
            
            if (!$user_id || $amount <= 0) {
                throw new Exception('Invalid input parameters');
            }

            $db = Database::getInstance()->getConnection();
            $db->beginTransaction();

            // Update user balance
            $stmt = $db->prepare("UPDATE users SET balance = balance + ?, total_deposit = total_deposit + ? WHERE id = ?");
            $stmt->execute([$amount, $amount, $user_id]);

            // Create transaction
            $reference = 'DEP' . time() . rand(1000, 9999);
            $stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, method, description, reference, status, admin_action_by, created_at) VALUES (?, 'deposit', ?, 'manual', ?, ?, 'completed', ?, NOW())");
            $stmt->execute([$user_id, $amount, $description, $reference, $_SESSION['admin_id']]);

            $db->commit();

            // Send Email Notification
            try {
                $stmt = $db->prepare("SELECT username, email FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($user) {
                    $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
                    $mail->isSMTP();
                    $mail->Host = SMTP_HOST;
                    $mail->SMTPAuth = true;
                    $mail->Username = SMTP_USERNAME;
                    $mail->Password = SMTP_PASSWORD;
                    $mail->SMTPSecure = SMTP_ENCRYPTION;
                    $mail->Port = SMTP_PORT;
                    
                    $mail->setFrom(SITE_EMAIL, SITE_NAME);
                    $mail->addAddress($user['email'], $user['username']);
                    $mail->addBCC(ADMIN_EMAIL); // Send copy to admin
                    
                    $mail->isHTML(true);
                    $mail->Subject = "Deposit Confirmed - " . SITE_NAME;
                    $mail->Body = "
                    <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
                        <h2 style='color: #333;'>Deposit Confirmation</h2>
                        <p>Dear {$user['username']},</p>
                        <p>A deposit of <strong>$" . number_format($amount, 2) . "</strong> has been credited to your account.</p>
                        <div style='background: #f9f9f9; padding: 15px; border-radius: 5px; margin: 20px 0;'>
                            <p><strong>Reference:</strong> {$reference}</p>
                            <p><strong>Description:</strong> {$description}</p>
                            <p><strong>Date:</strong> " . date('Y-m-d H:i:s') . "</p>
                        </div>
                        <p>Thank you for choosing " . SITE_NAME . ".</p>
                    </div>";
                    
                    $mail->send();
                }
            } catch (Exception $e) {
                // Continue even if email fails
            }
            
            echo json_encode(['success' => true, 'message' => 'Deposit added successfully']);
            break;

        case 'manual_withdrawal':
            $user_id = (int)($_POST['user_id'] ?? 0);
            $amount = (float)($_POST['amount'] ?? 0);
            $method = $_POST['method'] ?? 'manual';
            $wallet = $_POST['wallet'] ?? '';
            $network = $_POST['network'] ?? null;
            
            if (!$user_id || $amount <= 0) {
                throw new Exception('Invalid input parameters');
            }

            $db = Database::getInstance()->getConnection();
            
            // Check balance
            $stmt = $db->prepare("SELECT balance FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $balance = $stmt->fetchColumn();
            
            if ($balance < $amount) {
                throw new Exception('Insufficient user balance');
            }

            $db->beginTransaction();

            // Update user balance
            $stmt = $db->prepare("UPDATE users SET balance = balance - ?, total_withdrawal = total_withdrawal + ? WHERE id = ?");
            $stmt->execute([$amount, $amount, $user_id]);

            // Build details array including wallet_address and optional network
            $details = ['wallet_address' => $wallet];
            if ($network) {
                $details['network'] = $network;
            }

            // Create transaction
            $reference = 'WTH' . time() . rand(1000, 9999);
            $stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, method, description, reference, status, admin_action_by, details, created_at) VALUES (?, 'withdrawal', ?, ?, 'Manual Withdrawal', ?, 'completed', ?, ?, NOW())");
            $stmt->execute([$user_id, $amount, $method, $reference, $_SESSION['admin_id'], json_encode($details)]);

            $db->commit();
            
            echo json_encode([
                'success' => true,
                'message' => 'Withdrawal processed successfully'
            ]);
            break;

        case 'extend':
            $investment_id = (int)($_POST['investment_id'] ?? 0);
            $extra_days = (int)($_POST['extra_days'] ?? 0);
            
            if (!$investment_id || $extra_days <= 0) {
                throw new Exception('Invalid parameters');
            }
            
            $db = Database::getInstance()->getConnection();
            $stmt = $db->prepare("UPDATE investments SET end_date = DATE_ADD(end_date, INTERVAL ? DAY), duration_days = duration_days + ? WHERE id = ?");
            $stmt->execute([$extra_days, $extra_days, $investment_id]);
            
            echo json_encode(['success' => true, 'message' => 'Investment extended successfully']);
            break;

        case 'bonus':
            $investment_id = (int)($_POST['investment_id'] ?? 0);
            $amount = (float)($_POST['bonus_amount'] ?? 0);
            $reason = $_POST['reason'] ?? 'Bonus';
            
            if (!$investment_id || $amount <= 0) {
                throw new Exception('Invalid parameters');
            }
            
            $db = Database::getInstance()->getConnection();
            $stmt = $db->prepare("SELECT user_id FROM investments WHERE id = ?");
            $stmt->execute([$investment_id]);
            $user_id = $stmt->fetchColumn();
            
            if (!$user_id) throw new Exception('Investment not found');
            
            $db->beginTransaction();
            
            // Add to balance
            $stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $stmt->execute([$amount, $user_id]);
            
            // Transaction
            $reference = 'BNS' . time() . rand(1000, 9999);
            $stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, method, description, reference, status, created_at) VALUES (?, 'bonus', ?, 'system', ?, ?, 'completed', NOW())");
            $stmt->execute([$user_id, $amount, "Bonus for investment #$investment_id: $reason", $reference]);
            
            $db->commit();
            
            echo json_encode(['success' => true, 'message' => 'Bonus added successfully']);
            break;

        case 'add_profit':
            $investment_id = (int)($_POST['investment_id'] ?? 0);
            $add_to_balance = filter_var($_POST['add_to_balance'] ?? false, FILTER_VALIDATE_BOOLEAN);
            
            $db = Database::getInstance()->getConnection();
            $stmt = $db->prepare("SELECT * FROM investments WHERE id = ?");
            $stmt->execute([$investment_id]);
            $investment = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$investment) throw new Exception('Investment not found');
            
            $db->beginTransaction();
            
            // Update total profit
            $stmt = $db->prepare("UPDATE investments SET total_profit = total_profit + ?, last_profit_date = CURDATE() WHERE id = ?");
            $stmt->execute([$investment['daily_profit'], $investment_id]);
            
            if ($add_to_balance) {
                $stmt = $db->prepare("UPDATE users SET balance = balance + ?, profit_balance = profit_balance + ? WHERE id = ?");
                $stmt->execute([$investment['daily_profit'], $investment['daily_profit'], $investment['user_id']]);
                
                // Transaction
                $reference = 'PRF' . time() . rand(1000, 9999);
                $stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, method, description, reference, status, created_at) VALUES (?, 'profit', ?, 'system', ?, ?, 'completed', NOW())");
                $stmt->execute([$investment['user_id'], $investment['daily_profit'], "Manual profit for investment #$investment_id", $reference]);
            }
            
            $db->commit();
            
            echo json_encode(['success' => true, 'message' => 'Profit added successfully']);
            break;

        case 'skip_profit':
            $investment_id = (int)($_POST['investment_id'] ?? 0);
            
            $db = Database::getInstance()->getConnection();
            $stmt = $db->prepare("UPDATE investments SET last_profit_date = CURDATE() WHERE id = ?");
            $stmt->execute([$investment_id]);
            
            echo json_encode(['success' => true, 'message' => 'Profit skipped for today']);
            break;

        case 'add_investment_note':
            $investment_id = (int)($_POST['investment_id'] ?? 0);
            $note = $_POST['note'] ?? '';
            
            if (!$investment_id || empty($note)) throw new Exception('Invalid parameters');
            
            $db = Database::getInstance()->getConnection();
            // Ensure table exists
            $db->exec("CREATE TABLE IF NOT EXISTS investment_notes (
                id INT AUTO_INCREMENT PRIMARY KEY,
                investment_id INT NOT NULL,
                admin_id INT NOT NULL,
                note TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");
            
            $stmt = $db->prepare("INSERT INTO investment_notes (investment_id, admin_id, note) VALUES (?, ?, ?)");
            $stmt->execute([$investment_id, $_SESSION['admin_id'], $note]);
            
            echo json_encode(['success' => true, 'message' => 'Note added successfully']);
            break;

        default:
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action'
            ]);
            break;
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
