<?php
session_start();
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/notification.php';

redirectIfNotAdmin();

$error = '';
$success = '';
$generatedCount = 0;

// Fetch all users
$users = $pdo->query("
    SELECT u.user_id, u.full_name, u.email, a.account_id, a.account_number, a.balance
    FROM users u 
    LEFT JOIN accounts a ON u.user_id = a.user_id
    WHERE u.status = 'approved'
    ORDER BY u.full_name
")->fetchAll();

// Fetch transaction templates
$templates = $pdo->query("SELECT * FROM transaction_templates WHERE is_active = 1 ORDER BY category, template_name")->fetchAll();

// Generate transactions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate'])) {
    $user_id = intval($_POST['user_id'] ?? 0);
    $start_date = $_POST['start_date'] ?? date('Y-m-01', strtotime('-3 months'));
    $end_date = $_POST['end_date'] ?? date('Y-m-d');
    $patterns = $_POST['patterns'] ?? [];
    $max_transactions_per_day = intval($_POST['max_transactions'] ?? 3);

    if ($user_id <= 0) {
        $error = "Please select a user.";
    } else {
        try {
            // Get user account
            $stmt = $pdo->prepare("SELECT account_id, balance FROM accounts WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $account = $stmt->fetch();

            if (!$account) {
                throw new Exception("User account not found.");
            }

            $pdo->beginTransaction();

            // Get current balance
            $current_balance = $account['balance'];
            $generated = [];

            // Parse date range
            $start = new DateTime($start_date);
            $end = new DateTime($end_date);
            $end->modify('+1 day'); // Include end date

            $date_range = new DatePeriod($start, new DateInterval('P1D'), $end);

            // Track monthly patterns to avoid duplicates
            $monthly_patterns_used = [];

            foreach ($date_range as $date) {
                $current_date = $date->format('Y-m-d');
                $day_of_week = $date->format('N'); // 1=Monday, 7=Sunday
                $day_of_month = $date->format('j');
                $month_year = $date->format('F Y');
                $year_month = $date->format('Y-m');

                // Determine number of transactions for this day
                $transactions_today = rand(1, $max_transactions_per_day);

                // Weekend has fewer transactions
                if ($day_of_week >= 6) {
                    $transactions_today = rand(0, 2);
                }

                // Beginning of month has more bills
                if ($day_of_month <= 5) {
                    $transactions_today += rand(0, 2);
                }

                $transactions_added = 0;

                for ($i = 0; $i < $transactions_today && $transactions_added < $transactions_today; $i++) {
                    // Select a random template based on selected patterns
                    $available_templates = [];

                    if (!empty($patterns)) {
                        foreach ($templates as $template) {
                            if (in_array($template['category'], $patterns)) {
                                $available_templates[] = $template;
                            }
                        }
                    } else {
                        $available_templates = $templates;
                    }

                    if (empty($available_templates)) {
                        break;
                    }

                    // Weighted selection based on frequency
                    $selected_template = null;
                    $attempts = 0;

                    while ($selected_template === null && $attempts < 20) {
                        $random_template = $available_templates[array_rand($available_templates)];

                        // Check frequency
                        $should_generate = true;
                        $frequency_key = $random_template['frequency'] . '_' . $random_template['template_id'] . '_' . $year_month;

                        if ($random_template['frequency'] === 'daily') {
                            // Daily: always generate
                            $should_generate = true;
                        } elseif ($random_template['frequency'] === 'weekly') {
                            // Weekly: generate once per week (same day)
                            if (!isset($weekly_generated[$random_template['template_id']][$date->format('W')])) {
                                $weekly_generated[$random_template['template_id']][$date->format('W')] = true;
                                $should_generate = true;
                            } else {
                                $should_generate = false;
                            }
                        } elseif ($random_template['frequency'] === 'biweekly') {
                            // Biweekly: generate every 2 weeks
                            $week_number = floor($date->format('W') / 2);
                            if (!isset($biweekly_generated[$random_template['template_id']][$week_number])) {
                                $biweekly_generated[$random_template['template_id']][$week_number] = true;
                                $should_generate = true;
                            } else {
                                $should_generate = false;
                            }
                        } elseif ($random_template['frequency'] === 'monthly') {
                            // Monthly: generate once per month
                            if (!isset($monthly_patterns_used[$random_template['template_id']][$year_month])) {
                                $monthly_patterns_used[$random_template['template_id']][$year_month] = true;
                                $should_generate = true;
                            } else {
                                $should_generate = false;
                            }
                        }

                        if ($should_generate) {
                            $selected_template = $random_template;
                        }

                        $attempts++;
                    }

                    if (!$selected_template) {
                        continue;
                    }

                    // Calculate amount
                    $amount = round(rand($selected_template['amount_min'] * 100, $selected_template['amount_max'] * 100) / 100, 2);

                    // Generate description
                    $description = $selected_template['description_pattern'];
                    $description = str_replace('{month}', $date->format('F'), $description);
                    $description = str_replace('{year}', $date->format('Y'), $description);
                    $description = str_replace('{unit}', rand(1, 50), $description);
                    $description = str_replace('{item}', ['Gadgets', 'Clothing', 'Books', 'Home Decor', 'Electronics'][array_rand(['Gadgets', 'Clothing', 'Books', 'Home Decor', 'Electronics'])], $description);

                    // Determine transaction amount (positive or negative)
                    $amount_value = $amount;
                    $transaction_type = $selected_template['transaction_type'];

                    if (in_array($transaction_type, ['withdrawal', 'transfer_out', 'bill_payment', 'subscription'])) {
                        $amount_value = -$amount;
                        $type_display = $transaction_type;
                    } else {
                        $type_display = $transaction_type;
                    }

                    // Update running balance
                    $current_balance += $amount_value;

                    // Insert transaction
                    $stmt = $pdo->prepare("
                        INSERT INTO transactions (account_id, type, amount, description, created_at) 
                        VALUES (?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $account['account_id'],
                        $type_display,
                        abs($amount),
                        $description,
                        $current_date . ' ' . sprintf('%02d:%02d:00', rand(0, 23), rand(0, 59))
                    ]);

                    $generated[] = [
                        'date' => $current_date,
                        'merchant' => $selected_template['merchant_name'],
                        'amount' => $amount,
                        'type' => $type_display,
                        'description' => $description
                    ];

                    $transactions_added++;
                    $generatedCount++;
                }
            }

            // Update final balance
            $stmt = $pdo->prepare("UPDATE accounts SET balance = ? WHERE account_id = ?");
            $stmt->execute([$current_balance, $account['account_id']]);

            $pdo->commit();

            // Send notification to user
            $userStmt = $pdo->prepare("SELECT email, full_name FROM users WHERE user_id = ?");
            $userStmt->execute([$user_id]);
            $userData = $userStmt->fetch();

            $subject = "New Transactions Generated - Oakshire Finance";
            $message = "
                <html>
                <body style='font-family: Arial, sans-serif;'>
                    <h2 style='color: #0a2540;'>Transaction History Generated</h2>
                    <p>Dear <strong>" . htmlspecialchars($userData['full_name']) . "</strong>,</p>
                    <p>We've generated <strong>$generatedCount</strong> transactions for your account for the period $start_date to $end_date.</p>
                    <p>Your updated balance is: <strong>$" . number_format($current_balance, 2) . "</strong></p>
                    <p>You can view all your transactions by logging into your account.</p>
                    <br>
                    <p>Best regards,<br>Oakshire Finance Team</p>
                </body>
                </html>
            ";

            sendNotification($userData['email'], $subject, $message);

            $_SESSION['generated_count'] = $generatedCount;
            $_SESSION['generated_user'] = $userData['full_name'];
            header("Location: generate-transactions.php?success=1");
            exit();

        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Generation failed: " . $e->getMessage();
        }
    }
}

// Handle success message from redirect
if (isset($_GET['success']) && isset($_SESSION['generated_count'])) {
    $success = "Successfully generated " . $_SESSION['generated_count'] . " transactions for " . $_SESSION['generated_user'] . "!";
    unset($_SESSION['generated_count']);
    unset($_SESSION['generated_user']);
}

// Get admin info for sidebar
$adminId = $_SESSION['user_id'];
$adminInfo = $pdo->prepare("SELECT full_name FROM users WHERE user_id = ?");
$adminInfo->execute([$adminId]);
$admin = $adminInfo->fetch();

// Get template categories for filter
$categories = $pdo->query("SELECT DISTINCT category FROM transaction_templates WHERE is_active = 1")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Generate Transactions - Oakshire Finance Admin</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --success-green: #2e7d32;
            --error-red: #dc3545;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: var(--gray-50);
            color: var(--gray-700);
        }

        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 20px;
            color: white;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
        }

        .nav-menu {
            padding: 24px 16px;
        }

        .nav-item {
            margin-bottom: 4px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            font-weight: 500;
        }

        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-700);
        }

        .content-area {
            padding: 32px;
        }

        .card {
            background: var(--white);
            border-radius: 24px;
            border: 1px solid var(--gray-200);
            padding: 24px;
            margin-bottom: 24px;
        }

        .card h2 {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
            color: var(--gray-700);
        }

        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: var(--gray-600);
            margin-bottom: 8px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px 16px;
            font-size: 14px;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            transition: var(--transition);
            outline: none;
        }

        .form-group input:focus,
        .form-group select:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .btn-primary {
            padding: 12px 24px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        .checkbox-group {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 12px;
            margin-top: 12px;
        }

        .checkbox-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .checkbox-item input {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .checkbox-item label {
            margin: 0;
            cursor: pointer;
            font-size: 13px;
        }

        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
        }

        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .checkbox-group {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon"><i class="fas fa-building-columns"></i></div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>
            <nav class="nav-menu">
                <div class="nav-item"><a href="dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>
                        Dashboard</a></div>
                <div class="nav-item"><a href="manage-users.php" class="nav-link"><i class="fas fa-users"></i> Manage
                        Users</a></div>
                <div class="nav-item"><a href="manage-balance.php" class="nav-link"><i class="fas fa-wallet"></i> Manage
                        Balance</a></div>
                <div class="nav-item"><a href="generate-transactions.php" class="nav-link active"><i
                            class="fas fa-sync-alt"></i> Generate Transactions</a></div>
                <div class="nav-item"><a href="manage-loans.php" class="nav-link"><i
                            class="fas fa-hand-holding-usd"></i> Manage Loans</a></div>
                <div class="nav-item"><a href="manage-investments.php" class="nav-link"><i class="fas fa-chart-pie"></i>
                        Manage Investments</a></div>
                <div class="nav-item"><a href="recent_transactions.php" class="nav-link"><i
                            class="fas fa-exchange-alt"></i> Transactions</a></div>
            </nav>
            <div class="logout-section">
                <a href="../logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </aside>

        <main class="main-content">
            <header class="top-header">
                <button class="hamburger" id="hamburger"><i class="fas fa-bars"></i></button>
                <div class="page-title">
                    <h1>Generate Transactions</h1>
                </div>
                <div class="user-menu">
                    <div class="user-avatar"><i class="fas fa-user-shield"></i></div>
                </div>
            </header>

            <div class="content-area">
                <?php if ($success): ?>
                    <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= $success ?></div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= $error ?></div>
                <?php endif; ?>

                <div class="card">
                    <h2><i class="fas fa-chart-line"></i> Generate Realistic Transaction History</h2>
                    <p style="color: var(--gray-600); margin-bottom: 20px; font-size: 14px;">
                        This tool will automatically generate realistic transaction patterns for the selected user based
                        on pre-defined templates.
                        Transactions will be spread across the selected date range with realistic frequencies and
                        amounts.
                    </p>

                    <form method="POST">
                        <div class="form-row">
                            <div class="form-group">
                                <label><i class="fas fa-user"></i> Select User</label>
                                <select name="user_id" required>
                                    <option value="">-- Select User --</option>
                                    <?php foreach ($users as $user): ?>
                                        <option value="<?= $user['user_id'] ?>">
                                            <?= htmlspecialchars($user['full_name']) ?> - <?= $user['account_number'] ?>
                                            ($<?= number_format($user['balance'], 2) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label><i class="fas fa-calendar-alt"></i> Start Date</label>
                                <input type="date" name="start_date"
                                    value="<?= date('Y-m-01', strtotime('-3 months')) ?>" required>
                            </div>
                            <div class="form-group">
                                <label><i class="fas fa-calendar-alt"></i> End Date</label>
                                <input type="date" name="end_date" value="<?= date('Y-m-d') ?>" required>
                            </div>
                        </div>

                        <div class="form-group">
                            <label><i class="fas fa-filter"></i> Transaction Categories (Select which patterns to
                                use)</label>
                            <div class="checkbox-group">
                                <?php foreach ($categories as $cat): ?>
                                    <div class="checkbox-item">
                                        <input type="checkbox" name="patterns[]" value="<?= $cat['category'] ?>"
                                            id="cat_<?= $cat['category'] ?>" checked>
                                        <label for="cat_<?= $cat['category'] ?>">
                                            <?php
                                            $icons = [
                                                'Income' => '💰',
                                                'Shopping' => '🛍️',
                                                'Dining' => '🍽️',
                                                'Utilities' => '💡',
                                                'Subscription' => '📺',
                                                'Transport' => '🚗',
                                                'Cash' => '💵',
                                                'Transfer' => '🔄',
                                                'Investment' => '📈'
                                            ];
                                            echo $icons[$cat['category']] ?? '📊';
                                            ?>
                                            <?= ucfirst($cat['category']) ?>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label><i class="fas fa-chart-bar"></i> Max Transactions Per Day</label>
                                <select name="max_transactions">
                                    <option value="2">Low (1-2 per day)</option>
                                    <option value="3" selected>Medium (1-3 per day)</option>
                                    <option value="5">High (2-5 per day)</option>
                                    <option value="8">Very High (3-8 per day)</option>
                                </select>
                            </div>
                        </div>

                        <div
                            style="background: var(--gray-100); padding: 16px; border-radius: 12px; margin-bottom: 20px;">
                            <p style="font-size: 13px; color: var(--gray-600); margin-bottom: 8px;">
                                <i class="fas fa-info-circle"></i> <strong>How it works:</strong>
                            </p>
                            <ul style="font-size: 12px; color: var(--gray-600); margin-left: 20px;">
                                <li>Transactions are generated based on realistic spending patterns (salary, bills,
                                    groceries, etc.)</li>
                                <li>Weekends have fewer transactions, beginning of month has more bills</li>
                                <li>Monthly patterns (salary, bills) appear once per month</li>
                                <li>Weekly patterns (groceries, dining) appear once per week</li>
                                <li>Account balance updates automatically based on generated transactions</li>
                                <li>User receives email notification when transactions are generated</li>
                            </ul>
                        </div>

                        <button type="submit" name="generate" class="btn-primary">
                            <i class="fas fa-play"></i> Generate Transactions
                        </button>
                    </form>
                </div>


        </main>
    </div>

    <script>
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');
        if (hamburger) hamburger.addEventListener('click', () => sidebar.classList.toggle('mobile-open'));

        document.addEventListener('click', (event) => {
            if (window.innerWidth <= 1024) {
                if (!sidebar.contains(event.target) && !hamburger.contains(event.target) && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });
    </script>
</body>

</html>