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

define('UPLOAD_DIR', 'C:\\wamp64\\www\\');
define('MAX_SIZE', 5242880); // 5MB

$response = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $count = $_REQUEST["count"];
    $json = json_decode($_REQUEST["json"]);
    $rowid = $json->data->rowid;
    $site_cd = $json->data->site_cd;
    $EMPID = $json->data->EMPID;
    $EMPNAME = $json->data->EmpName;
    $folder = $json->data->folder;
    $dvc_id = $json->data->dvc_id;

    $uploadDir = UPLOAD_DIR . $folder . "\\temp_" . $dvc_id . "\\";
    createDirectories($uploadDir);

    for ($x = 1; $x <= $count; $x++) {
        $file = $_FILES['file_' . $x];
        $fileType = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $filePath = $uploadDir . basename($file['name']);

        if (!move_uploaded_file($file['tmp_name'], $filePath)) {
            addErrorResponse($response, 0, "move_uploaded_file failed for file (" . $file['name'] . ")");
            continue;
        }

        if (!file_exists($filePath)) {
            addErrorResponse($response, 0, "File not exist (" . $file['name'] . ")");
            continue;
        }

        $fileContent = file_get_contents($filePath);
        $hexData = unpack("H*hex", $fileContent)['hex'];

        switch ($fileType) {
            case 'png':
                processPngFile($filePath, $EMPID, $site_cd, $rowid, $EMPNAME, $hexData, $response);
                break;
            case 'jpg':
            case 'jpeg':
                processJpegFile($filePath, $EMPID, $site_cd, $rowid, $EMPNAME, $hexData, $response);
                break;
            case 'mp4':
            case 'avi':
            case '3gp':
            case 'mov':
            case 'mpeg':
                processVideoFile($filePath, $EMPID, $site_cd, $rowid, $EMPNAME, $hexData, $response);
                break;
            case 'pdf':
                processPdfFile($filePath, $EMPID, $site_cd, $rowid, $EMPNAME, $hexData, $response);
                break;
            default:
                addErrorResponse($response, 0, "Invalid file extension for file (" . $file['name'] . ")");
        }

        unlink($filePath);
    }

    returnData($response, $rowid);
}

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

function processPngFile($filePath, $EMPID, $site_cd, $rowid, $EMPNAME, $hexData, &$response) {
    // Convert PNG to JPG and process similarly to JPEG
    $newFilePath = str_replace(".png", ".jpg", $filePath);
    imagejpeg(imagecreatefrompng($filePath), $newFilePath, 100);
    processJpegFile($newFilePath, $EMPID, $site_cd, $rowid, $EMPNAME, unpack("H*hex", file_get_contents($newFilePath))['hex'], $response);
}

function processJpegFile($filePath, $EMPID, $site_cd, $rowid, $EMPNAME, $hexData, &$response) {
    $chart_id = uniqid();
    $sql = "INSERT INTO wko_ls11 
                (site_cd, mst_RowID, wko_ls11_name, wko_ls11_sts_upd, wko_ls11_category, status, type, file_name, attachment, audit_user, audit_date, column1, column2, column3, column4, column5, chatID) 
            VALUES 
                (?, ?, ?, NULL, 'Image', 'Mobile', NULL, ?, 0x$hexData, ?, GETDATE(), NULL, NULL, NULL, NULL, NULL, ?)";

    $params = [$site_cd, $rowid, $EMPNAME, basename($filePath), $EMPID, $chart_id];
    executeSql($sql, $params, $response);
}

function processVideoFile($filePath, $EMPID, $site_cd, $rowid, $EMPNAME, $hexData, &$response) {
    $chart_id = uniqid();
    $sql = "INSERT INTO wko_ls11 
                (site_cd, mst_RowID, wko_ls11_name, wko_ls11_sts_upd, wko_ls11_category, status, type, file_name, attachment, audit_user, audit_date, column1, column2, column3, column4, column5, chatID) 
            VALUES 
                (?, ?, ?, NULL, 'Image', 'Mobile', NULL, ?, 0x$hexData, ?, GETDATE(), NULL, NULL, NULL, NULL, NULL, ?)";

    $params = [$site_cd, $rowid, $EMPNAME, basename($filePath), $EMPID, $chart_id];
    executeSql($sql, $params, $response);
}

function processPdfFile($filePath, $EMPID, $site_cd, $rowid, $EMPNAME, $hexData, &$response) {
    $chart_id = uniqid();
    $sql = "INSERT INTO wko_ls11 
                (site_cd, mst_RowID, wko_ls11_name, wko_ls11_sts_upd, wko_ls11_category, status, type, file_name, attachment, audit_user, audit_date, column1, column2, column3, column4, column5, chatID) 
            VALUES 
                (?, ?, ?, NULL, 'Image', 'Mobile', NULL, ?, 0x$hexData, ?, GETDATE(), NULL, NULL, NULL, NULL, NULL, ?)";

    $params = [$site_cd, $rowid, $EMPNAME, basename($filePath), $EMPID, $chart_id];
    executeSql($sql, $params, $response);
}

function executeSql($sql, $params, &$response) {
    global $conn;
    $stmt = sqlsrv_query($conn, $sql, $params);

    if (!$stmt) {
        returnError("Error inserting into table (wko_ls11)");
    } else {
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            $response[] = ['rowid' => $row['rowid'], 'action' => "INSERT"];
        }
    }
}

function addErrorResponse(&$response, $rowid, $message) {
    $response[] = ['rowid' => $rowid, 'action' => $message];
}

function returnData($response, $rowid) {
    echo json_encode([
        'status' => 'SUCCESS',
        'message' => 'Attachment Inserted Successfully',
        'rowid' => $rowid,
        'data' => $response
    ]);
    exit();
}

function returnError($error_message) {
    echo json_encode([
        'status' => 'ERROR',
        'message' => $error_message,
        'data' => []
    ]);
    exit();
}
?>
