<?php

namespace App\Utils;

require_once __DIR__ . '/fpdf.php';

class ExpiryPDFGenerator extends \FPDF {
    private $tenantName;
    
    public function __construct(string $tenantName) {
        // Initialize FPDF: Portrait, millimeters, A4
        parent::__construct('P', 'mm', 'A4');
        $this->tenantName = $tenantName;
        $this->SetMargins(15, 15, 15);
        $this->SetAutoPageBreak(true, 15);
    }
    
    // Page header override
    public function Header() {
        // Bleed banner at the very top of the page (vibrant accent)
        $this->SetFillColor(79, 70, 229); // Brand Indigo
        $this->Rect(0, 0, 210, 6, 'F');
        
        // Left accent block in the header
        $this->SetFillColor(79, 70, 229);
        $this->Rect(15, 15, 3, 12, 'F');
        
        // Title
        $this->SetXY(21, 14);
        $this->SetFont('Helvetica', 'B', 14);
        $this->SetTextColor(15, 23, 42); // Dark slate
        $this->Cell(0, 7, $this->tenantName, 0, 1, 'L');
        
        $this->SetXY(21, 20);
        $this->SetFont('Helvetica', 'B', 8);
        $this->SetTextColor(79, 70, 229); // Brand Indigo
        $this->Cell(0, 5, 'EXPIRY ALERT REPORT', 0, 1, 'L');
        
        // Right side info
        $this->SetXY(140, 14);
        $this->SetFont('Helvetica', '', 8);
        $this->SetTextColor(100, 116, 139); // Slate muted grey
        $localTime = new \DateTime('now', new \DateTimeZone('Asia/Colombo'));
        $this->Cell(55, 5, 'Generated: ' . $localTime->format('Y-m-d h:i A'), 0, 1, 'R');
        
        $this->SetXY(140, 19);
        $this->Cell(55, 5, 'Status: Active Batches Only', 0, 1, 'R');
        
        // Divider line
        $this->SetDrawColor(226, 232, 240);
        $this->SetLineWidth(0.3);
        $this->Line(15, 28, 195, 28);
        
        // Body starts below header
        $this->SetY(32);
    }
    
    // Page footer override
    public function Footer() {
        $this->SetY(-15);
        $this->SetFont('Helvetica', '', 8);
        $this->SetTextColor(148, 163, 184);
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . ' of {nb}', 0, 0, 'C');
    }
    
    /**
     * Generate the PDF binary string for the given expiring items.
     *
     * @param array $items
     * @return string PDF content string
     */
    public function generate(array $items): string {
        $this->AliasNbPages();
        $this->AddPage();
        
        // Table Columns width configuration (Total width = 180mm)
        $w = [10, 45, 28, 28, 16, 28, 25];
        $headers = ['#', 'Medicine Details', 'Batch No.', 'Branch', 'Qty', 'Expiry Date', 'Status'];
        
        // Print Table Header
        $this->SetFont('Helvetica', 'B', 9);
        $this->SetFillColor(30, 41, 59); // Premium Dark Slate
        $this->SetTextColor(255, 255, 255); // White
        
        for ($i = 0; $i < count($headers); $i++) {
            $align = ($i >= 4 || $i === 0) ? 'C' : 'L';
            $this->Cell($w[$i], 9, $headers[$i], 0, 0, $align, true);
        }
        $this->Ln();
        
        // Print Table Body
        $fill = false;
        $this->SetFont('Helvetica', '', 8.5);
        
        $index = 1;
        foreach ($items as $item) {
            $details = $item['medicine_name'];
            if (!empty($item['generic_name'])) {
                $details .= "\n(" . $item['generic_name'] . ")";
            }
            
            // Calculate line count for wrapping details
            $lines = 1;
            $rawLines = explode("\n", $details);
            foreach ($rawLines as $rl) {
                // ~30 chars fit in 55mm with Helvetica 8.5
                $lines += floor(strlen($rl) / 30);
            }
            $lines = max(count($rawLines), $lines);
            
            // Give row some comfortable vertical padding (breathing room)
            $rowHeight = max(11, $lines * 5);
            
            // Check page break trigger
            if ($this->GetY() + $rowHeight > $this->PageBreakTrigger) {
                $this->AddPage();
                
                // Re-print headers on new page
                $this->SetFont('Helvetica', 'B', 9);
                $this->SetFillColor(30, 41, 59);
                $this->SetTextColor(255, 255, 255);
                for ($i = 0; $i < count($headers); $i++) {
                    $align = ($i >= 4 || $i === 0) ? 'C' : 'L';
                    $this->Cell($w[$i], 9, $headers[$i], 0, 0, $align, true);
                }
                $this->Ln();
                $this->SetFont('Helvetica', '', 8.5);
            }
            
            $startY = $this->GetY();
            
            // Fill background row if alternate row
            if ($fill) {
                $this->SetFillColor(248, 250, 252); // Soft premium grey/blue
                $this->Rect(15, $startY, 180, $rowHeight, 'F');
            }
            
            // Column 1: #
            $this->SetFont('Helvetica', '', 8.5);
            $this->SetTextColor(51, 65, 85);
            $this->SetXY(15, $startY);
            $this->Cell($w[0], $rowHeight, $index . '.', 0, 0, 'C');
            
            // Column 2: Medicine Details (Name + Generic) - Vertically Centered!
            $textHeight = $lines * 4.5;
            $verticalOffset = ($rowHeight - $textHeight) / 2;
            
            $this->SetXY(15 + $w[0], $startY + $verticalOffset);
            $this->SetTextColor(15, 23, 42); // Dark slate
            $this->SetFont('Helvetica', 'B', 8.5);
            
            $this->MultiCell($w[1], 4.5, $details, 0, 'L', false);
            
            // Column 3: Batch No.
            $this->SetFont('Helvetica', '', 8.5);
            $this->SetTextColor(51, 65, 85);
            $this->SetXY(15 + $w[0] + $w[1], $startY);
            $this->Cell($w[2], $rowHeight, $item['batch_number'], 0, 0, 'L');
            
            // Column 4: Branch
            $this->Cell($w[3], $rowHeight, $item['branch_name'], 0, 0, 'L');
            
            // Column 5: Qty
            $this->Cell($w[4], $rowHeight, $item['quantity'], 0, 0, 'C');
            
            // Determine Urgency based on Days Left
            $daysLeft = intval($item['days_left']);
            
            if ($daysLeft < 0) {
                // Expired: Solid Red
                $textClr = [220, 38, 38];
                $fontStyle = 'B';
                $daysText = 'Expired';
            } elseif ($daysLeft === 0) {
                // Expire Today: Solid Red
                $textClr = [220, 38, 38];
                $fontStyle = 'B';
                $daysText = 'Expire Today';
            } else {
                // Others: Orange
                $textClr = [249, 115, 22];
                $fontStyle = 'B';
                $daysText = $daysLeft . 'd left';
            }
            
            // Column 6: Expiry Date (Urgency colored)
            $this->SetTextColor($textClr[0], $textClr[1], $textClr[2]);
            $this->SetFont('Helvetica', $fontStyle, 8.5);
            $this->Cell($w[5], $rowHeight, $item['expiry_date'], 0, 0, 'C');
            
            // Column 7: Status / Days remaining (Urgency colored)
            $this->Cell($w[6], $rowHeight, $daysText, 0, 0, 'C');
            
            // Draw clean light borders around all cells in this row
            $this->SetDrawColor(226, 232, 240); // Slate 200 border
            $this->SetLineWidth(0.2);
            $xOffset = 15;
            for ($i = 0; $i < count($w); $i++) {
                $this->Rect($xOffset, $startY, $w[$i], $rowHeight);
                $xOffset += $w[$i];
            }
            
            // Reset position to next line
            $this->SetXY(15, $startY + $rowHeight);
            
            // Alternate fill row background
            $fill = !$fill;
            $index++;
        }
        
        // Output PDF to string representation
        return $this->Output('S');
    }
}
