<?php
require_once('config.php');

$error_message = '';
$valid = true;

$json_return = array();

$site_cd  = $_REQUEST['site_cd'] ?? '';
$mst_rowid = $_REQUEST['rowid'] ?? '';

$MobileURL = $_REQUEST['url'] ?? '';
$Folder    = $_REQUEST['folder'] ?? '';
$LOGINID   = $_REQUEST['LOGINID'] ?? '';
$dvc_id    = $_REQUEST['dvc_id'] ?? '';

/* -------------------------------
   Build folder paths
-------------------------------- */
$uploaddir = "C:\\wamp64\\www\\".$Folder."\\mobile_image_temp\\temp_".$LOGINID."_".$dvc_id."\\";

if (!is_dir($uploaddir)) {
    mkdir($uploaddir, 0777, true);
    mkdir($uploaddir."\\thumbnail\\", 0777, true);
}

$MobileURLFullSize = $MobileURL . "/mobile_image_temp/temp_".$LOGINID."_".$dvc_id."/";
$MobileURLTnSize   = $MobileURL . "/mobile_image_temp/temp_".$LOGINID."_".$dvc_id."/thumbnail/";

$exportdir   = "C:\\wamp64\\www\\". $Folder ."\\mobile_image_temp\\temp_".$LOGINID."_".$dvc_id."\\";
$exportdirtn = "C:\\wamp64\\www\\". $Folder ."\\mobile_image_temp\\temp_".$LOGINID."_".$dvc_id."\\thumbnail\\";

/* -------------------------------
   CF LABEL HEADERS
-------------------------------- */
$labels = array(
    'ler_det_sign_by' => '',
    'ler_det_sign_by_id' => '',
    'ler_det_sign_by_contact' => ''
);

$sql_label = "
    SELECT column_name, customize_header
    FROM cf_label WITH (NOLOCK)
    WHERE table_name = ?
      AND column_name IN ('ler_det_sign_by','ler_det_sign_by_id','ler_det_sign_by_contact')
      AND language_cd = ?
";
$stmt_label = sqlsrv_query($conn, $sql_label, array('lri_det', 'DEFAULT'));
if ($stmt_label === false) {
    returnError('Error selecting cf_label: ' . print_r(sqlsrv_errors(), true));
}
while ($r = sqlsrv_fetch_array($stmt_label, SQLSRV_FETCH_ASSOC)) {
    $col = trim($r['column_name'] ?? '');
    $lbl = trim($r['customize_header'] ?? '');
    if ($col !== '') {
        $labels[$col] = $lbl;
    }
}
sqlsrv_free_stmt($stmt_label);

/* -------------------------------
   ATTACHMENTS
-------------------------------- */
$counter = 0;

$sql = "
    SELECT RowID, attachment, file_name
    FROM ler_ref WITH (NOLOCK)
    WHERE site_cd = ?
      AND mst_RowID = ?
      AND column2 = 'SIGN'
      AND attachment IS NOT NULL
      AND DATALENGTH(attachment) > 0
      AND mst_RowID IS NOT NULL
      AND file_name NOT LIKE '%xlsx%'
      AND file_name NOT LIKE '%xls%'
    ORDER BY RowID
";

$stmt = sqlsrv_query($conn, $sql, array($site_cd, $mst_rowid));
if ($stmt === false) {
    returnError("Error selecting table (ler_ref): " . print_r(sqlsrv_errors(), true));
}

do {
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {

        $Photo    = $row['attachment'];
        $fileName = $row['file_name'];
        $refRowID = $row['RowID'];

        // Detect mime (fixed: use !== false)
        $mime = null;
        $lower = strtolower($fileName);
        if (strpos($lower, 'jpeg') !== false) $mime = 'image/jpeg';
        else if (strpos($lower, 'jpg') !== false) $mime = 'image/jpg';
        else if (strpos($lower, 'gif') !== false) $mime = 'image/gif';
        else if (strpos($lower, 'png') !== false) $mime = 'image/png';

        $exportFullPathFileName   = $exportdir.$fileName;
        $exportFullPathTNFileName = $exportdirtn.$fileName;

        $publicFullPathFileName   = $MobileURLFullSize.$fileName;
        $publicFullPathTNFileName = $MobileURLTnSize.$fileName;

        // If file exists, rename (keeps original extension handling for .jpg only as your old code)
        if (file_exists($exportFullPathFileName)) {
            $counter++;

            // Safer rename for any extension
            $pathInfo = pathinfo($fileName);
            $base = $pathInfo['filename'] ?? $fileName;
            $ext  = isset($pathInfo['extension']) ? ('.' . $pathInfo['extension']) : '';
            $newname = $base . "_" . $counter . $ext;

            $exportFullPathFileName   = $exportdir.$newname;
            $exportFullPathTNFileName = $exportdirtn.$newname;

            $publicFullPathFileName   = $MobileURLFullSize.$newname;
            $publicFullPathTNFileName = $MobileURLTnSize.$newname;

            $fileName = $newname;
        }

        // Export full-size file
        if ($file = fopen($exportFullPathFileName, "wb")) {
            if (fwrite($file, $Photo) === false) {
                fclose($file);
                returnError("Error Write Files");
            }
            fclose($file);
        } else {
            returnError("Cannot open file for writing: " . $exportFullPathFileName);
        }

        // Thumbnail generation is still commented (same as your original)

        $json_img_link = array();
        $json_img_link['rowid'] = $refRowID;
        $json_img_link['type'] = 'image';
        $json_img_link['file_name'] = $fileName;
        $json_img_link['thumbnail_link'] = $publicFullPathTNFileName;
        $json_img_link['full_size_link'] = $publicFullPathFileName;
        $json_img_link['file_source'] = 'server';

        array_push($json_return, $json_img_link);
    }
} while (sqlsrv_next_result($stmt));

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

// Return response with headers + data
returnData($json_return, $labels);


/* -------------------------------
   FUNCTIONS
-------------------------------- */
function returnData($json, $labels){
    $returnData = array(
        'status' => 'SUCCESS',
        'message' => 'Work order attachment retrieve successfully',
        'cf_label_header' => $labels,
        'data' => $json
    );
    echo json_encode($returnData);
    exit();
}

function returnError($error_message){
    $json = array();

    $returnData = array(
        'status' => 'ERROR',
        'message' => $error_message,
        'data' => $json
    );

    echo json_encode($returnData);
    exit();
}
?>