<?php

namespace App\Services;

class SimplePdfGenerator
{
    public function generatePdf($data)
    {
        // Create a simple HTML-based invoice
        $html = $this->createInvoiceHtml($data);
        
        // Convert to basic PDF format
        return $this->createBasicPdf($html, $data);
    }
    
    private function createInvoiceHtml($data)
    {
        $company = $data['company'];
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Invoice #' . $data['invoice_number'] . '</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: "Helvetica Neue", Arial, sans-serif; 
            color: #333; 
            line-height: 1.4;
            background: #fff;
            padding: 20px;
        }
        .invoice-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 0;
            background: #fff;
            border: 1px solid #ddd;
        }
        .invoice-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 30px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-bottom: 2px solid #007bff;
        }
        .company-info h1 {
            font-size: 28px;
            color: #2c3e50;
            margin-bottom: 8px;
            font-weight: 700;
        }
        .company-info p {
            font-size: 14px;
            color: #666;
            margin-bottom: 4px;
        }
        .invoice-info {
            text-align: right;
        }
        .invoice-info h2 {
            font-size: 24px;
            color: #007bff;
            margin-bottom: 8px;
            font-weight: 700;
        }
        .invoice-info .invoice-number {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
        }
        .invoice-info .invoice-date {
            font-size: 14px;
            color: #666;
        }
        .invoice-body {
            padding: 30px;
        }
        .billing-section {
            margin-bottom: 30px;
        }
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 15px;
            text-transform: uppercase;
            letter-spacing: 1px;
            border-bottom: 2px solid #007bff;
            padding-bottom: 5px;
            display: inline-block;
        }
        .billing-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-top: 20px;
        }
        .billing-box {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #007bff;
        }
        .billing-box h3 {
            font-size: 14px;
            color: #007bff;
            margin-bottom: 10px;
            text-transform: uppercase;
            font-weight: 600;
        }
        .billing-box p {
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-radius: 8px;
            overflow: hidden;
        }
        .items-table thead {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
        }
        .items-table th {
            padding: 15px 12px;
            text-align: left;
            font-weight: 600;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .items-table td {
            padding: 15px 12px;
            border-bottom: 1px solid #e0e0e0;
            font-size: 14px;
        }
        .items-table tbody tr:nth-child(even) {
            background: #f8f9fa;
        }
        .items-table tbody tr:hover {
            background: #e3f2fd;
        }
        .text-right {
            text-align: right;
            font-weight: 600;
            color: #007bff;
        }
        .totals-section {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-top: 3px solid #007bff;
        }
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 16px;
        }
        .total-row.final {
            font-size: 20px;
            font-weight: 700;
            color: #007bff;
            border-top: 2px solid #dee2e6;
            padding-top: 10px;
            margin-top: 10px;
        }
        .invoice-footer {
            padding: 30px;
            text-align: center;
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
        .footer-text {
            font-size: 12px;
            color: #666;
        }
        .thank-you {
            font-size: 16px;
            color: #007bff;
            font-weight: 600;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="invoice-container">
        <div class="invoice-header">
            <div class="company-info">
                <h1>' . $company['name'] . '</h1>
                <p>' . $company['address'] . ', ' . $company['city'] . '</p>
                <p>' . $company['state'] . ' - ' . $company['pincode'] . '</p>
                <p>Phone: ' . $company['phone_number'] . '</p>
                <p>GST: ' . $company['gst_number'] . '</p>
            </div>
            <div class="invoice-info">
                <h2>INVOICE</h2>
                <div class="invoice-number">#' . $data['invoice_number'] . '</div>
                <div class="invoice-date">Date: ' . $data['date'] . '</div>
            </div>
        </div>
        
        <div class="invoice-body">
            <div class="billing-section">
                <div class="section-title">Billing Information</div>
                <div class="billing-grid">
                    <div class="billing-box">
                        <h3>Bill To</h3>
                        <p><strong>' . $data['client_name'] . '</strong></p>
                        <p>' . $data['client_phone'] . '</p>
                        <p>' . $data['client_address'] . '</p>
                    </div>
                    <div class="billing-box">
                        <h3>Registration Details</h3>
                        <p><strong>ID:</strong> ' . $data['registration_id'] . '</p>
                        <p><strong>Plan:</strong> ' . $data['membership_plan'] . '</p>
                        <p><strong>Contract:</strong> ' . $data['contract_period'] . '</p>
                    </div>
                </div>
            </div>
            
            <div class="section-title">Locker Details</div>
            <table class="items-table">
                <thead>
                    <tr>
                        <th>Locker #</th>
                        <th>Size</th>
                        <th>Type</th>
                        <th class="text-right">Amount</th>
                    </tr>
                </thead>
                <tbody>';
        
        foreach ($data['items'] as $item) {
            $html .= '
                    <tr>
                        <td>' . $item['locker_number'] . '</td>
                        <td>' . $item['size'] . '</td>
                        <td>' . $item['type'] . '</td>
                        <td class="text-right">MR ' . number_format($item['amount'], 2) . '</td>
                    </tr>';
        }
        
        $html .= '
                </tbody>
            </table>
            
            <div class="totals-section">
                <div class="total-row">
                    <span>Subtotal:</span>
                    <span>MR ' . number_format($data['total_amount'], 2) . '</span>
                </div>
                <div class="total-row">
                    <span>Tax (0%):</span>
                    <span>MR 0.00</span>
                </div>
                <div class="total-row final">
                    <span>TOTAL:</span>
                    <span>MR ' . number_format($data['total_amount'], 2) . '</span>
                </div>
            </div>
            
            <div style="margin-top: 20px; padding: 15px; background: #d1ecf1; border-left: 4px solid #17a2b8; border-radius: 4px;">
                <h4 style="margin: 0 0 10px 0; font-size: 16px; color: #0c5460;">Calculation Breakdown:</h4>
                <div style="font-size: 14px; color: #0c5460;">
                    <div style="margin-bottom: 5px;"><strong>Number of Items:</strong> ' . count($data['items']) . ' locker(s)</div>
                    <div style="margin-bottom: 5px;"><strong>Amount per Item:</strong> MR ' . number_format($data['total_amount'] / count($data['items']), 2) . '</div>
                    <div style="margin-bottom: 5px;"><strong>Subtotal:</strong> MR ' . number_format($data['total_amount'], 2) . '</div>
                    <div style="margin-bottom: 5px;"><strong>Tax (0%):</strong> MR 0.00</div>
                    <div style="border-top: 1px solid #bee5eb; padding-top: 5px; margin-top: 10px;">
                        <strong>Total Amount:</strong> MR ' . number_format($data['total_amount'], 2) . '
                    </div>
                </div>
            </div>
            
            <div style="margin-top: 15px; padding: 12px; background: #f8f9fa; border-radius: 4px; font-size: 12px; color: #6c757d;">
                <strong>Formula:</strong> Total = (Amount per Item × Number of Items) + Tax<br>
                <strong>Calculation:</strong> MR ' . number_format($data['total_amount'] / count($data['items']), 2) . ' × ' . count($data['items']) . ' + MR 0.00 = MR ' . number_format($data['total_amount'], 2) . '
            </div>
        </div>
        
        <div class="invoice-footer">
            <div class="thank-you">Thank you for your business!</div>
            <div class="footer-text">This is a system-generated invoice. For any questions, please contact our support team.</div>
        </div>
    </div>
</body>
</html>';
        
        return $html;
    }
    
    private function createBasicPdf($html, $data)
    {
        // Create a professional text-based PDF
        $lines = [];
        $company = $data['company'];
        
        // Professional invoice header
        $lines[] = str_repeat('=', 60);
        $lines[] = sprintf('%-30s %30s', $company['name'], 'INVOICE #' . $data['invoice_number']);
        $lines[] = sprintf('%-30s %30s', $company['address'] . ', ' . $company['city'], $data['date']);
        $lines[] = sprintf('%-30s %30s', $company['state'] . ' - ' . $company['pincode'], '');
        $lines[] = sprintf('%-30s %30s', 'Phone: ' . $company['phone_number'], '');
        $lines[] = sprintf('%-30s %30s', 'GST: ' . $company['gst_number'], '');
        $lines[] = str_repeat('=', 60);
        $lines[] = '';
        
        // Bill To section
        $lines[] = 'BILL TO:';
        $lines[] = str_repeat('-', 60);
        $lines[] = sprintf('%-15s %s', 'Client:', $data['client_name']);
        $lines[] = sprintf('%-15s %s', 'Phone:', $data['client_phone']);
        $lines[] = sprintf('%-15s %s', 'Address:', $data['client_address']);
        $lines[] = '';
        
        // Registration Details
        $lines[] = 'REGISTRATION DETAILS:';
        $lines[] = str_repeat('-', 60);
        $lines[] = sprintf('%-20s %s', 'Registration ID:', $data['registration_id']);
        $lines[] = sprintf('%-20s %s', 'Membership Plan:', $data['membership_plan']);
        $lines[] = sprintf('%-20s %s', 'Contract Period:', $data['contract_period']);
        $lines[] = '';
        
        // Locker Details Table
        $lines[] = 'LOCKER DETAILS:';
        $lines[] = str_repeat('-', 60);
        $lines[] = sprintf('%-12s %-12s %-12s %20s', 
            'Locker #', 'Size', 'Type', 'Amount'
        );
        $lines[] = str_repeat('-', 60);
        
        foreach ($data['items'] as $item) {
            $lines[] = sprintf('%-12s %-12s %-12s %20s', 
                $item['locker_number'], 
                $item['size'], 
                $item['type'], 
                'MR ' . number_format($item['amount'], 2)
            );
        }
        
        $lines[] = str_repeat('-', 60);
        $lines[] = sprintf('%48s %20s', 'TOTAL:', 'MR ' . number_format($data['total_amount'], 2));
        $lines[] = str_repeat('=', 60);
        $lines[] = '';
        $lines[] = 'Note: Total includes ' . count($data['items']) . ' locker item(s) at MR ' . number_format($data['total_amount'] / count($data['items']), 2) . ' per item.';
        $lines[] = '';
        $lines[] = 'This is a system-generated invoice. Thank you for your business!';
        $lines[] = str_repeat('=', 60);
        
        // Generate PDF content
        $content = "BT\n/F1 12 Tf\n50 750 Td\n";
        $y = 750;
        
        foreach ($lines as $line) {
            $escaped = str_replace(['(', ')', '\\'], ['\\(', '\\)', '\\\\'], $line);
            $content .= "({$escaped}) Tj\n";
            $y -= 15;
            
            if ($y < 50) {
                break; // Prevent going off page
            } else {
                $content .= "0 -15 Td\n";
            }
        }
        
        $content .= "ET\n";
        
        $length = strlen($content);
        
        $pdf = '%PDF-1.4
1 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj

2 0 obj
<<
/Type /Pages
/Kids [3 0 R]
/Count 1
>>
endobj

3 0 obj
<<
/Type /Page
/Parent 2 0 R
/MediaBox [0 0 612 792]
/Contents 4 0 R
/Resources <<
/Font <<
/F1 5 0 R
>>
>>
>>
endobj

4 0 obj
<<
/Length ' . $length . ' >>
stream
' . $content . '
endstream
endobj

5 0 obj
<<
/Type /Font
/Subtype /Type1
/BaseFont /Helvetica
>>
endobj

xref
0 6
0000000000 65535 f 
0000000009 00000 n 
0000000058 00000 n 
0000000115 00000 n 
0000000274 00000 n 
0000000' . (275 + $length) . ' 00000 n 
trailer
<<
/Size 6
/Root 1 0 R
>>
startxref
' . (280 + $length) . '
%%EOF';
        
        return $pdf;
    }
}
