<?php

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

class Export_AllPermitsBySubdivision_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);

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

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

        $permit_area = $subscription->record->subscription_area;
        $projecttype = $subscription->record->subscription_projecttype;

        $permits = (new PermitsBySubdivision())->getAllPermitsBySubdivision($permit_area, $projecttype, $_POST);

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="All_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->permit_sub_div_name;
            $address          = "{$permit->permit_address} {$permit->permit_city} {$permit->permit_state} {$permit->permit_zip}";
            $city             = $permit->permit_city;
            $builder          = $permit->permit_company;
            $permit_date      = $permit->permit_permit_date_verbose;
            $square_footage   = $permit->permit_size_verbose;
            $value            = $permit->permit_value_verbose;

            $permit_ytd_value = "$" . number_format((int) $permit->permit_ytd_value, 2);
            $permit_value     = "$" . number_format((int) $permit->permit_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();
    }
}

?>
