<?php

// ====================
// Export Permits - CSV
// ====================

class Export_PermitFactsToCSV 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;

        $permits = (new PermitFacts())->getPermitFactsPage($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_legacy = [
            'PermitFactsID', 'EntryDate', 'PermitNum', 'PermitDate', 'ProjectAddr', 'ProjectName',
            'ProjectType', 'ProjectCity', 'ProjectState', 'ProjectZip', 'Company', 'Address',
            'City', 'State', 'Zip', 'Phone', 'Size', 'Value', 'WorkType',
            'BldgType', 'County', 'Lot_BLK', 'Dist_LL', 'OwnerName', 'OwnerAddress',
            'OwnerCity', 'OwnerState', 'OwnerZip', 'OwnerPhone'
        ];

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

        $header_array = [
            'permitfact_legacy_id', 'permitfact_entry_date_verbose', 'permitfact_permit_number', 'permitfact_permit_date_verbose', 'permitfact_project_address', 'permitfact_project_name',
            'permitfact_project_type_verbose', 'project_city_verbose', 'permitfact_project_state', 'permitfact_project_zip', 'permitfact_company', 'permitfact_address',
            'permitfact_city_verbose', 'permitfact_state', 'permitfact_zip', 'permitfact_phone', 'permitfact_size', 'permitfact_value', 'permitfact_work_type_verbose',
            'permitfact_building_type_verbose', 'permitfact_county_name_verbose', 'permitfact_lot_block', 'permitfact_dist_ll', 'permitfact_owner_name', 'permitfact_owner_address',
            'owner_city_verbose', 'permitfact_owner_state', 'permitfact_owner_zip', 'permitfact_owner_phone'
        ];

        foreach ($permits->record as $permit) {

            $row = [];

            foreach ($header_array as $field) {

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

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

        fclose($output);

        exit();
    }
}

?>
