<?php
// Random Transaction Generator
include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/header.php");

$pageName = "Generate Random Transactions";

$selected_user_id = isset($_POST['user_id']) ? $_POST['user_id'] : null;
$generate_clicked = isset($_POST['generate']);
$start_date = isset($_POST['start_date']) ? $_POST['start_date'] : null;
$end_date   = isset($_POST['end_date'])   ? $_POST['end_date']   : null;

// ─── Sender names ─────────────────────────────────────────────────────────────
$sender_names = [
    // European
    "James Richardson", "Emma Thompson", "Oliver Bennett", "Sophie Clarke",
    "Liam Harrison", "Charlotte Evans", "Noah Williams", "Isabella Martin",
    "George Campbell", "Amelia Foster", "Harry Mitchell", "Grace Turner",
    "Edward Hughes", "Florence Baker", "Arthur Collins", "Matilda Wright",
    "Sebastian Moore", "Arabella Scott", "Frederick Hill", "Penelope Adams",
    "Theodore Walker", "Rosalind Green", "Barnaby White", "Cordelia Hall",
    "Maximilian King", "Beatrice Lane", "Alistair Wood", "Clarissa Shaw",
    "Leopold Stone", "Vivienne Price",
    // American
    "Michael Johnson", "Ashley Davis", "Christopher Wilson", "Jessica Anderson",
    "Matthew Taylor", "Amanda Martinez", "Joshua Thomas", "Stephanie White",
    "Brandon Harris", "Lauren Robinson", "Tyler Nelson", "Megan Carter",
    "Nathan Phillips", "Brittany Campbell", "Dylan Mitchell", "Amber Roberts",
    "Caleb Turner", "Samantha Parker", "Logan Evans", "Kayla Edwards",
    "Hunter Collins", "Vanessa Stewart", "Blake Morris", "Cassandra Reed",
    "Garrett Cook", "Danielle Morgan", "Spencer Bell", "Paige Murphy",
    "Preston Bailey", "Shelby Rivera",
    // Asian
    "Wei Zhang", "Yuki Tanaka", "Raj Patel", "Priya Sharma",
    "Chen Liu", "Sakura Yamamoto", "Arjun Singh", "Min-Ji Kim",
    "Hiroshi Nakamura", "Mei Lin Chen", "Vikram Mehta", "Ananya Krishnan",
    "Jae-Won Park", "Xiao Ming Wang", "Takeshi Suzuki", "Deepa Nair",
    "Soo-Jin Lee", "Ravi Chandrasekhar", "Haruto Watanabe", "Pooja Iyer",
    "Dong-Hyun Choi", "Aiko Kobayashi", "Suresh Pillai", "Nayeon Jung",
    "Kenji Ishida", "Lavanya Venkatesh", "Byung-Ho Yoon", "Fumiko Ito",
    "Sandeep Bose", "Ji-Yeon Kwon",
    // Middle Eastern & African
    "Omar Al-Rashid", "Fatima Al-Zahra", "Khalid Al-Mansouri", "Layla Hassan",
    "Tariq Osman", "Amira Benali", "Yousef Al-Farsi", "Nadia Mahmoud",
    "Karim El-Amin", "Sara Al-Habsi",
];

// ─── Recipient names (companies) ─────────────────────────────────────────────
$recipient_names = [
    // Global Tech & Software
    "Amazon Web Services", "Netflix Inc", "Apple Services",
    "Google Pay", "Microsoft Corporation", "Spotify Premium",
    "Adobe Systems", "Salesforce Inc", "Oracle Corporation",
    "Zoom Video Communications", "Slack Technologies", "Dropbox Inc",
    "LinkedIn Premium", "GitHub Inc", "Cloudflare Inc",
    // Global Retail & Fashion
    "Walmart Inc", "IKEA Group", "H&M Fashion",
    "Zara International", "ASOS Online", "Uniqlo Co",
    "Marks and Spencer", "John Lewis", "Target Corporation",
    "Costco Wholesale", "eBay Inc", "Alibaba Group",
    // Global Food & Dining
    "McDonald's Corp", "Starbucks Coffee", "KFC International",
    "Subway Restaurants", "Pizza Hut", "Domino's Pizza",
    "Deliveroo Ltd", "DoorDash Inc", "Uber Eats",
    // Global Finance & Payments
    "PayPal Inc", "Stripe Payments", "Wise Transfers",
    "Revolut Ltd", "Square Inc", "Western Union",
    "Mastercard Inc", "Visa International", "American Express",
    // Global Utilities & Energy
    "Shell Energy", "BP Fuel", "ExxonMobil Corp",
    "E.ON Energy", "British Gas", "TotalEnergies SE",
    // Global Travel & Transport
    "Uber Technologies", "Airbnb Inc", "Emirates Airlines",
    "British Airways", "Delta Air Lines", "Singapore Airlines",
    "DHL Express", "FedEx Corporation", "UPS Logistics",
    // Global Healthcare & Insurance
    "Bupa Health Insurance", "AXA Insurance", "Allianz Group",
    "CVS Health", "Boots Pharmacy", "Lloyds Pharmacy",
    // Global Telecom
    "Vodafone Group", "AT&T Inc", "T-Mobile US",
    "Verizon Communications", "Deutsche Telekom", "NTT Docomo",
];

// ─── Bank names ───────────────────────────────────────────────────────────────
$bank_names = [
    // European
    "Barclays Bank", "HSBC Holdings", "Deutsche Bank",
    "BNP Paribas", "Santander Bank", "ING Group",
    "Credit Suisse", "UBS Group", "Lloyds Banking Group",
    "NatWest Group", "Societe Generale", "UniCredit Bank",
    "Rabobank", "ABN AMRO Bank", "Commerzbank",
    // American
    "JPMorgan Chase", "Bank of America", "Wells Fargo",
    "Citibank", "Goldman Sachs", "Morgan Stanley",
    "US Bancorp", "PNC Financial", "Capital One",
    "TD Bank USA", "Charles Schwab", "American Express Bank",
    // Asian
    "ICBC China", "DBS Bank Singapore", "HDFC Bank India",
    "Mitsubishi UFJ", "Standard Chartered", "Bank of Tokyo",
    "China Construction Bank", "ANZ Bank", "Maybank Malaysia",
    "State Bank of India", "Sumitomo Mitsui", "OCBC Bank",
    // Middle Eastern
    "Emirates NBD", "Qatar National Bank", "Arab National Bank",
    "First Abu Dhabi Bank", "Kuwait Finance House",
];

// ─── Bank → Country mapping ───────────────────────────────────────────────────
$bank_names_country = [
    "Barclays Bank"           => "United Kingdom",
    "HSBC Holdings"           => "United Kingdom",
    "Lloyds Banking Group"    => "United Kingdom",
    "NatWest Group"           => "United Kingdom",
    "Standard Chartered"      => "United Kingdom",
    "Deutsche Bank"           => "Germany",
    "Commerzbank"             => "Germany",
    "BNP Paribas"             => "France",
    "Societe Generale"        => "France",
    "Santander Bank"          => "Spain",
    "ING Group"               => "Netherlands",
    "Rabobank"                => "Netherlands",
    "ABN AMRO Bank"           => "Netherlands",
    "Credit Suisse"           => "Switzerland",
    "UBS Group"               => "Switzerland",
    "UniCredit Bank"          => "Italy",
    "JPMorgan Chase"          => "United States",
    "Bank of America"         => "United States",
    "Wells Fargo"             => "United States",
    "Citibank"                => "United States",
    "Goldman Sachs"           => "United States",
    "Morgan Stanley"          => "United States",
    "US Bancorp"              => "United States",
    "PNC Financial"           => "United States",
    "Capital One"             => "United States",
    "TD Bank USA"             => "United States",
    "Charles Schwab"          => "United States",
    "American Express Bank"   => "United States",
    "ICBC China"              => "China",
    "China Construction Bank" => "China",
    "DBS Bank Singapore"      => "Singapore",
    "OCBC Bank"               => "Singapore",
    "HDFC Bank India"         => "India",
    "State Bank of India"     => "India",
    "Mitsubishi UFJ"          => "Japan",
    "Sumitomo Mitsui"         => "Japan",
    "Bank of Tokyo"           => "Japan",
    "Maybank Malaysia"        => "Malaysia",
    "ANZ Bank"                => "Australia",
    "Emirates NBD"            => "United Arab Emirates",
    "Qatar National Bank"     => "Qatar",
    "Arab National Bank"      => "Saudi Arabia",
    "First Abu Dhabi Bank"    => "United Arab Emirates",
    "Kuwait Finance House"    => "Kuwait",
];

// ─── Credit descriptions ──────────────────────────────────────────────────────
$credit_descriptions = [
    "Monthly salary payment", "Weekly wage deposit",
    "Bonus and performance incentive", "Holiday pay credited",
    "Overtime pay received", "Commission payment received",
    "Annual increment credited", "Severance pay received",
    "Freelance project payment", "Consulting fee received",
    "Business sales revenue", "Client invoice payment",
    "Contract milestone payment", "Retainer fee received",
    "Service charge collected", "Professional fee credited",
    "Investment dividend payout", "Stock dividend credited",
    "Bond interest payment", "Mutual fund redemption",
    "Crypto asset sale proceeds", "Real estate rental income",
    "Pension fund disbursement", "Annuity payment received",
    "Refund for cancelled order", "Insurance claim settlement",
    "Tax refund credited", "Overpayment refund received",
    "Warranty claim settlement", "Cashback reward credited",
    "Loyalty points redeemed", "Chargeback reversal",
    "Transfer from savings account", "Mobile wallet transfer",
    "Family support payment", "Gift received from relative",
    "Crowdfunding proceeds received", "Grant disbursement",
    "Scholarship payment credited", "Bursary fund received",
    "Loan disbursement received", "Credit facility drawdown",
    "Mortgage overpayment refund", "Bridging loan credited",
];

// ─── Debit descriptions ───────────────────────────────────────────────────────
$debit_descriptions = [
    "Online shopping payment", "Supermarket grocery shopping",
    "Department store purchase", "Electronics purchase",
    "Clothing and apparel purchase", "Home furnishing payment",
    "Bookstore purchase", "Sports equipment payment",
    "Pharmacy and toiletries", "Jewellery store purchase",
    "Restaurant and dining", "Fast food purchase",
    "Coffee shop payment", "Food delivery order",
    "Meal kit subscription", "Catering service payment",
    "Bar and entertainment", "Bakery purchase",
    "Electricity bill payment", "Water bill payment",
    "Gas and heating bill", "Internet subscription",
    "Mobile phone bill", "Landline telephone bill",
    "Council tax payment", "Home insurance premium",
    "Fuel and gas purchase", "Public transport fare",
    "Taxi and rideshare payment", "Flight ticket purchase",
    "Hotel accommodation", "Car rental payment",
    "Parking fee payment", "Toll road charge",
    "Car maintenance service", "Vehicle insurance premium",
    "Medical and healthcare", "Dental treatment payment",
    "Gym membership fee", "Pharmacy prescription",
    "Optical care payment", "Therapy session fee",
    "Wellness and spa payment", "Vitamin supplement purchase",
    "Streaming service subscription", "Gaming platform payment",
    "Cinema and events ticket", "Music streaming subscription",
    "Magazine subscription", "Software licence fee",
    "Cloud storage subscription", "Online course payment",
    "Transfer to beneficiary", "Loan repayment",
    "Credit card payment", "Mortgage instalment",
    "Insurance premium payment", "Investment contribution",
    "Pension contribution", "Utility bill payment",
];

// ─── Transaction types ────────────────────────────────────────────────────────
$trans_types = [
    "Local transfer", "Interbank transfer", "Online banking",
    "Deposit", "Withdrawal",
];

// ─── Helper functions ─────────────────────────────────────────────────────────
function randomDate($start_date = null, $end_date = null) {
    if ($start_date && $end_date) {
        $random_timestamp = rand(strtotime($start_date), strtotime($end_date));
        return date('Y-m-d', $random_timestamp);
    }
    return date('Y-m-d', strtotime("-" . rand(0, 90) . " days"));
}

function randomTime() {
    return str_pad(rand(6, 22), 2, '0', STR_PAD_LEFT) . ':' .
           str_pad(rand(0, 59), 2, '0', STR_PAD_LEFT) . ':' .
           str_pad(rand(0, 59), 2, '0', STR_PAD_LEFT);
}

function randomAccountNumber() {
    return str_pad(rand(1000000000, 9999999999), 10, '0', STR_PAD_LEFT);
}

function randomRefId($date) {
    return str_replace('-', '', $date) . strtoupper(substr(uniqid(), -8));
}

// ─── Get all users ────────────────────────────────────────────────────────────
$sql = "SELECT * FROM users ORDER BY id ASC";
$stmt = $conn->prepare($sql);
$stmt->execute();
$all_users = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($all_users)) {
    die("No users found in the database!");
}

echo "<div class='content-wrapper'>";
echo "<section class='content-header'><h1>Random Transaction Generator</h1></section>";
echo "<section class='content'>";

// ─── Selection form ───────────────────────────────────────────────────────────
if (!$generate_clicked) { ?>
    <div class="box box-primary">
        <div class="box-header with-border">
            <h3 class="box-title">Generate Random Transactions</h3>
        </div>
        <form method="POST">
            <div class="box-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Select User (Optional - Leave blank for all users)</label>
                            <select name="user_id" class="form-control select2" style="width:100%;">
                                <?php foreach ($all_users as $u): ?>
                                    <option value="<?= $u['id'] ?>">
                                        <?= ucwords($u['firstname'] . " " . $u['lastname']) ?> —
                                        Acct: <?= $u['acct_no'] ?> —
                                        Balance: <?= number_format($u['acct_balance'], 2) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Number of Transactions</label>
                            <input type="number" name="num_transactions" class="form-control"
                                   value="20" min="1" max="100" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Start Date</label>
                            <input type="date" name="start_date" class="form-control"
                                   value="<?= date('Y-m-d', strtotime('-30 days')) ?>" required>
                            <small class="text-muted">Transactions will be generated from this date</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>End Date</label>
                            <input type="date" name="end_date" class="form-control"
                                   value="<?= date('Y-m-d') ?>" required>
                            <small class="text-muted">Transactions will be generated up to this date</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="box-footer">
                <button type="submit" name="generate" class="btn btn-primary">
                    <i class="fa fa-random"></i> Generate Transactions
                </button>
            </div>
        </form>
    </div>
<?php
    echo "</section></div>";
    include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/footer.php");
    exit;
}

// ─── Processing ───────────────────────────────────────────────────────────────
$NUMBER_OF_TRANSACTIONS = isset($_POST['num_transactions']) ? intval($_POST['num_transactions']) : 20;

if ($start_date && $end_date && strtotime($start_date) > strtotime($end_date)) {
    echo "<div class='alert alert-danger'>Start date cannot be after end date!</div>";
    echo "</section></div>";
    include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/footer.php");
    exit;
}

if ($selected_user_id && $selected_user_id != '') {
    $sql = "SELECT * FROM users WHERE id = :user_id";
    $stmt = $conn->prepare($sql);
    $stmt->execute(['user_id' => $selected_user_id]);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($users)) {
        echo "<div class='alert alert-danger'>User not found!</div>";
        echo "</section></div>";
        include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/footer.php");
        exit;
    }
    $target_mode = "specific user: <strong>" . $users[0]['firstname'] . " " . $users[0]['lastname'] . "</strong>";
} else {
    $users = $all_users;
    $target_mode = "<strong>all users (randomly)</strong>";
}

// Balance tracker
$balanceTracker = [];
foreach ($users as $u) {
    $balanceTracker[$u['id']] = (float) $u['acct_balance'];
}

$transactions_created = 0;
$errors               = [];
$pendingTransactions  = [];

for ($i = 0; $i < $NUMBER_OF_TRANSACTIONS; $i++) {
    $user            = $users[array_rand($users)];
    $user_id         = $user['id'];
    $current_balance = $balanceTracker[$user_id];
    $is_credit       = (rand(0, 1) == 1);
    $amount          = rand(500, 50000);

    if ($is_credit) {
        $transaction_type = "credit";
        $account_name     = $sender_names[array_rand($sender_names)];
        $description      = $credit_descriptions[array_rand($credit_descriptions)];
        $new_balance      = $current_balance + $amount;
    } else {
        $transaction_type = "debit";
        $account_name     = $recipient_names[array_rand($recipient_names)];
        $description      = $debit_descriptions[array_rand($debit_descriptions)];

        if ($current_balance < $amount) {
            $amount = max(100, (int)($current_balance - rand(100, 500)));
            if ($amount <= 0) {
                $amount           = rand(100, 500);
                $is_credit        = true;
                $transaction_type = "credit";
                $account_name     = $sender_names[array_rand($sender_names)];
                $description      = $credit_descriptions[array_rand($credit_descriptions)];
                $new_balance      = $current_balance + $amount;
            } else {
                $new_balance = $current_balance - $amount;
            }
        } else {
            $new_balance = $current_balance - $amount;
        }
    }

    $balanceTracker[$user_id] = $new_balance;

    $trans_date  = randomDate($start_date, $end_date);
    $trans_time  = randomTime();
    $trans_type  = $trans_types[array_rand($trans_types)];
    $bank_name   = $bank_names[array_rand($bank_names)];
    $bank_country = $bank_names_country[$bank_name]; // ← auto-matched to bank
    $account_number = randomAccountNumber();
    $refrence_id    = randomRefId($trans_date);
    $trans_status   = "completed";
    $created_at     = $trans_date . ' ' . $trans_time;

    $pendingTransactions[] = [
        'user'             => $user,
        'user_id'          => $user_id,
        'amount'           => $amount,
        'is_credit'        => $is_credit,
        'transaction_type' => $transaction_type,
        'trans_type'       => $trans_type,
        'account_name'     => $account_name,
        'account_number'   => $account_number,
        'bank_name'        => $bank_name,
        'bank_country'     => $bank_country,
        'description'      => $description,
        'trans_date'       => $trans_date,
        'trans_time'       => $trans_time,
        'created_at'       => $created_at,
        'refrence_id'      => $refrence_id,
        'trans_status'     => $trans_status,
        'new_balance'      => $new_balance,
    ];
}

// Sort chronologically
usort($pendingTransactions, function ($a, $b) {
    return strcmp($a['created_at'], $b['created_at']);
});

echo "<div class='box box-primary'>";
echo "<div class='box-header with-border'>";
echo "<h3 class='box-title'>Generating $NUMBER_OF_TRANSACTIONS Transactions for $target_mode</h3>";
echo "<p class='text-muted' style='margin-top:5px;'>Date range: <strong>$start_date</strong> to <strong>$end_date</strong></p>";
echo "</div>";
echo "<div class='box-body'>";

foreach ($pendingTransactions as $idx => $tx) {
    try {
        $sql = "INSERT INTO transactions 
                    (amount, refrence_id, account_name, account_number, bank_name, bank_country,
                     user_id, trans_type, transaction_type, trans_status, description,
                     trans_date, trans_time)
                VALUES
                    (:amount, :refrence_id, :account_name, :account_number, :bank_name, :bank_country,
                     :user_id, :trans_type, :transaction_type, :trans_status, :description,
                     :trans_date, :trans_time)";
        $insertStmt = $conn->prepare($sql);
        $insertStmt->execute([
            'amount'           => $tx['amount'],
            'refrence_id'      => $tx['refrence_id'],
            'account_name'     => $tx['account_name'],
            'account_number'   => $tx['account_number'],
            'bank_name'        => $tx['bank_name'],
            'bank_country'     => $tx['bank_country'],
            'user_id'          => $tx['user_id'],
            'trans_type'       => $tx['trans_type'],
            'transaction_type' => $tx['transaction_type'],
            'trans_status'     => $tx['trans_status'],
            'description'      => $tx['description'],
            'trans_date'       => $tx['trans_date'],
            'trans_time'       => $tx['trans_time'],
        ]);

        $lastId = $conn->lastInsertId();

        // Force-update created_at to override MySQL DEFAULT CURRENT_TIMESTAMP
        try {
            $conn->prepare("UPDATE transactions SET created_at = :val WHERE trans_id = :tid")
                 ->execute(['val' => $tx['created_at'], 'tid' => $lastId]);
        } catch (Exception $e) { /* column may not exist */ }

        try {
            $conn->prepare("UPDATE transactions SET createdAt = :val WHERE trans_id = :tid")
                 ->execute(['val' => $tx['created_at'], 'tid' => $lastId]);
        } catch (Exception $e) { /* column may not exist */ }

        $conn->prepare("UPDATE transactions SET trans_date = :td, trans_time = :tt WHERE trans_id = :tid")
             ->execute(['td' => $tx['trans_date'], 'tt' => $tx['trans_time'], 'tid' => $lastId]);

        $transactions_created++;

        $typeLabel = $tx['is_credit'] ? 'Credit' : 'Debit';
        $typeClass = $tx['is_credit'] ? 'success' : 'danger';
        $direction = $tx['is_credit'] ? 'from' : 'to';

        echo "<p class='text-$typeClass'>";
        echo "✓ #" . ($idx + 1) . " ";
        echo "<span class='label label-$typeClass'>$typeLabel</span> ";
        echo "<strong>" . number_format($tx['amount'], 2) . "</strong> ";
        echo "$direction <strong>" . htmlspecialchars($tx['account_name']) . "</strong> ";
        echo "via <em>" . htmlspecialchars($tx['trans_type']) . "</em> ";
        echo "for <strong>" . $tx['user']['firstname'] . " " . $tx['user']['lastname'] . "</strong> ";
        echo "on <strong>" . $tx['trans_date'] . " " . $tx['trans_time'] . "</strong>";
        echo " — <small class='text-muted'>" . htmlspecialchars($tx['description']) . "</small>";
        echo "</p>";

    } catch (Exception $e) {
        $errors[] = "Transaction #" . ($idx + 1) . ": " . $e->getMessage();
        echo "<p class='text-danger'>✗ Error on transaction #" . ($idx + 1) . ": " . htmlspecialchars($e->getMessage()) . "</p>";
    }
}

// Update balances
foreach ($balanceTracker as $uid => $finalBalance) {
    try {
        $conn->prepare("UPDATE users SET acct_balance = :balance WHERE id = :id")
             ->execute(['balance' => $finalBalance, 'id' => $uid]);
    } catch (Exception $e) {
        $errors[] = "Balance update for user #$uid: " . $e->getMessage();
    }
}

echo "</div>";
echo "<div class='box-footer'>";
echo "<div class='alert alert-success'>";
echo "<h4><i class='icon fa fa-check'></i> Complete!</h4>";
echo "<strong>$transactions_created</strong> transactions created successfully out of $NUMBER_OF_TRANSACTIONS attempts.";
echo "<br>All transactions inserted with correct dates between <strong>$start_date</strong> and <strong>$end_date</strong>.";
echo "</div>";

if (!empty($errors)) {
    echo "<div class='alert alert-warning'><h4><i class='icon fa fa-warning'></i> Errors:</h4><ul>";
    foreach ($errors as $error) {
        echo "<li>" . htmlspecialchars($error) . "</li>";
    }
    echo "</ul></div>";
}

echo "<a href='./autotrans.php' class='btn btn-default'><i class='fa fa-refresh'></i> Generate More</a> ";
echo "<a href='./transactions.php' class='btn btn-info'><i class='fa fa-list'></i> View All Transactions</a> ";
echo "<a href='./dashboard.php' class='btn btn-primary'><i class='fa fa-dashboard'></i> Back to Dashboard</a>";
echo "</div></div></section></div>";

include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/footer.php");
?>