<?php
ob_start();
require("dbconnect.php");
require("config.php");
require("function.php");

if (!isset($_SESSION["username_" . $dbname])) {
    header('Content-Type: application/json');
    echo json_encode(['ok' => false, 'error' => 'Not logged in']);
    exit;
}

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

require_once("upload_path.php");
$_upBc      = upload_path('billconf');
$bcUploadDir = $_upBc['dir'];   // absolute path for file_exists/file_get_contents
$bcUploadUrl = $_upBc['url'];   // relative URL (not used for pickup but kept for consistency)

$action = isset($_POST['action']) ? $_POST['action'] : 'list';

header('Content-Type: application/json');

if ($action == 'get') {
    $vouchno = isset($_POST['vouchno']) ? (int)$_POST['vouchno'] : 0;
    if ($vouchno <= 0) {
        echo json_encode(['ok' => false, 'error' => 'Invalid voucher']);
        exit;
    }

    $result = mysqli_query($conn,
        "SELECT b.*, p.name AS partyname, s.name AS suppliername
         FROM `billconf` b
         LEFT JOIN `accmast` p ON p.accode = b.party
         LEFT JOIN `accmast` s ON s.accode = b.supplier
         WHERE b.vouchno='$vouchno'") or die(mysqli_error($conn));
    $get = mysqli_fetch_assoc($result);
    if (!$get) {
        echo json_encode(['ok' => false, 'error' => 'Voucher not found']);
        exit;
    }

    $tres  = mysqli_query($conn, "SELECT * FROM `billconftr` WHERE `vouchno`='$vouchno' ORDER BY `srl`") or die(mysqli_error($conn));
    $lines = [];
    while ($r = mysqli_fetch_assoc($tres)) {
        // Convert picfile to base64 data URI so the browser can show it
        $imageData = '';
        $picfile   = isset($r['picfile']) ? $r['picfile'] : '';
        if ($picfile != '') {
            $fullPath = $bcUploadDir . $picfile;
            // If not found in current year folder, scan all year subfolders
            if (!file_exists($fullPath)) {
                $baseUploads = dirname(rtrim($bcUploadDir, '/')) . '/';  // .../uploads/billconf/
                if (is_dir($baseUploads)) {
                    foreach (scandir($baseUploads) as $sub) {
                        if ($sub === '.' || $sub === '..') continue;
                        $candidate = $baseUploads . $sub . '/' . $picfile;
                        if (file_exists($candidate)) { $fullPath = $candidate; break; }
                    }
                }
            }
            if (file_exists($fullPath)) {
                $ext  = strtolower(pathinfo($picfile, PATHINFO_EXTENSION));
                $mime = ($ext === 'jpg' || $ext === 'jpeg') ? 'image/jpeg' : "image/$ext";
                $imageData = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($fullPath));
            }
        }

        $lines[] = [
            'description' => $r['description'],
            'shipmark'    => $r['shipmark'] ?? '',
            'ctn'         => (float)$r['ctn'],
            'qty'         => (float)$r['qty'],
            'tqty'        => (float)$r['tqty'],
            'amt'         => (float)($r['amt'] ?? 0),
            'cbm'         => (float)$r['cbm'],
            'weight'      => (float)$r['weight'],
            'picfile'     => $picfile,
            'imageData'   => $imageData,
        ];
    }

    echo json_encode([
        'ok'           => true,
        'vouchno'      => (int)$get['vouchno'],
        'shipmark'     => $get['shipmark'],
        'supplier'     => (int)$get['supplier'],
        'suppliername' => $get['suppliername'],
        'customer'     => (int)$get['party'],
        'customername' => $get['partyname'],
        'advance'      => (float)($get['advance'] ?? 0),
        'lines'        => $lines,
    ]);
    exit;
}

// action == 'list'
// Only show Bill Confirming vouchers NOT yet referenced by any purchase
$search   = isset($_POST['search'])   ? mysqli_real_escape_string($conn, trim($_POST['search'])) : '';
$page     = isset($_POST['page'])     ? max(1, (int)$_POST['page']) : 1;
$customer = isset($_POST['customer']) ? (int)$_POST['customer'] : 0;
$supplier = isset($_POST['supplier']) ? (int)$_POST['supplier'] : 0;
$pagesize = 8;

// "Not picked yet" only applies for purchase pickup — loading plan can pick any BC
$caller = isset($_POST['caller']) ? trim($_POST['caller']) : 'purchase';
$jsfunc = ($caller === 'loadingplan') ? 'bcPickSelect' : 'bcPick';

$notPickedCond = ($caller !== 'loadingplan')
    ? "AND b.vouchno NOT IN (SELECT DISTINCT `billconfref` FROM `purchase` WHERE `billconfref` > 0)"
    : '';
$customerCond = ($customer > 0) ? "AND b.`party`='$customer'"    : '';
$supplierCond = ($supplier > 0) ? "AND b.`supplier`='$supplier'" : '';

$where = "WHERE 1=1 $notPickedCond $customerCond $supplierCond";
if ($search != '') {
    $where .= " AND (b.shipmark LIKE '%$search%' OR b.remarks LIKE '%$search%' OR p.name LIKE '%$search%' OR s.name LIKE '%$search%')";
}

$totalRes = mysqli_query($conn,
    "SELECT COUNT(*) AS cnt FROM `billconf` b
     LEFT JOIN `accmast` p ON p.accode = b.party
     LEFT JOIN `accmast` s ON s.accode = b.supplier
     $where") or die(mysqli_error($conn));
$total = (int) mysqli_fetch_assoc($totalRes)['cnt'];
$pages = max(1, (int) ceil($total / $pagesize));
if ($page > $pages) $page = $pages;
$offset = ($page - 1) * $pagesize;

$result = mysqli_query($conn,
    "SELECT b.*, p.name AS partyname, s.name AS suppliername
     FROM `billconf` b
     LEFT JOIN `accmast` p ON p.accode = b.party
     LEFT JOIN `accmast` s ON s.accode = b.supplier
     $where
     ORDER BY b.vouchno DESC LIMIT $pagesize OFFSET $offset") or die(mysqli_error($conn));

$rows = '';
$alt  = false;
while ($row = mysqli_fetch_array($result)) {
    $bg  = $alt ? '#f8fafc' : '#fff';
    $alt = !$alt;
    $dt  = $row['vouchdt'] != '0000-00-00' ? date('d-m-Y', strtotime($row['vouchdt'])) : '';
    $adv = (float)($row['advance'] ?? 0);
    $advDisp = $adv > 0 ? number_format($adv, 2) : '';
    $rows .= '<tr class="srch-row" style="cursor:pointer;background:' . $bg . ';transition:background .1s;"'
        . ' onmouseover="this.style.background=\'#eff6ff\'"'
        . ' onmouseout="this.style.background=\'' . $bg . '\'"'
        . ' onclick="' . $jsfunc . '(' . (int)$row['vouchno'] . ')">'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;font-weight:600;">' . $row['vouchno'] . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;">' . $dt . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;font-weight:500;color:#1e293b;">' . htmlspecialchars($row['partyname'] ?? '') . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;">' . htmlspecialchars($row['suppliername'] ?? '') . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;">' . htmlspecialchars($row['shipmark']) . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;text-align:right;color:#16a34a;font-weight:600;">' . $advDisp . '</td>'
        . '</tr>';
}

if ($total == 0) {
    $rows = '<tr><td colspan="5" style="text-align:center;padding:24px;color:#94a3b8;">No unpicked Bill Confirming records found.</td></tr>';
}

echo json_encode([
    'rows'  => $rows,
    'total' => $total,
    'page'  => $page,
    'pages' => $pages,
]);
