output_type = $output_type; } // ================ // Print the Report // ================ public function print() { $report = new BusinessFacts_Print(); $report->subscription_serial = $_SESSION['subscription_serial']; $report->usersubscription_serial = $_SESSION['usersubscription_serial']; $report->output_type = $this->output_type; ob_clean(); if ($this->output_type == "string") { return $report->render(); } else { $report->render(); } } } // ========================== // Class to Generate the .pdf // ========================== class BusinessFacts_Print extends TCPDF { // Variables public $subscription_serial = 0; public $usersubscription_serial = 0; public $report_header_title = ""; public $first_page = true; public $output_type = "normal"; // ================ // Debug an Object. // ================ public function debug($object = "") { echo "
";
        print_r($object);
        exit();
    }

    // =================
    // Render the Report
    // =================

    public function render() {

        set_time_limit(0);

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

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

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

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

        // Set report defaults
        $this->report_header_title = $subscription->record->subscription_full_title;
        $this->title = $subscription->record->subscription_full_title;

        $this->SetFont("Calibri");
        $this->SetMargins(2, 26, 10);
        $this->SetHeaderMargin(10);
        $this->SetFooterMargin(10);
        $this->setCellPaddings(0, 0, 0, 0);
        $this->setCellMargins(2, 0, 0, 0);

//        $this->addPage("L", "LETTER");

        $card = function (float $x, float $y, float $w, float $h, array $d) {

            // Card background + border
            $this->SetDrawColor(210, 210, 210);
            $this->SetFillColor(250, 250, 250);
            $this->Rect($x, $y, $w, $h, 'DF');

            // Header bar
            $headerH = 10;
            $this->SetFillColor(30, 93, 168); // Bootstrap-ish primary
            $this->Rect($x, $y, $w, $headerH, 'F');

            // Header text
            $this->SetTextColor(255, 255, 255);
            $this->SetFont('helvetica', 'B', 11);
            $this->SetXY($x + 3, $y + 2.5);
            $this->Cell($w - 6, 0, "Company Name: {$d['businessfact_company']}", 0, 0, 'L', false);

            // Body
            $this->SetTextColor(20, 20, 20);
            $this->SetFont('helvetica', '', 9);

            $padX = 3;
            $padY = 3;

            $curY = $y + $headerH + $padY;

            $bodyX = $x + $padX;
            $bodyW = $w - ($padX * 2);

            $colGap = 6;
            $colW = ($bodyW - $colGap) / 2;

            $leftX = $bodyX;
            $rightX = $bodyX + $colW + $colGap;

            $labelW = 37; // tweak to taste

            $row2 = function (string $l1, string $v1, string $l2, string $v2) use (&$curY, $leftX, $rightX, $colW, $labelW) {
                $yStart = $curY;

                // LEFT cell
                $this->SetXY($leftX, $yStart);
                $this->SetFont('helvetica', 'B', 9);
                $this->Cell($labelW, 0, $l1, 0, 0, 'L');
                $this->Cell(2, 0, '', 0, 0); // spacer
                $this->SetFont('helvetica', '', 9);
                $this->MultiCell($colW - $labelW, 0, $v1, 0, 'L', false, 1);
                $yAfterLeft = $this->GetY();

                // RIGHT cell (reset to same starting Y)
                $this->SetXY($rightX, $yStart);
                $this->SetFont('helvetica', 'B', 9);
                $this->Cell($labelW, 0, $l2, 0, 0, 'L');
                $this->SetFont('helvetica', '', 9);
                $this->MultiCell($colW - $labelW, 0, $v2, 0, 'L', false, 1);
                $yAfterRight = $this->GetY();

                // Advance cursor to max height used
                $curY = max($yAfterLeft, $yAfterRight) + 1;
            };

            // Two-column rows (swap these however you like)
            $row2('Contact Name: ',    $d['businessfact_contact_name'],     'Business Classification:', $d['businessfact_business_class']);
            $row2('Title: ',           $d['businessfact_contact_title'],    'Action:',                  $d['businessfact_action']);
            $row2('Phone:',            $d['businessfact_company_phone'],    'Employee Count:',           $d['businessfact_employee_count']);
            $row2('Fax:',              $d['businessfact_company_fax'],      'Inception:',                $d['businessfact_inception']);
            $row2('Email Address:',    $d['businessfact_email_address'],    'SIC Code:',                 $d['businessfact_sic_code']);
            $row2('Address:',          $d['businessfact_address_one'],      'License Date:',            $d['businessfact_license_date']);
            $row2('City/State/Zip:',   $d['businessfact_city_state_zip'],   'Home Based Business:',     $d['businessfact_home_based_business']);
            $row2('County:',           $d['businessfact_county_name'],      'Year Established:',        $d['businessfact_year_established']);
            $row2('','',                                                    '',''  );
            $row2('','',                                                    'Business Fact ID:',        $d['businessfact_legacy_id']);
            $row2('','',                                                    'Entry Date:',              $d['businessfact_entry_date']);

        };

        // Get the data for the report

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

        $this->AddPage('L', 'LETTER');

        $marginL = 10;
        $marginT = 20; // below header area
        $pageW = $this->getPageWidth();
        $pageH = $this->getPageHeight();

        $usableW = $pageW - ($marginL * 2);
        $usableH = $pageH - $marginT - 12;

        $gapY = 6;

        // Two rows per page
        $cardW = $usableW;
        $cardH = ($usableH - $gapY) / 2;

        $index = 0;

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

            // Add a new page every 2 cards
            if ($index > 0 && $index % 2 === 0) {
                $this->AddPage('L', 'LETTER');
            }

            $slot = $index % 2;

            $x = $marginL;
            $y = $marginT + ($slot * ($cardH + $gapY));

            // Map your XML fields to the card placeholders (use verbose)

            $d = [ 
                // Card Header
                'businessfact_company'             => trim((string) $businessfact->businessfact_company),
                
                // Left Side of Card
                
                'businessfact_contact_name'        => trim((string) $businessfact->businessfact_contact_name),
                'businessfact_contact_title'       => trim((string) $businessfact->businessfact_contact_title),
                'businessfact_company_phone'       => $this->formatPhoneNumber(trim((string) $businessfact->businessfact_phone)),
                'businessfact_company_fax'         => $this->formatPhoneNumber(trim((string) $businessfact->businessfact_fax)),
                'businessfact_email_address'       => trim((string) $businessfact->businessfact_email_address),
                'businessfact_address_one'         => trim((string) $businessfact->businessfact_address_one),
                'businessfact_city_state_zip'      => trim((string) $businessfact->businessfact_city_verbose) . ', ' . trim((string) $businessfact->businessfact_state) . ' ' . trim((string) $businessfact->businessfact_zip),
                'businessfact_county_name'         => trim((string) $businessfact->businessfact_county_name_verbose),
                
                
                // Right Side of Card
                'businessfact_business_class'      => trim((string) $businessfact->businessfact_business_class_verbose),
                'businessfact_action'              => trim((string) $businessfact->businessfact_action_verbose),
                'businessfact_employee_count'      => trim((string) $businessfact->businessfact_employee_count),
                'businessfact_inception'           => trim((string) $businessfact->businessfact_inception),
                'businessfact_sic_code'            => trim((string) $businessfact->businessfact_sic_code). ' - ' .trim((string) $businessfact->businessfact_siccode_description_verbose),
                'businessfact_license_date'        => trim((string) $businessfact->businessfact_license_date_verbose),
                'businessfact_home_based_business' => trim((string) $businessfact->businessfact_home_based_business),
                'businessfact_year_established'    => trim((string) $businessfact->businessfact_year_established),
                'businessfact_legacy_id'           => trim((string) $businessfact->businessfact_legacy_id),
                'businessfact_entry_date'          => trim((string) $businessfact->businessfact_entry_date_verbose)
            ];

            $card($x, $y, $cardW, $cardH, $d);

            $index++;
        }


        // -----------------
        // Render the Report
        // -----------------

        $this->SetFont('helvetica', '', 9);

        // --------------
        // Return the pdf
        // --------------

        if ($this->output_type == "string") {
            return $this->Output("{$subscription->record->subscription_full_title}.pdf", "S");
        } else {
            $this->Output("{$subscription->record->subscription_full_title}.pdf");
        }
    }

    // ======
    // Header
    // ======

    public function Header() {

        $this->setCellPaddings(0, 0, 0, 0);
        $this->setCellMargins(2, 0, 0, 0);

        $this->Image("images/dec-international-logo.png", 250, 8, 20, 8);

        $this->SetFont("Calibri", "B", 16);

        $this->Cell(4, 0, "", 0, 0, "L");
        $this->Cell(0, 0, $this->report_header_title . " Report", 0, 0, "L");

        $this->Ln(10);
    }

    // ======
    // Footer
    // ======

    public function Footer() {

        $this->SetFont("Calibri ", "I", 8);

        $X = $this->GetX();

        $this->Cell(0, 10, "https://dec-international.com", 0, false, "C");

        $this->SetX($X);

        $this->Cell(40, 10, "Page " . $this->getAliasNumPage() . "/" . $this->getAliasNbPages(), 0, false, "L");
        $this->Cell(0, 10, "Generated: " . date("n/j/Y g:i A   "), 0, false, "R"
        );
    }

    // =======================
    // Stripe the printed line
    // =======================

    private function stripeLine($pRowCount = 0, $pRowWidth = 0) {

        $this->SetFillColor(($pRowCount % 2) ? 220 : 255);
        $X = $this->GetX();
        $this->Cell($pRowWidth, 0, "", 0, 0, "L", true);
        $this->SetX($X);
    }

    // =======================
    // Format Raw Phone Number
    // =======================

    public function formatPhoneNumber(string $phonenumber): string {

        // Remove everything except digits
        $digits = preg_replace('/\D+/', '', $phonenumber);

        // Handle leading country code (US)
        if (strlen($digits) === 11 && str_starts_with($digits, '1')) {
            $digits = substr($digits, 1);
        }

        return substr($digits, 0, 3) . '-' .
                substr($digits, 3, 3) . '-' .
                substr($digits, 6, 4);
    }
}

?>