<?php

// ===========================
// Export Business Facts - CSV
// ===========================

class Export_BusinessFactsToCSV extends Base {

    // Variables

    private $current_user_serial = 0;
    private $current_user_id = "";
    private $current_user_name = "";
    private $current_user_email = "";

    // ==================
    // Class Constructor.
    // ==================

    public function __construct() {

        set_error_handler(array($this, "displayError"));

        date_default_timezone_set(self::TIMEZONE);

        $this->current_user_serial = $_SESSION[self::USER_SERIAL] ?? 0;
        $this->current_user_id = $_SESSION[self::USER_ID] ?? "";
        $this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
        $this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
    }

    // ===============
    // Export the Data
    // ===============

    public function export() {

        $subscription_serial = $_SESSION['subscription_serial'];
        $usersubscription_serial = $_SESSION['usersubscription_serial'];

        $subscription = (new Subscriptions())->getSubscription($subscription_serial);

        if ($subscription->count() === 0) {
            $this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
        }

        $userssubscription = (new Users())->getUserSubscription($usersubscription_serial);

        $user_subscription_start_date = $userssubscription->record->usersubscription_start_date;
        $user_subscription_end_date = $userssubscription->record->usersubscription_end_date;

        $businessfacts = (new BusinessFacts())->getBusinessFactsPage($user_subscription_start_date, $user_subscription_end_date);

        $filename = "{$subscription->record->subscription_full_title}.csv";

        header('Content-Type: text/csv');
        header("Content-Disposition: attachment; filename=\"{$filename}\"");

        $output = fopen('php://output', 'w');

        // Add CSV headers

        $header_array = [
            'BusinessFactID', 'Company', 'Address1', 'Address2', 'City', 'State',
            'Zip', 'County', 'Phone', 'Fax', 'EmailAddress', 'BusinessClass',
            'Action', 'ES', 'Inception', 'SIC', 'SIC_Description', 'ContactName',
            'ContactTitle', 'LicenseDate', 'HomeBasedBusiness', 'YearEstablished', 'EntryDate'
        ];

        fputcsv($output, $header_array, ',', '"', '\\');

        $header_array = [
            'businessfact_legacy_id', 'businessfact_company', 'businessfact_address_one', 'businessfact_address_two', 'businessfact_city_verbose', 'businessfact_state',
            'businessfact_zip', 'businessfact_county_name_verbose', 'businessfact_phone', 'businessfact_fax', 'businessfact_email_address', 'businessfact_business_class_verbose',
            'businessfact_action_verbose', 'businessfact_employee_count', 'businessfact_inception', 'businessfact_sic_code', 'businessfact_siccode_description_verbose', 'businessfact_contact_name',
            'businessfact_contact_title', 'businessfact_license_date_verbose', 'businessfact_home_based_business', 'businessfact_year_established', 'businessfact_entry_date_verbose'
        ];

        foreach ($businessfacts->record as $businessfact) {

            $row = [];

            foreach ($header_array as $field) {

                // Cast SimpleXML nodes safely; empty nodes become ""
                $row[] = isset($businessfact->$field) ? trim((string) $businessfact->$field) : '';
            }

            fputcsv($output, $row, ',', '"', '\\');
        }

        fclose($output);

        exit();
    }
}

?>
