<?php
/**
 * bc_image.php — fetch base64 image for a packlist row
 * Priority: 1) purchase uploads by picfile, 2) look up purchasetr by
 * bcvouchno (via purchase.billconfref) + description.
 * (Bill Confirming's own upload bucket / billconftr fallback removed along
 * with the rest of that feature — Purchase is now the sole image source.)
 */
require_once(__DIR__ . '/upload_path.php');

function getBcImageSrc($conn, $picfile, $bcvouchno, $description) {
    $purUp   = upload_path('purchase');
    $purDir  = $purUp['dir'];
    $purBase = dirname(rtrim($purDir, '/')) . '/';

    $candidates = [];

    if (!empty($picfile)) {
        $candidates[] = $purDir . $picfile;
        if (is_dir($purBase)) {
            foreach (scandir($purBase) as $sub) {
                if ($sub === '.' || $sub === '..') continue;
                $candidates[] = $purBase . $sub . '/' . $picfile;
            }
        }
    }

    // Lookup from purchasetr by bcvouchno (via purchase.billconfref) + description
    if ((int)$bcvouchno > 0) {
        $bv   = (int)$bcvouchno;
        $desc = mysqli_real_escape_string($conn, $description);
        $pr = mysqli_query($conn, "SELECT vouchno FROM purchase WHERE billconfref='$bv' LIMIT 1");
        if ($pr && ($prow = mysqli_fetch_assoc($pr)) && $prow['vouchno']) {
            $pv  = (int)$prow['vouchno'];
            $ptr = mysqli_query($conn, "SELECT picfile FROM purchasetr WHERE vouchno='$pv' AND description='$desc' AND picfile!='' LIMIT 1");
            if (!$ptr || mysqli_num_rows($ptr) == 0)
                $ptr = mysqli_query($conn, "SELECT picfile FROM purchasetr WHERE vouchno='$pv' AND picfile!='' LIMIT 1");
            if ($ptr && ($ptrow = mysqli_fetch_assoc($ptr)) && !empty($ptrow['picfile'])) {
                $pf = $ptrow['picfile'];
                $candidates[] = $purDir . $pf;
                if (is_dir($purBase)) {
                    foreach (scandir($purBase) as $sub) {
                        if ($sub === '.' || $sub === '..') continue;
                        $candidates[] = $purBase . $sub . '/' . $pf;
                    }
                }
            }
        }
    }

    // Try each candidate path
    foreach ($candidates as $path) {
        if (file_exists($path) && is_file($path)) {
            $ext  = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            $mime = in_array($ext, ['jpg','jpeg']) ? 'image/jpeg' : "image/$ext";
            return 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($path));
        }
    }

    return '';
}
