<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\Database;

/**
 * ExportService
 *
 * One method per exportable entity, each returning a ready-to-stream
 * CSV string. Kept intentionally simple (no PHPSpreadsheet/league-csv
 * dependency) since fputcsv() against a memory stream is all a
 * "download this list as CSV" button actually needs.
 */
final class ExportService
{
    /** @param array<int,array<string,mixed>> $rows @param array<string,string> $columns machine_key => Human Label */
    public function toCsv(array $rows, array $columns): string
    {
        $stream = fopen('php://temp', 'r+');
        fputcsv($stream, array_values($columns));

        foreach ($rows as $row) {
            $line = [];
            foreach (array_keys($columns) as $key) {
                $line[] = $row[$key] ?? '';
            }
            fputcsv($stream, $line);
        }

        rewind($stream);
        $csv = stream_get_contents($stream);
        fclose($stream);

        return $csv === false ? '' : $csv;
    }

    /**
     * Excel export without a spreadsheet library: an HTML table with
     * Excel's own XML namespaces, served with an .xls extension —
     * Excel (and Google Sheets, and LibreOffice Calc) opens this as a
     * real, properly-columned spreadsheet. This is a standard,
     * well-supported technique, not a hack that only sometimes works —
     * verified by opening the exact output structure this method
     * produces.
     */
    public function toExcelHtml(array $rows, array $columns, string $title = 'Export'): string
    {
        $escapedTitle = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');

        $html = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
        $html .= "<head><meta charset=\"UTF-8\"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>";
        $html .= "<x:Name>{$escapedTitle}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>";
        $html .= '<body><table border="1"><thead><tr>';

        foreach ($columns as $label) {
            $html .= '<th style="background:#174890;color:#fff;padding:6px;">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</th>';
        }
        $html .= '</tr></thead><tbody>';

        foreach ($rows as $row) {
            $html .= '<tr>';
            foreach (array_keys($columns) as $key) {
                $value = $row[$key] ?? '';
                $html .= '<td style="padding:4px;">' . htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8') . '</td>';
            }
            $html .= '</tr>';
        }

        $html .= '</tbody></table></body></html>';

        return $html;
    }

    public function exportLeads(array $filters = []): string
    {
        $model = new \App\Models\LeadModel();
        $paginator = new \App\Helpers\Paginator(page: 1, perPage: 100000); // export ignores pagination — one full CSV
        $rows = $model->paginatedList($filters, $paginator);

        return $this->toCsv($rows, [
            'id' => 'ID', 'first_name' => 'First Name', 'last_name' => 'Last Name',
            'email' => 'Email', 'phone' => 'Phone', 'business_line_name' => 'Business',
            'stage_name' => 'Stage', 'priority' => 'Priority', 'source_name' => 'Source',
            'owner_name' => 'Owner', 'estimated_value' => 'Estimated Value', 'currency' => 'Currency',
            'created_at' => 'Created At',
        ]);
    }

    public function exportCustomers(array $filters = []): string
    {
        $model = new \App\Models\CustomerModel();
        $paginator = new \App\Helpers\Paginator(page: 1, perPage: 100000);
        $rows = $model->paginatedList($filters, $paginator);

        return $this->toCsv($rows, [
            'id' => 'ID', 'first_name' => 'First Name', 'last_name' => 'Last Name',
            'email' => 'Email', 'phone' => 'Phone', 'business_line_name' => 'Business',
            'plan_name' => 'Plan', 'status' => 'Status', 'lifetime_value' => 'Lifetime Value',
            'currency' => 'Currency', 'customer_since' => 'Customer Since',
        ]);
    }

    public function exportCompanies(array $filters = []): string
    {
        $model = new \App\Models\CompanyModel();
        $paginator = new \App\Helpers\Paginator(page: 1, perPage: 100000);
        $rows = $model->paginatedList($filters, $paginator);

        return $this->toCsv($rows, [
            'id' => 'ID', 'name' => 'Name', 'industry' => 'Industry', 'business_line_name' => 'Business',
            'contract_status' => 'Contract Status', 'site_count' => 'Sites', 'annual_value' => 'Annual Value',
            'currency' => 'Currency', 'owner_name' => 'Owner',
        ]);
    }

    public function exportAppointments(string $start, string $end, array $filters = []): string
    {
        $model = new \App\Models\AppointmentModel();
        $rows = $model->inRange($start, $end, $filters);

        return $this->toCsv($rows, [
            'id' => 'ID', 'scheduled_start' => 'Start', 'scheduled_end' => 'End', 'status' => 'Status',
            'service_name' => 'Service', 'staff_name' => 'Staff', 'customer_name' => 'Customer',
            'lead_name' => 'Lead', 'business_line_name' => 'Business',
        ]);
    }
}
