<?php
// public/export_wakeup_txt.php
require __DIR__ . '/../src/auth.php';
require_login();
require __DIR__ . '/../src/db.php';

// 1. Force Download
header('Content-Type: text/plain; charset=utf-8');
header('Content-Disposition: attachment; filename="all_wakeup_errors_full_' . date('Y-m-d_Hi') . '.txt"');

// 2. Formatting Helpers
function printRow($columns, $widths) {
    $line = "";
    foreach ($columns as $i => $col) {
        $w = $widths[$i];
        // Truncate if too long to maintain alignment
        $val = substr((string)$col, 0, $w - 2); 
        $line .= str_pad($val, $w);
    }
    echo trim($line) . "\n"; 
}

function printDivider($widths) {
    echo str_repeat("-", array_sum($widths)) . "\n";
}

// 3. GET PROVIDERS
$stmt = $pdo->query("
    SELECT service_provider, MIN(id) as first_seen_id
    FROM raw_reports 
    WHERE service_provider IS NOT NULL AND service_provider != '' 
    GROUP BY service_provider
    ORDER BY first_seen_id ASC
");
$providers = $stmt->fetchAll(PDO::FETCH_COLUMN);

// 4. GENERATE CONTENT
foreach ($providers as $prov) {
    
    // Fetch ALL columns for Wakeup Errors
    $sql = "SELECT t.*, r.uploaded_at 
            FROM wakeup_errors t 
            JOIN raw_reports r ON t.report_id = r.id 
            WHERE r.service_provider = ? 
            ORDER BY t.id ASC";
    $rows = $pdo->prepare($sql);
    $rows->execute([$prov]);
    $data = $rows->fetchAll();

    if ($data) {
        echo "PROVIDER:       " . $prov . "\n";
        echo str_repeat("=", 150) . "\n\n"; // Wider separator

        echo "--- WAKEUP ERRORS (ALL COLUMNS) ---\n";
        
        // Define All Headers
        $headers = [
            "Uploaded", 
            "Prop ID", 
            "Property Name", 
            "Room", 
            "Att", 
            "Schedule Time", 
            "Wakeup Time", 
            "Status", 
            "Rm Stat", 
            "PBX Type"
        ];
        
        // Define Widths (Total ~150 chars)
        $widths  = [
            18, // Uploaded
            10, // Prop ID
            35, // Name (Reduced slightly to fit others)
            8,  // Room
            5,  // Att
            22, // Schedule
            22, // Wakeup
            25, // Status
            10, // Room Status (Valid/Invalid)
            15  // PBX Type
        ];

        printRow($headers, $widths);
        printDivider($widths);

        foreach ($data as $row) {
            printRow([
                $row['uploaded_at'],
                $row['property_id'], 
                $row['prop_name'], 
                $row['room_number'],
                $row['attempts'],
                $row['schedule_time'],
                $row['wakeup_time'],
                $row['status_text'],
                $row['room_status'], // Added
                $row['pbx_type']     // Added
            ], $widths);
        }
        echo "\n\n\n";
    }
}
exit;
?>