<?php
/**
 * PHPUnit Bootstrap File
 * Sets up testing environment
 */

// Start session for testing
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Load Composer autoloader
require_once __DIR__ . '/../vendor/autoload.php';

// Load configuration
require_once __DIR__ . '/../config/config.php';

// Override database name for testing
if (!defined('DB_NAME_TEST')) {
    define('DB_NAME_TEST', 'birthday_reminder_test');
}

/**
 * Helper function to reset database for testing
 */
function resetTestDatabase() {
    $db = Database::getInstance();
    
    // Truncate all tables
    $tables = ['notification_subscriptions', 'sessions', 'user_templates', 'notes', 'contacts', 'templates', 'users'];
    
    $db->execute('SET FOREIGN_KEY_CHECKS = 0');
    foreach ($tables as $table) {
        $db->execute("TRUNCATE TABLE $table");
    }
    $db->execute('SET FOREIGN_KEY_CHECKS = 1');
    
    // Insert test admin user
    $db->execute(
        "INSERT INTO users (username, password_hash, email, is_active) VALUES (?, ?, ?, ?)",
        ['testadmin', password_hash('test123', PASSWORD_DEFAULT), 'test@example.com', 1]
    );
}

/**
 * Helper function to create test user
 */
function createTestUser($username = 'testuser', $email = 'testuser@example.com', $password = 'test123') {
    $db = Database::getInstance();
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    
    $db->execute(
        "INSERT INTO users (username, password_hash, email, is_active) VALUES (?, ?, ?, ?)",
        [$username, $passwordHash, $email, 1]
    );
    
    return $db->lastInsertId();
}

/**
 * Helper function to generate random string
 */
function randomString($length = 10) {
    return substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', $length)), 0, $length);
}

/**
 * Helper function to generate random phone number
 */
function randomPhoneNumber($length = 10) {
    $phone = '';
    for ($i = 0; $i < $length; $i++) {
        $phone .= rand(0, 9);
    }
    return $phone;
}

/**
 * Helper function to generate random date
 */
function randomDate($startDate = '1950-01-01', $endDate = '2010-12-31') {
    $start = strtotime($startDate);
    $end = strtotime($endDate);
    $timestamp = rand($start, $end);
    return date('Y-m-d', $timestamp);
}

/**
 * Helper function to generate random email
 */
function randomEmail() {
    return randomString(8) . '@example.com';
}
