# PDF, Barcode & QR Code Documentation

## 🎯 Features Implemented

### 1. PDF Templates
- ✅ Purchase Order (PO) PDF
- ✅ Delivery Order (DO/Surat Jalan) PDF  
- ✅ Invoice PDF (template ready)

### 2. Barcode & QR Code Generation
- ✅ Barcode generation for Finish Goods (CODE128, EAN13, etc.)
- ✅ QR Code generation with product tracking data
- ✅ Printable label with barcode + QR code + product info

---

## 📄 PDF Generation

### Purchase Order PDF

**Endpoint:** `GET /api/purchase-orders/{id}/pdf`

**Authentication:** Required (Bearer Token)

**Response:** PDF file download (`PO_xxxxxxxx.pdf`)

**Usage Example:**
```javascript
// Direct download link
const downloadPOPdf = (poId) => {
  window.open(`/api/purchase-orders/${poId}/pdf`, '_blank');
};

// Or with axios
import api from '@/services/api';

const response = await api.get(`/purchase-orders/${poId}/pdf`, {
  responseType: 'blob'
});

const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `PO_${poNumber}.pdf`);
document.body.appendChild(link);
link.click();
```

**Template Features:**
- Company header with logo area
- Supplier information
- Order details (PO number, dates, status)
- Itemized product list with quantities and prices
- Subtotal, discount, tax, and total calculations
- Terms & conditions
- Signature sections (Prepared By, Approved By, Supplier)

---

### Delivery Order PDF

**Endpoint:** `GET /api/delivery-orders/{id}/pdf`

**Authentication:** Required (Bearer Token)

**Response:** PDF file download (`DO_xxxxxxxx.pdf`)

**Template Features:**
- Bilingual headers (Indonesian & English)
- Customer delivery address
- Driver and vehicle information
- QR Code embedded for tracking
- Product list with pallet numbers
- Signature sections (Sender, Driver, Receiver, Company Stamp)
- Important notes and instructions

**Usage Example:**
```javascript
const downloadDOPdf = (doId) => {
  window.open(`/api/delivery-orders/${doId}/pdf`, '_blank');
};
```

---

## 🔢 Barcode Generation

### Generate Barcode Image

**Endpoint:** `GET /api/finish-goods/{id}/barcode`

**Query Parameters:**
- `type` (optional): Barcode type - `C128` (default), `EAN13`, `C39`, etc.
- `width` (optional): Bar width in pixels (default: 2)
- `height` (optional): Bar height in pixels (default: 50)

**Response:**
```json
{
  "success": true,
  "data": {
    "barcode": "FG202602150123451234",
    "image": "data:image/png;base64,iVBORw0KG...",
    "type": "C128"
  }
}
```

**Usage Example:**
```vue
<template>
  <div>
    <img :src="barcodeImage" alt="Barcode" />
    <p>{{ barcodeText }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from '@/services/api';

const barcodeImage = ref('');
const barcodeText = ref('');

const loadBarcode = async (finishGoodId) => {
  const response = await api.get(`/finish-goods/${finishGoodId}/barcode`, {
    params: { type: 'C128', width: 2, height: 50 }
  });
  
  barcodeImage.value = response.data.data.image;
  barcodeText.value = response.data.data.barcode;
};

onMounted(() => loadBarcode(123));
</script>
```

---

### Download Barcode

**Endpoint:** `GET /api/finish-goods/{id}/barcode/download`

**Query Parameters:** Same as generate barcode

**Response:** PNG image file download (`barcode_FGxxxxxxxx.png`)

**Usage:**
```javascript
const downloadBarcode = (finishGoodId) => {
  window.open(`/api/finish-goods/${finishGoodId}/barcode/download?type=C128`, '_blank');
};
```

---

## 📱 QR Code Generation

### Generate QR Code

**Endpoint:** `GET /api/finish-goods/{id}/qrcode`

**Query Parameters:**
- `size` (optional): QR code size in pixels (default: 200)

**Response:**
```json
{
  "success": true,
  "data": {
    "qr_data": {
      "fg_number": "FG202402150001",
      "product": "Carton Box Type A",
      "quantity": 1000,
      "pallet": "PLT-001",
      "date": "2024-02-15",
      "warehouse": "Main Warehouse",
      "barcode": "FG202602150123451234",
      "url": "http://localhost:8000/api/finish-goods/123"
    },
    "image": "data:image/png;base64,iVBORw0KG..."
  }
}
```

**Usage Example:**
```vue
<template>
  <img :src="qrCodeImage" alt="QR Code" style="width: 200px;" />
</template>

<script setup>
import { ref } from 'vue';
import api from '@/services/api';

const qrCodeImage = ref('');

const generateQrCode = async (finishGoodId) => {
  const response = await api.get(`/finish-goods/${finishGoodId}/qrcode`, {
    params: { size: 300 }
  });
  qrCodeImage.value = response.data.data.image;
};
</script>
```

---

### Download QR Code

**Endpoint:** `GET /api/finish-goods/{id}/qrcode/download`

**Response:** PNG image file download (`qrcode_FGxxxxxxxx.png`)

---

## 🏷️ Generate Printable Label

**Endpoint:** `GET /api/finish-goods/{id}/label`

**Description:** Generates a complete printable label with barcode, QR code, and product information.

**Response:**
```json
{
  "success": true,
  "data": {
    "fg_number": "FG202402150001",
    "product_name": "Carton Box Type A",
    "product_code": "CB-001",
    "quantity": 1000,
    "unit": "pcs",
    "pallet_number": "PLT-001",
    "warehouse": "Main Warehouse",
    "location": "A-01-02",
    "date": "15 Feb 2024",
    "barcode_text": "FG202602150123451234",
    "barcode_image": "data:image/png;base64,...",
    "qr_code_image": "data:image/png;base64,..."
  }
}
```

**Usage with Vue Component:**
```vue
<template>
  <BarcodeQrCodeDisplay :finish-good-id="123" />
</template>

<script setup>
import BarcodeQrCodeDisplay from '@/components/BarcodeQrCodeDisplay.vue';
</script>
```

---

## 🔧 Configuration

### DomPDF Configuration

Edit `config/dompdf.php`:

```php
return [
    'show_warnings' => false,
    'public_path' => null,
    'convert_entities' => true,
    'options' => [
        'font_dir' => storage_path('fonts/'),
        'font_cache' => storage_path('fonts/'),
        'temp_dir' => sys_get_temp_dir(),
        'chroot' => realpath(base_path()),
        'enable_php' => false,
        'enable_javascript' => true,
        'enable_remote' => true,
        'enable_css_float' => true,
        'enable_html5_parser' => true,
    ],
];
```

---

## 📊 Supported Barcode Types

- **CODE128** (`C128`) - Recommended for general use
- **EAN13** - For retail products
- **CODE39** (`C39`) - Alphanumeric
- **CODE93** (`C93`)
- **UPCA**
- **UPCE**

---

## 🎨 Customization

### Custom PDF Template

1. Create new blade file in `resources/views/pdf/`
2. Add method in controller:

```php
public function downloadCustomPdf($id)
{
    $data = YourModel::find($id);
    $pdf = Pdf::loadView('pdf.custom_template', ['data' => $data]);
    $pdf->setPaper('a4', 'landscape'); // or 'portrait'
    return $pdf->download('custom.pdf');
}
```

### Custom Barcode Style

```php
DNS1D::getBarcodePNG($code, 'C128', 3, 80, [255,0,0]); // Red barcode
```

---

## 🚀 Testing

### Test PDF Generation:
```bash
# From browser
http://localhost:8000/api/purchase-orders/1/pdf
http://localhost:8000/api/delivery-orders/1/pdf
```

### Test Barcode Generation:
```bash
# From browser or Postman
http://localhost:8000/api/finish-goods/1/barcode
http://localhost:8000/api/finish-goods/1/qrcode
http://localhost:8000/api/finish-goods/1/label
```

---

## 📦 Packages Used

- **barryvdh/laravel-dompdf** (v3.1) - PDF generation
- **simplesoftwareio/simple-qrcode** (v4.2) - QR code generation
- **milon/barcode** (v12.1) - Barcode generation

---

## 💡 Tips

1. **PreLoad Relations:** Always eager load relationships to avoid N+1 queries
2. **Cache QR Codes:** For frequently accessed items, consider caching QR codes
3. **PDF Assets:** Use absolute paths for images in PDF templates
4. **Mobile Scanning:** Test QR codes with actual mobile devices
5. **Print Quality:** Use higher DPI for print labels (300dpi recommended)

---

## 🐛 Troubleshooting

### PDF not generating?
- Check if `storage/fonts` directory is writable
- Verify all relationships are loaded
- Check PHP memory limit (increase if needed)

### Barcode not displaying?
- Verify barcode text format is valid
- Check barcode type is supported
- Ensure GD extension is enabled

### QR Code scanning issues?
- Increase QR code size (300x300 minimum for scanning)
- Use error correction level 'H' for damaged labels
- Ensure good contrast (dark on light background)

---

**Happy Coding! 🎉**
