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

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

// Restore classic mysqli error-return behaviour instead of PHP 8.1+'s fatal
// mysqli_sql_exception, so a query failure comes back as JSON, not an HTML
// crash dump inside what's supposed to be an AJAX response.
if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_OFF); }

if (!isset($_SESSION["username_".$dbname])) {
    echo json_encode(['success'=>false,'message'=>'Session expired. Please re-login.']);
    exit;
}

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

// ── Defensive auto-migrate (keep in sync with sale.php) ────────────────────
foreach ([
    'lrimage' => "VARCHAR(200) NOT NULL DEFAULT ''",
    'soref'   => "VARCHAR(100) NOT NULL DEFAULT ''",
] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `sale` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0) {
        mysqli_query($conn, "ALTER TABLE `sale` ADD COLUMN `$col` $def");
    }
}

try {

$vouchno = isset($_POST['vouchno']) ? (int)$_POST['vouchno'] : 0;
if ($vouchno <= 0) {
    echo json_encode(['success'=>false,'message'=>'Invalid sale invoice.']);
    exit;
}

$chkSale = mysqli_query($conn, "SELECT `vouchno`,`lrimage`,`soref` FROM `sale` WHERE `vouchno`='$vouchno'");
$saleRow = $chkSale ? mysqli_fetch_assoc($chkSale) : null;
if (!$saleRow) {
    echo json_encode(['success'=>false,'message'=>'Sale invoice not found.']);
    exit;
}

if (!isset($_FILES['lrimage']) || $_FILES['lrimage']['error'] === UPLOAD_ERR_NO_FILE) {
    echo json_encode(['success'=>false,'message'=>'No file uploaded.']);
    exit;
}

$img = $_FILES['lrimage'];
$lrImageMaxSize = 2 * 1024 * 1024; // 2 MB

if ($img['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success'=>false,'message'=>'Upload failed.']);
    exit;
}
if ($img['size'] > $lrImageMaxSize) {
    echo json_encode(['success'=>false,'message'=>'File size must be up to 2 MB.']);
    exit;
}

$allowedExt = ['jpg'=>'image/jpeg','jpeg'=>'image/jpeg','png'=>'image/png','gif'=>'image/gif','webp'=>'image/webp'];
$ext  = strtolower(pathinfo($img['name'], PATHINFO_EXTENSION));
$mime = mime_content_type($img['tmp_name']);

if (!isset($allowedExt[$ext]) || $mime != $allowedExt[$ext]) {
    echo json_encode(['success'=>false,'message'=>'Only JPG, PNG, GIF or WEBP images are allowed.']);
    exit;
}

require_once("upload_path.php");
// LR images get their own bucket (uploads/lrimage/{finyear}/) instead of
// sharing the general 'sale' upload folder with unrelated sale attachments.
$_upSale   = upload_path('lrimage');
$uploaddir = $_upSale['dir'];

$newname = 'lr_' . $vouchno . '_' . time() . '.' . $ext;
if (!move_uploaded_file($img['tmp_name'], $uploaddir . $newname)) {
    echo json_encode(['success'=>false,'message'=>'Could not save uploaded file.']);
    exit;
}

// Remove old LR image file if replacing
if (!empty($saleRow['lrimage']) && file_exists($uploaddir . $saleRow['lrimage'])) {
    @unlink($uploaddir . $saleRow['lrimage']);
}

$audituser = mysqli_real_escape_string($conn, audituser());
$ok = mysqli_query($conn, "UPDATE `sale` SET `lrimage`='" . mysqli_real_escape_string($conn, $newname) . "',
    `edituser`='$audituser', `editdate`=CURDATE(), `edittime`=CURTIME()
    WHERE `vouchno`='$vouchno'");

if (!$ok) {
    echo json_encode(['success'=>false,'message'=>mysqli_error($conn)]);
    exit;
}

// ── Mirror onto the source Sale Order(s) this invoice was generated from ───
// (soref = comma-separated saleorder vouchno(s), set by
// includes/pendinginvoice_geninvoice.php when Dispatch Alert's "Generate
// Invoice" creates this invoice). Same shipment, same LR document — copies
// the file into each sale order's own bucket/naming convention so
// dispatchalert.php's existing view/URL logic needs no changes.
$soref = trim((string)($saleRow['soref'] ?? ''));
if ($soref !== '') {
    $soVouchnos = array_filter(array_map('intval', explode(',', $soref)));
    if ($soVouchnos) {
        $_upSO      = upload_path('so_lrimage');
        $soUploaddir = $_upSO['dir'];
        foreach ($soVouchnos as $soVouchno) {
            $soRowRes = mysqli_query($conn, "SELECT `lrimage` FROM `saleorder` WHERE `vouchno`='$soVouchno'");
            $soRow    = $soRowRes ? mysqli_fetch_assoc($soRowRes) : null;
            if ($soRow === null) continue;
            $soNewname = 'solr_' . $soVouchno . '_' . time() . '.' . $ext;
            if (copy($uploaddir . $newname, $soUploaddir . $soNewname)) {
                if (!empty($soRow['lrimage']) && file_exists($soUploaddir . $soRow['lrimage'])) {
                    @unlink($soUploaddir . $soRow['lrimage']);
                }
                mysqli_query($conn, "UPDATE `saleorder` SET `lrimage`='" . mysqli_real_escape_string($conn, $soNewname) . "' WHERE `vouchno`='$soVouchno'");
            }
        }
    }
}

if (ob_get_level() > 0) { ob_clean(); }
echo json_encode(['success'=>true, 'lrimage'=>$newname]);

} catch (\Throwable $e) {
    if (ob_get_level() > 0) { ob_clean(); }
    echo json_encode(['success'=>false, 'message'=>$e->getMessage()]);
}
