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

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

function printRow($columns, $widths) {
    $line = "";
    foreach ($columns as $i => $col) {
        $w = $widths[$i];
        $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";
}

$stmt = $pdo->query("SELECT service_provider, MIN(id) as first_seen_id FROM raw_reports WHERE service_provider != '' GROUP BY service_provider ORDER BY first_seen_id ASC");
$providers = $stmt->fetchAll(PDO::FETCH_COLUMN);

foreach ($providers as $prov) {
    $sql = "SELECT t.*, r.uploaded_at FROM offline_rt1000 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("=", 100) . "\n\n";
        echo "--- OFFLINE RT1000 PROPERTIES ---\n";
        
        // All Headers available for Offline RT
        $headers = ["Uploaded", "Prop ID", "Property Name", "RT Name"];
        $widths  = [18, 10, 50, 30];

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

        foreach ($data as $row) {
            printRow([
                $row['uploaded_at'],
                $row['property_id'], 
                $row['prop_name'], 
                $row['rt_name']
            ], $widths);
        }
        echo "\n\n\n";
    }
}
exit;
?>