<?php

// ========================================
// Export Selected Permits By Builder - CSV
// ========================================

class Export_SelectedPermitsByBuilderCSV 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_reference", FILTER_SANITIZE_NUMBER_INT) ?: 0;

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

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

        $permits = (new PermitsByBuilder())->getSelectedPermits($permit_area, $projecttype, $selected_permits);

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

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

        $header = array('Builder/Company', 'Permits', 'Value', 'Current Year YTD', 'Current YTD Value', 'Last 12 Months', 'Address', 'Phone');

        // Add CSV headers
        fputcsv($output, $header, ',', '"', '\\');

        $permit_ytd_value = 0.00;
        $permit_value = 0.00;

        foreach ($permits as $permit) {

            $builder                  = $permit->permit_company;
            $permitcount              = $permit->permit_permit_count;
            $permit_value             = $permit->permit_value_verbose;
            $currentyearytd           = $permit->ytd_permits;
            $permit_ytd_value         = $permit->ytd_value;
            $permit12monthprevpermits = $permit->previous_ytd_permits;
            $address                  = "{$permit->permit_address} {$permit->permit_city} {$permit->permit_state} {$permit->permit_zip}";
            $phone                    = $permit->permit_phone_verbose;

            $permit_ytd_value = "$" . number_format((int) $permit_ytd_value, 2);
            $permit_value = "$" . number_format((int) $permit_value, 2);

            $permit_data = array($builder, $permitcount, $permit_value, $currentyearytd, $permit_ytd_value, $permit12monthprevpermits, $address, $phone);

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

        fclose($output);

        exit();
    }

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

    public function debug($object = "") {

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

?>
