<?php
/**
 * Client Data Seeder Script
 * Generates 60 varied client records for testing statistics
 */

// Include the application initialization
require_once 'init.php';

// Sample data arrays for generating varied information
$firstNames = [
    'John', 'Jane', 'Michael', 'Sarah', 'David', 'Emily', 'Robert', 'Jessica', 'William', 'Ashley',
    'James', 'Amanda', 'Christopher', 'Jennifer', 'Daniel', 'Lisa', 'Matthew', 'Nancy', 'Anthony', 'Karen',
    'Mark', 'Betty', 'Donald', 'Helen', 'Steven', 'Sandra', 'Paul', 'Donna', 'Andrew', 'Carol',
    'Joshua', 'Ruth', 'Kenneth', 'Sharon', 'Kevin', 'Michelle', 'Brian', 'Laura', 'George', 'Sarah',
    'Edward', 'Kimberly', 'Ronald', 'Deborah', 'Timothy', 'Dorothy', 'Jason', 'Lisa', 'Jeffrey', 'Nancy',
    'Ryan', 'Karen', 'Jacob', 'Betty', 'Gary', 'Helen', 'Nicholas', 'Sandra', 'Eric', 'Donna'
];

$lastNames = [
    'Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis', 'Rodriguez', 'Martinez',
    'Hernandez', 'Lopez', 'Gonzalez', 'Wilson', 'Anderson', 'Thomas', 'Taylor', 'Moore', 'Jackson', 'Martin',
    'Lee', 'Perez', 'Thompson', 'White', 'Harris', 'Sanchez', 'Clark', 'Ramirez', 'Lewis', 'Robinson',
    'Walker', 'Young', 'Allen', 'King', 'Wright', 'Scott', 'Torres', 'Nguyen', 'Hill', 'Flores',
    'Green', 'Adams', 'Nelson', 'Baker', 'Hall', 'Rivera', 'Campbell', 'Mitchell', 'Carter', 'Roberts',
    'Gomez', 'Phillips', 'Evans', 'Turner', 'Diaz', 'Parker', 'Cruz', 'Edwards', 'Collins', 'Reyes'
];

$cities = [
    'Nairobi', 'Mombasa', 'Kisumu', 'Nakuru', 'Eldoret', 'Thika', 'Malindi', 'Kitale', 'Garissa', 'Kakamega',
    'Nyeri', 'Meru', 'Machakos', 'Kisii', 'Kericho', 'Bungoma', 'Busia', 'Vihiga', 'Siaya', 'Homa Bay',
    'Migori', 'Kisii', 'Nyamira', 'Trans Nzoia', 'Uasin Gishu', 'Nandi', 'Baringo', 'Laikipia', 'Nakuru', 'Narok'
];

$districts = [
    'Central', 'East', 'West', 'North', 'South', 'Downtown', 'Uptown', 'Riverside', 'Hillside', 'Valley',
    'Park', 'Garden', 'Heights', 'Ridge', 'Meadows', 'Woods', 'Springs', 'Lakes', 'Pines', 'Oaks'
];

$states = [
    'Nairobi', 'Mombasa', 'Kisumu', 'Nakuru', 'Uasin Gishu', 'Kakamega', 'Bungoma', 'Busia', 'Vihiga', 'Siaya',
    'Homa Bay', 'Migori', 'Kisii', 'Nyamira', 'Trans Nzoia', 'Nandi', 'Baringo', 'Laikipia', 'Narok', 'Kajiado'
];

$serviceTypes = ['Hotspot', 'PPPoE', 'Others'];
$accountTypes = ['Business', 'Personal'];
$statuses = ['Active', 'Inactive', 'Limited', 'Suspended', 'Banned', 'Disabled'];

// Function to generate random phone number
function generatePhoneNumber() {
    $prefixes = ['254', '2547', '2541', '2542', '2543', '2544', '2545', '2546', '2548', '2549'];
    $prefix = $prefixes[array_rand($prefixes)];
    $suffix = str_pad(rand(0, 99999999), 8, '0', STR_PAD_LEFT);
    return $prefix . $suffix;
}

// Function to generate random email
function generateEmail($firstName, $lastName) {
    $domains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'company.co.ke', 'business.ke'];
    $domain = $domains[array_rand($domains)];
    $variations = ['', '.', '_', rand(1, 99)];
    $variation = $variations[array_rand($variations)];
    return strtolower($firstName . $variation . $lastName . '@' . $domain);
}

// Function to generate random coordinates (Kenya bounds)
function generateCoordinates() {
    $lat = rand(-4700000, -1000000) / 100000; // Kenya latitude range
    $lng = rand(33000000, 42000000) / 100000; // Kenya longitude range
    return $lat . ',' . $lng;
}

// Function to generate random balance
function generateBalance() {
    $balances = [0, 50, 100, 150, 200, 250, 300, 500, 750, 1000, 1500, 2000, 2500, 3000, 5000];
    return $balances[array_rand($balances)];
}

// Function to generate random address
function generateAddress($city) {
    $streets = ['Main St', 'First Ave', 'Second Ave', 'Oak St', 'Pine St', 'Cedar Ave', 'Maple Dr', 'Elm St', 'Park Ave', 'Broadway'];
    $street = $streets[array_rand($streets)];
    $number = rand(1, 9999);
    return $number . ' ' . $street . ', ' . $city;
}

// Function to generate random zip code
function generateZipCode() {
    return str_pad(rand(10000, 99999), 5, '0', STR_PAD_LEFT);
}

echo "Starting client data seeding...\n";

try {
    // Get admin ID for created_by field
    $admin = ORM::for_table('tbl_users')->where('user_type', 'SuperAdmin')->find_one();
    $adminId = $admin ? $admin['id'] : 1;

    $successCount = 0;
    $errorCount = 0;

    for ($i = 1; $i <= 60; $i++) {
        try {
            // Generate random data
            $firstName = $firstNames[array_rand($firstNames)];
            $lastName = $lastNames[array_rand($lastNames)];
            $fullname = $firstName . ' ' . $lastName;
            $username = generatePhoneNumber();
            $email = generateEmail($firstName, $lastName);
            $city = $cities[array_rand($cities)];
            $district = $districts[array_rand($districts)];
            $state = $states[array_rand($states)];
            $serviceType = $serviceTypes[array_rand($serviceTypes)];
            $accountType = $accountTypes[array_rand($accountTypes)];
            $status = $statuses[array_rand($statuses)];
            $balance = generateBalance();
            $coordinates = generateCoordinates();
            $address = generateAddress($city);
            $zip = generateZipCode();
            $phonenumber = generatePhoneNumber();
            
            // Generate passwords
            $password = 'client' . $i . 'pass';
            $pppoePassword = 'pppoe' . $i . 'pass';
            
            // Create customer record
            $customer = ORM::for_table('tbl_customers')->create();
            $customer->username = $username;
            $customer->password = $password;
            $customer->pppoe_password = $pppoePassword;
            $customer->email = $email;
            $customer->account_type = $accountType;
            $customer->fullname = $fullname;
            $customer->address = $address;
            $customer->created_by = $adminId;
            $customer->phonenumber = $phonenumber;
            $customer->service_type = $serviceType;
            $customer->coordinates = $coordinates;
            $customer->city = $city;
            $customer->district = $district;
            $customer->state = $state;
            $customer->zip = $zip;
            $customer->balance = $balance;
            $customer->auto_renewal = rand(0, 1);
            $customer->status = $status;
            
            if ($customer->save()) {
                $successCount++;
                echo "Created client #$i: $fullname ($email) - $serviceType - $accountType - $status\n";
                
                // Add some custom fields for variety
                if (rand(0, 1)) { // 50% chance of having custom fields
                    $customFields = [
                        'Company' => 'Company ' . $i,
                        'Department' => ['IT', 'Sales', 'Marketing', 'Finance', 'HR'][array_rand(['IT', 'Sales', 'Marketing', 'Finance', 'HR'])],
                        'Referral' => ['Website', 'Friend', 'Advertisement', 'Walk-in', 'Social Media'][array_rand(['Website', 'Friend', 'Advertisement', 'Walk-in', 'Social Media'])],
                        'Notes' => 'Customer notes for ' . $fullname
                    ];
                    
                    foreach ($customFields as $fieldName => $fieldValue) {
                        $customField = ORM::for_table('tbl_customers_fields')->create();
                        $customField->customer_id = $customer->id();
                        $customField->field_name = $fieldName;
                        $customField->field_value = $fieldValue;
                        $customField->save();
                    }
                }
            } else {
                $errorCount++;
                echo "Failed to create client #$i\n";
            }
            
        } catch (Exception $e) {
            $errorCount++;
            echo "Error creating client #$i: " . $e->getMessage() . "\n";
        }
    }

    echo "\nSeeding completed!\n";
    echo "Successfully created: $successCount clients\n";
    echo "Errors: $errorCount\n";
    echo "Total clients in database: " . ORM::for_table('tbl_customers')->count() . "\n";

} catch (Exception $e) {
    echo "Fatal error: " . $e->getMessage() . "\n";
}
?>
