<?php

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

class Export_SelectedPermitsBySubdivision_CSV extends Base {

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

    public function __construct() {

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

        date_default_timezone_set(self::TIMEZONE);
    }

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

    public function export() {

        set_time_limit(0);

        $selected_permits = filter_input(INPUT_POST, "selected_permits") ?: "";
        $subscription_serial = filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;

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

        $permits = (new PermitsBySubdivision())->getSelectedPermits($selected_permits);
        foreach ($permits as $permit) {

            $county_serial = $permit->rdi_county;

            $county_name = (new Counties())->getCounty($county_serial);
            $permit->county_name_verbose = $county_name->record->county_name;
        }

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="Selected_PermitsBySubdivision.csv"');

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

        // Add CSV headers
        fputcsv($output, ['County', 'Subdivision', 'Address', 'City', 'Builder', 'Permit Date', 'Square Footage', 'Value'], ',', '"', '\\');

        $permit_ytd_value = 0.00;
        $permit_value = 0.00;

        foreach ($permits as $permit) {

            $county_name = $permit->county_name_verbose;
            $subdivision = $permit->rdi_sub_div_name;
            $address = "{$permit->rdi_address} {$permit->rdi_city} {$permit->rdi_state} {$permit->rdi_zip}";
            $city = $permit->rdi_city;
            $builder = $permit->rdi_company;
            $permit_date = $permit->rdi_permit_date_verbose;
            $square_footage = $permit->rdi_size_verbose;
            $value = $permit->rdi_value_verbose;

            $permit_ytd_value = "$" . number_format((int) $permit->rdi_ytd_value, 2);
            $permit_value = "$" . number_format((int) $permit->rdi_value, 2);

            $permit_data = array($county_name, $subdivision, $address, $city, $builder, $permit_date, $square_footage, $value);

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

        fclose($output);

        exit();
    }

    // ===============
    // Debug an Object
    // ===============

    public function debug($object = "") {

        echo "<pre>";
        print_r($object);
        exit();
    }
}

?>
