<?php
/**
 * Test upload script - simulates file upload to whitelist
 */
require_once 'src/Database.php';

$db = new Database();
$conn = $db->getConnection();

// Sanitize phone number
function sanitizePhone($phone) {
    $phone = preg_replace('/[^0-9]/', '', $phone);
    
    if (strlen($phone) == 10 && substr($phone, 0, 1) == "0") {
        return "254" . substr($phone, 1);
    }
    if (strlen($phone) == 9) {
        return "254" . $phone;
    }
    if (strlen($phone) == 12 && substr($phone, 0, 3) == "254") {
        return $phone;
    }
    if (strlen($phone) == 13 && substr($phone, 0, 1) == "+") {
        return substr($phone, 1);
    }
    
    return null;
}

// Process CSV file
function processCSV($conn, $file_path) {
    $count = 0;
    $handle = fopen($file_path, 'r');
    if (!$handle) {
        throw new Exception("Cannot open file: $file_path");
    }
    
    $header = fgetcsv($handle);

    $batch = [];
    while (($row = fgetcsv($handle)) !== false) {
        $phone = sanitizePhone(trim($row[0] ?? ''));
        $name = trim($row[1] ?? 'Unknown');

        if ($phone) {
            $batch[] = ['phone' => $phone, 'name' => $name];
            if (count($batch) >= 100) {
                $count += insertBatch($conn, $batch);
                $batch = [];
            }
        }
    }
    if (!empty($batch)) {
        $count += insertBatch($conn, $batch);
    }
    fclose($handle);
    return $count;
}

// Insert batch of contacts
function insertBatch($conn, $batch) {
    $count = 0;
    try {
        $stmt = $conn->prepare('INSERT IGNORE INTO contacts (phone_number, name, created_at) VALUES (?, ?, NOW())');
        if (!$stmt) {
            throw new Exception('Failed to prepare statement: ' . $conn->errorInfo()[2]);
        }
        
        foreach ($batch as $contact) {
            try {
                if ($stmt->execute([$contact['phone'], $contact['name']])) {
                    $count++;
                }
            } catch (Exception $e) {
                echo "Error inserting contact: " . $e->getMessage() . "\n";
            }
        }
    } catch (Exception $e) {
        echo "Batch insert error: " . $e->getMessage() . "\n";
    }
    return $count;
}

// Test the upload
try {
    $test_file = '/tmp/test_contacts.csv';
    
    if (!file_exists($test_file)) {
        die("Test file not found: $test_file\n");
    }
    
    echo "Testing CSV upload...\n";
    echo "File: $test_file\n";
    
    $count = processCSV($conn, $test_file);
    
    echo "Imported: $count contacts\n";
    
    // Verify by counting contacts
    $stmt = $conn->query('SELECT COUNT(*) as count FROM contacts');
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "Total contacts in database: " . $result['count'] . "\n";
    
    // Show the uploaded contacts
    $stmt = $conn->query('SELECT * FROM contacts ORDER BY created_at DESC LIMIT 5');
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "\nRecent contacts:\n";
    foreach ($results as $contact) {
        echo "  - {$contact['phone_number']}: {$contact['name']}\n";
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>
