<?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 dispatchalert.php) ──────────
foreach ([
    'lrimage'   => "VARCHAR(200) NOT NULL DEFAULT ''",
    'invoiceno' => "INT(11) NOT NULL DEFAULT 0",
] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `saleorder` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0) {
        mysqli_query($conn, "ALTER TABLE `saleorder` ADD COLUMN `$col` $def");
    }
}

try {

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

$chkSO = mysqli_query($conn, "SELECT `vouchno`,`lrimage`,`invoiceno` FROM `saleorder` WHERE `vouchno`='$vouchno'");
$soRow = $chkSO ? mysqli_fetch_assoc($chkSO) : null;
if (!$soRow) {
    echo json_encode(['success'=>false,'message'=>'Sale order 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");
// Sale order LR images get their own bucket (uploads/so_lrimage/{finyear}/),
// separate from Sale Invoice's own 'lrimage' bucket.
$_upSO     = upload_path('so_lrimage');
$uploaddir = $_upSO['dir'];

$newname = 'solr_' . $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($soRow['lrimage']) && file_exists($uploaddir . $soRow['lrimage'])) {
    @unlink($uploaddir . $soRow['lrimage']);
}

$audituser = mysqli_real_escape_string($conn, audituser());
$ok = mysqli_query($conn, "UPDATE `saleorder` 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 Sale Invoice generated from this order (if any) ────────
// LR copy is one physical document for the shipment; a sale order and the
// invoice raised against it (Dispatch Alert → Generate Invoice, see
// includes/pendinginvoice_geninvoice.php) should show the same one whichever
// side it was uploaded from. Copies the file into the Sale Invoice's own
// bucket/naming convention (rather than repointing sale.lrimage at this
// so_lrimage file) so sale.php's existing view/URL logic needs no changes.
$soInvoiceno = (int)($soRow['invoiceno'] ?? 0);
if ($soInvoiceno > 0) {
    $saleRowRes = mysqli_query($conn, "SELECT `lrimage` FROM `sale` WHERE `vouchno`='$soInvoiceno'");
    $saleRow    = $saleRowRes ? mysqli_fetch_assoc($saleRowRes) : null;
    if ($saleRow !== null) {
        $_upSale      = upload_path('lrimage');
        $saleUploaddir = $_upSale['dir'];
        $saleNewname   = 'lr_' . $soInvoiceno . '_' . time() . '.' . $ext;
        if (copy($uploaddir . $newname, $saleUploaddir . $saleNewname)) {
            if (!empty($saleRow['lrimage']) && file_exists($saleUploaddir . $saleRow['lrimage'])) {
                @unlink($saleUploaddir . $saleRow['lrimage']);
            }
            mysqli_query($conn, "UPDATE `sale` SET `lrimage`='" . mysqli_real_escape_string($conn, $saleNewname) . "' WHERE `vouchno`='$soInvoiceno'");
        }
    }
}

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()]);
}
