# Barcode Image Troubleshooting Guide

**Issue**: `/items/preview_labels` shows broken barcode images

**Last Updated**: 2025-11-20

---

## ✅ FIXES APPLIED:

### 1. Enhanced Barcode Controller
**File**: `application/controllers/Barcode.php`

**Added Features**:
- ✅ GD library check (required for image generation)
- ✅ Try-catch error handling
- ✅ Input sanitization
- ✅ Error logging to CodeIgniter logs
- ✅ Error image generation (shows "Barcode Error" if fails)
- ✅ Empty input handling

---

## 🔍 COMMON CAUSES & SOLUTIONS:

### Cause 1: GD Library Not Enabled (Most Common)

**Symptom**: Broken image icons, no barcode appears

**Check**:
```bash
php -r "echo extension_loaded('gd') ? 'GD enabled' : 'GD NOT enabled';"
```

**Fix for XAMPP (Windows)**:
1. Open `C:\xampp\php\php.ini`
2. Find line: `;extension=gd`
3. Remove semicolon: `extension=gd`
4. Save file
5. Restart Apache in XAMPP Control Panel
6. Verify: Visit `http://localhost/pos/phpinfo.php` and search for "gd"

**Fix for cPanel/Linux**:
1. Login to cPanel
2. Select PHP Version → Extensions
3. Check ☑ **gd**
4. Save
5. Or use command: `sudo apt-get install php-gd && sudo service apache2 restart`

---

### Cause 2: Zend Library Files Missing

**Symptom**: Error "Class 'Zend_Barcode' not found"

**Check**:
- Verify `application/libraries/Zend/Barcode.php` exists
- Verify `application/libraries/Zend/Barcode/Renderer/Image.php` exists

**Fix**:
- If missing, Zend library files need to be uploaded
- Complete Zend structure exists in local: `application/libraries/Zend/`
- Upload entire `Zend` folder to cPanel

---

### Cause 3: Base URL Issues

**Symptom**: Barcode URL is incorrect, 404 error

**Check**:
View page source, find barcode image tag:
```html
<img src="http://localhost/pos/barcode/TEST123">
```

**Verify URL works**: Visit `http://localhost/pos/barcode/TEST123` directly

**Fix**:
- Ensure .htaccess exists and mod_rewrite enabled
- Check base_url auto-detection (already implemented)
- Verify barcode controller accessible

---

### Cause 4: PHP 8 Compatibility Issues

**Symptom**: Errors about string casting, deprecated functions

**Check Error Log**:
```
application/logs/log-YYYY-MM-DD.php
```

**Fix**:
The updated Barcode controller already handles this with try-catch.

---

### Cause 5: Missing Item Barcode Data

**Symptom**: Some items show barcode, others don't

**Check**:
```sql
SELECT item_code, custom_barcode
FROM db_items
WHERE item_code IS NULL OR item_code = '';
```

**Fix**:
Items need valid `item_code` or `custom_barcode`:
```sql
UPDATE db_items
SET item_code = CONCAT('ITEM', id)
WHERE item_code IS NULL OR item_code = '';
```

---

## 🧪 TESTING:

### Test 1: Direct Barcode Generation

**Access**: `http://localhost/pos/barcode/TEST123`

**Expected Results**:
- ✅ Barcode image appears (black and white stripes)
- ✅ Text "TEST123" below barcode
- ✅ PNG image format

**If Broken**:
- ❌ Shows "GD library is not enabled" → Enable GD extension
- ❌ Shows "Barcode Error" image → Check error log
- ❌ 404 Not Found → Check .htaccess and routing

---

### Test 2: Preview Labels Page

**Steps**:
1. Navigate to Items > Items List
2. Select items with checkboxes
3. Click "Print Labels" button
4. Preview opens in new window/tab

**Expected Results**:
- ✅ Item names appear
- ✅ Prices appear
- ✅ Barcodes appear below each item
- ✅ Company name at top

**If Broken**:
Check browser console (F12) for 404 errors on barcode images.

---

### Test 3: Error Logging

**Check Log File**:
```
application/logs/log-YYYY-MM-DD.php
```

**Look for**:
```
ERROR - 2025-11-20: Barcode generation failed: [specific error message]
```

This will show the exact error causing barcode failure.

---

## 🔧 MANUAL VERIFICATION:

### Check GD Functions:

Create `test_gd.php` in root:
```php
<?php
if (extension_loaded('gd')) {
    echo "✅ GD is enabled<br>";
    $info = gd_info();
    echo "<pre>";
    print_r($info);
    echo "</pre>";

    // Test image creation
    $img = imagecreatetruecolor(200, 50);
    $bg = imagecolorallocate($img, 255, 255, 255);
    imagefilledrectangle($img, 0, 0, 200, 50, $bg);

    header('Content-Type: image/png');
    imagepng($img);
    imagedestroy($img);
} else {
    echo "❌ GD is NOT enabled - Please enable in php.ini";
}
?>
```

Visit: `http://localhost/pos/test_gd.php`

**Should show**: White PNG image

**If error**: GD not enabled properly

---

### Check Zend Library:

Create `test_zend.php` in root:
```php
<?php
define('BASEPATH', TRUE);
define('APPPATH', __DIR__ . '/application/');

require_once(APPPATH . 'libraries/Zend.php');
$zend = new Zend();
$zend->load('Zend/Barcode');

echo "✅ Zend Barcode library loaded successfully!<br>";
echo "Zend_Barcode class exists: " . (class_exists('Zend_Barcode') ? 'YES' : 'NO');
?>
```

Visit: `http://localhost/pos/test_zend.php`

**Should show**: "Zend Barcode library loaded successfully!"

---

## 📋 DEPLOYMENT CHECKLIST:

### For cPanel:

- [ ] Uploaded Barcode.php controller (with error handling)
- [ ] Uploaded complete Zend library folder
- [ ] Enabled GD extension in cPanel
- [ ] Verified .htaccess exists
- [ ] Tested direct barcode URL
- [ ] Tested preview labels page
- [ ] Checked error logs

---

## 🚨 STILL NOT WORKING?

### Debug Mode:

**Enable detailed errors** in Barcode controller (temporary):

```php
// Add at top of index() function
ini_set('display_errors', 1);
error_reporting(E_ALL);
echo "Starting barcode generation for: " . $input . "<br>";
```

Then visit: `http://localhost/pos/barcode/TEST123`

You'll see exact error messages.

**REMEMBER**: Remove debug code after fixing!

---

### Alternative: Generate Static Barcode Images

If Zend Barcode continues to fail, generate static images:

**Option A**: Use online barcode generator
1. Visit barcode-generator website
2. Generate images for each item
3. Save to `uploads/barcodes/ITEMCODE.png`
4. Update view to use static images

**Option B**: Use different PHP barcode library
- Consider: `picqer/php-barcode-generator`
- Install via Composer
- Replace Zend Barcode calls

---

## 💡 BEST PRACTICES:

### 1. Always Set Item Codes
Ensure all items have valid `item_code` or `custom_barcode`:
```sql
-- Check items without codes
SELECT id, item_name
FROM db_items
WHERE (item_code IS NULL OR item_code = '')
  AND (custom_barcode IS NULL OR custom_barcode = '');
```

### 2. Test After PHP Upgrades
PHP 8.x changes may affect Zend library - test barcodes after upgrades.

### 3. Monitor Error Logs
Check logs regularly for barcode generation errors.

### 4. Backup Zend Library
Keep copy of working Zend library for easy restoration.

---

## 📞 SUPPORT:

**Common Error Messages**:

| Error | Cause | Fix |
|-------|-------|-----|
| "Call to undefined function imagecreate()" | GD not enabled | Enable GD extension |
| "Class 'Zend_Barcode' not found" | Zend missing | Upload Zend library |
| "Barcode Error" image | Various | Check error log |
| 404 on barcode URL | Routing issue | Check .htaccess |
| Empty barcode field | Missing item_code | Update item data |

---

**File Locations**:
- Barcode Controller: `application/controllers/Barcode.php`
- Zend Library: `application/libraries/Zend/`
- Error Logs: `application/logs/log-YYYY-MM-DD.php`
- Preview Labels Model: `application/models/Items_model.php` (line 456)

---

**Last Updated**: 2025-11-20
**Status**: Error handling added, GD check implemented
**Next**: Test with actual items and verify on cPanel
