using Dapper;
using iTextSharp.text.pdf;
using MassTransit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Npgsql;
using RabbitMQ.Client.Framing.Impl;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using WK_KLI_LAPS_COMMONTOOL_Service.App_Data;
using WK_KLI_LAPS_COMMONTOOL_Service.Models;
using static MassTransit.Logging.LogCategoryName;

namespace WK_KLI_LAPS_COMMONTOOL_Service.Controllers.WorkArea
{
    [Route("api/[controller]")]
    [ApiController]
    public class WorkAreaApiController : ControllerBase
    {
        CommonRepository oCommonRepository = new CommonRepository();
        WorkAreaService oWorkAreaService = new WorkAreaService();
        string baseurl = Startup.Configuration.GetValue<string>("AppSettings:serverroot");

        [AllowAnonymous]
        [HttpPost("getCheckout")]
        public IActionResult getCheckout([FromBody] object data)
        {
            try
            {
                var _list = oWorkAreaService.getCheckout(data);
                return Ok(_list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }

        }

        [AllowAnonymous]
        [HttpPost("usrstagemove")]
        public IActionResult usrstagemove([FromBody] lottraninfo data)
        {
            try
            {
                var _list = oWorkAreaService.usrstagemove(data);
                return Ok(_list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }

        }
        [AllowAnonymous]
        [HttpPost("getJobDetails")]
        public IActionResult getJobDetails([FromBody] object data)
        {
            var _list = oWorkAreaService.getJobDetails(data);
            return Ok(_list);
        }
        [AllowAnonymous]
        [HttpPost("getLotDetailsComments")]
        public IActionResult getLotDetailsComments([FromBody] object data)
        {
            var _list = oWorkAreaService.getLotDetailsComments(data);
            return Ok(_list);
        }
        [HttpPost("getLotDetailsOCR")]
        public IActionResult GetLotDetailsOCR([FromBody] JobRequest request)
        {
            if (request == null || request.JobId <= 0)
                return BadRequest("Invalid job ID");
            string serverinfo = string.Empty;

            var resultObj = oWorkAreaService.getLotDetailsOCR(request.JobId);

            // Convert to int safely
            int tranid = 0;
            if (resultObj != null)
            {
                // If resultObj is a list and you want the first item:
                var list = resultObj as IEnumerable<object>;
                if (list != null && list.Any())
                {
                    tranid = Convert.ToInt32(list.First());
                }

                serverinfo = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");


            }
            return Ok(serverinfo);
        }



        [HttpGet("DownloadFile")]


        public async Task<IActionResult> DownloadFile([FromQuery] string path, [FromQuery] string title, [FromQuery] string jobid)
        {
            if (string.IsNullOrWhiteSpace(path))
                return BadRequest("Folder path is required.");

            try
            {
                // ✅ Validate allowed network base path
                string allowedBasePath = @"\\pdynxfs\OEB_xml";
                if (!path.StartsWith(allowedBasePath, StringComparison.OrdinalIgnoreCase))
                    return BadRequest("Access to this path is not allowed.");

                // ✅ Append subfolder if needed
                path = Path.Combine(path, "IN");
                if (!Directory.Exists(path))
                    return NotFound("Folder not found.");

                // ✅ Fallback title
                if (string.IsNullOrWhiteSpace(title))
                    title = "Download";

                var zipFileName = $"{title}.zip";

                // ✅ Use application temp folder instead of system temp
                string tempBase = Path.Combine(System.AppContext.BaseDirectory, "TempZips");
                Directory.CreateDirectory(tempBase); // ensure exists
                var tempZipPath = Path.Combine(tempBase, zipFileName);

                // ✅ Remove existing temp ZIP (if any)
                if (System.IO.File.Exists(tempZipPath))
                    System.IO.File.Delete(tempZipPath);

                // ✅ Impersonate with granted folder permission
                using (var permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                    await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
                    {
                        // Step 1: Create ZIP (no compression = faster)
                        ZipFile.CreateFromDirectory(path, tempZipPath, CompressionLevel.NoCompression, includeBaseDirectory: true);
                        await Task.CompletedTask; // keep async signature clean
                    });
                }

                // Step 2: Stream ZIP asynchronously to response
                Response.ContentType = "application/zip";
                Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{zipFileName}\"");

                await using (var stream = new FileStream(tempZipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    await stream.CopyToAsync(Response.Body);
                }

                // Step 3: Delete temporary ZIP
                try
                {
                    System.IO.File.Delete(tempZipPath);
                }
                catch
                {
                    // ignore file delete issues
                }

                return new EmptyResult(); // response already written
            }
            catch (Exception ex)
            {
                // ✅ Log the error
                oCommonRepository.addlog(new
                {
                    errormessage = "Error: " + ex.Message,
                    createdby = 0,
                    controller = "WorkAreaApi: DownloadFile"
                }, "errorlog");

                return StatusCode(500, $"Error while downloading folder: {ex.Message}");
            }
        }



        [HttpPost]
        public object PostValidateQA(Fields fields)
        {
            //DBContext db = new DBContext();
            //db.CheckLogin();
            var json = new List<object>();
            //try
            //{
            //    BLDatamanipulation db_ = new BLDatamanipulation();
            //    DataTable svrpath = db_.GetDataTable(db, string.Format("select * from usr_server_path_info({0},'serverinfo')", fields.transid), null);
            //    string serverpath = svrpath.Rows[0]["serverpath"].ToString();
            //    serverpath = "\\\\" + serverpath.Replace("/", "\\");
            //    string serveroutpath = System.IO.Path.Combine(serverpath, "OUT");
            //    string serverinpath = System.IO.Path.Combine(serverpath, "IN");
            //    var ext = new List<string> { ".pdf", ".xml" };


            //    if (Directory.Exists(serveroutpath) && Directory.Exists(serverinpath))
            //    {
            //        List<string> infile = Directory.GetFiles(serverinpath, "*.*", SearchOption.AllDirectories)
            //             .Where(s => ext.Contains(Path.GetExtension(s).ToLower())).Select(x => Path.GetFileName(x)).ToList();
            //        List<string> outfile = Directory.GetFiles(serveroutpath, "*.*", SearchOption.AllDirectories)
            //            .Where(s => ext.Contains(Path.GetExtension(s).ToLower())).Select(x => Path.GetFileName(x)).ToList();
            //        List<string> exept = infile.Except(outfile).ToList();
            //        if (exept.Count > 0)
            //        {
            //            json.Add(JObject.Parse("{\"success\":false}"));
            //            json.Add(JObject.Parse("{\"log\":\"Please completed QA process then proceed.\"}"));
            //        }
            //        else
            //        {
            //            if (File.Exists(Path.Combine(serveroutpath, "error.txt")))
            //            {
            //                json.Add(JObject.Parse("{\"success\":false}"));
            //                json.Add(JObject.Parse("{\"log\":\"Please clear the validation error then proceed.\"}"));
            //            }
            //            else
            //                json.Add(JObject.Parse("{\"success\":true}"));
            //        }

            //    }
            //    else { json.Add(JObject.Parse("{\"success\":false}")); json.Add(JObject.Parse("{\"log\":\"Please completed QA process then proceed.\"}")); }

            //}
            //catch (Exception ex)
            //{

            //    json.Add(JObject.Parse("{\"success\":false}"));
            //    json.Add(JObject.Parse("{\"log\":\"Process failed. " + ex.Message + "\"}"));

            //}
            return json;
        }

        //raji

        [Authorize]
        [HttpPost("savefilechecker")]
        public object savefilechecker()
        {
            bool dirvalidate = false;
            bool filevalidate = false;
            string message = "";
            try
            {
                //var json =[];

                var httpRequest = HttpContext.Request.Form;
                string filepath = string.Empty;
                string actualdirectory = string.Empty;
                string filepath_name = string.Empty;
                string lottitles = string.Empty;
                string jobtitle = string.Empty;
                string dirName = string.Empty;
                //int charIndex = 0;
                string retmsg = string.Empty;
                string jobid = Request.Form["jobid"].ToString();
                string kvpmode = Request.Form["kvpmode"].ToString();
                string kvpvalue = Request.Form["kvpvalue"].ToString();
                string tranid = Request.Form["tranid"].ToString();
                string serverinfo = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
                string serverpath = Path.Combine(serverinfo, "OUT");
                string templatefileserverpath = string.Empty;
                var titleqry = oWorkAreaService.spfiletypevalidation(tranid.ToString(), jobid);
                var titleqry_jsonList = new List<string>();
                if (titleqry != null)
                {
                    var titleqry_filetype = JsonConvert.DeserializeObject<object>(titleqry.ToString());
                    JArray titleqry_a_filetype = JArray.Parse(titleqry_filetype.ToString());
                    lottitles = titleqry_a_filetype[0]["titlecur"].ToString();
                    jobtitle = titleqry_a_filetype[0]["jobtitle"].ToString();
                    lottitles = lottitles.Replace("-img", "");
                    lottitles = lottitles.Replace("-txt", "");
                }
                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                    {
                        if (httpRequest.Files.Count > 0)
                        {
                            if (!Directory.Exists(serverpath))
                            {
                                Directory.CreateDirectory(serverpath);
                            }
                            if (!string.IsNullOrEmpty(kvpmode) && !string.IsNullOrEmpty(kvpvalue))
                            {

                                if (kvpmode == "file")
                                {
                                    filepath = Directory.GetDirectories(serverpath, lottitles, SearchOption.TopDirectoryOnly).FirstOrDefault();
                                    if (!string.IsNullOrEmpty(filepath) && Directory.Exists(filepath))
                                    {
                                        dirvalidate = true;
                                    }
                                    else
                                    {
                                        //dirvalidate = true;
                                        if (!Directory.Exists(Path.Combine(serverpath, lottitles)))
                                        {
                                            Directory.CreateDirectory(Path.Combine(serverpath, lottitles));
                                            dirvalidate = true;
                                        }
                                    }
                                    for (int i = 0; i < httpRequest.Files.Count; i++)
                                    {
                                        var outfile = httpRequest.Files[i];
                                        dirName = "";
                                        dirName = Path.GetDirectoryName(outfile.FileName);
                                        if (dirName == "")
                                        {
                                            filepath_name = Path.GetFileNameWithoutExtension(outfile.FileName);

                                            if (kvpvalue == "_Redacted")
                                            {
                                                filevalidate = true;
                                                if (!filepath_name.ToString().EndsWith(kvpvalue) || !filepath_name.ToLower().Contains(lottitles.ToLower()))
                                                {
                                                    filevalidate = false;
                                                }

                                            }
                                            else if (filepath_name.ToString().EndsWith(kvpvalue))
                                            {
                                                filevalidate = true;
                                                break;
                                            }

                                        }
                                    }
                                }
                                else
                                {
                                    filevalidate = true;
                                    actualdirectory = string.Empty;
                                    actualdirectory = Path.Combine(serverpath, jobtitle + kvpvalue);
                                    string visf_folder = string.Empty;
                                    string[] extensionFilters = new string[] { kvpvalue };
                                    visf_folder = Directory.GetDirectories(serverpath, "*.*", SearchOption.TopDirectoryOnly)
        .Where(filename => extensionFilters.Any(x =>
        filename.EndsWith(x, StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
                                    if (!string.IsNullOrEmpty(visf_folder))
                                    {
                                        dirvalidate = true;
                                    }
                                    else
                                    {

                                        if (!Directory.Exists(actualdirectory))
                                        {
                                            Directory.CreateDirectory(actualdirectory);
                                            dirvalidate = true;
                                        }
                                    }
                                }
                                //}
                                if (kvpmode == "file")
                                {
                                    if (filevalidate == false)
                                    {
                                        message = "" + kvpvalue + " file missing please check";
                                    }
                                    else
                                    {
                                        if (dirvalidate == false)
                                        {
                                            message = "file is not placed properly in lotname against job";
                                        }
                                    }
                                }
                                else
                                {
                                    if (dirvalidate == false)
                                    {
                                        message = "" + kvpvalue + " folder missing against job.Please Check";
                                    }
                                }

                            }

                            //else
                            //{
                            //    message = "Unknown stage processor.please check";
                            //    var json = new { dirresult = dirvalidate, fileresults = filevalidate, Message = message };
                            //    return json;
                            //}

                        }
                    });

                }
                var json1 = new { dirresult = dirvalidate, fileresults = filevalidate, Message = message };
                return json1;

            }
            catch (Exception ex)
            {
                message = ex.Message;
                dirvalidate = false;
                filevalidate = false;
                var json = new { dirresult = dirvalidate, fileresults = filevalidate, Message = message };
                return json;
            }

        }

        //rajii


        [Authorize]
        [HttpPost]
        public object PostUpdatelot_transaction(Fields fields)
        {
            //DBContext db = new DBContext();
            //db.CheckLogin();

            //long transactionid = fields.transid;
            //string option = fields.option;
            //string comment = fields.comment;

            //if (fields.fields != "null")
            //{
            //    BLDatamanipulation db_ = new BLDatamanipulation();
            //    List<NpgsqlParameter> parms = new List<NpgsqlParameter>();
            //    db_.InsertQuery(db, "update lot_master set lotmastermetafields = '" + fields.fields + "' where lotid in (select a.lotid from lot_transaction a where a.transactionid = " + fields.transid + ")", parms);
            //    db_.InsertQuery(db, "update lot_transaction set lotmetafields = '" + fields.fields + "' where transactionid = " + fields.transid + "", parms);
            //}

            //lot_tran_info lotinfo = new lot_tran_info();
            //lotinfo.p_tranid = transactionid.ToString();
            //lotinfo.p_userid = (HttpContext.Current.Session["UserID"] as string);
            //lotinfo.p_option = option;
            //lotinfo.p_holdreason = comment;
            //if (option == "checkout")
            //    Checkout_transaction(lotinfo);
            //else if (option == "hold")
            //    getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "I", "hold", "0", lotinfo.p_holdreason);
            //else if (option == "checkin")
            //    getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "P", "hold", "0", lotinfo.p_holdreason);
            return "Done";


        }
        public void TriggerMail(string tranid, string ordernumber, string nxttranid)
        {
            try
            {
                if (ordernumber == "1")
                {
                    System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_PM?tranid=", tranid, "&sflag=", "1")));
                    System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_Ack?tranid=", tranid, "&sflag=", "2")));
                }
                else if (ordernumber == "2")
                {
                    System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_SignOff?tranid=", nxttranid, "&jobworkflowid=", 0, "&sflag=", "2", "&curtranid=", tranid)));
                }
            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = "Error: " + ex.Message,
                    createdby = 0,
                    controller = "UploaderApi: Downloader"
                };
                oCommonRepository.addlog(data_input, "errorlog");
            }
        }
        public void SendMailRequest(string apiUrl)
        {
            try
            {
                HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
                authRequest.ContentType = "application/xml";
                authRequest.Method = "POST";
                authRequest.ContentLength = 0;
                WebResponse authResponseTwitter = authRequest.GetResponse();
            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = "Error: " + ex.Message,
                    createdby = 0,
                    controller = "UploaderApi: Downloader"
                };
                oCommonRepository.addlog(data_input, "errorlog");
            }
        }

        [HttpPost]
        public object getbronsdetails(string jobid)
        {
            //DBContext db = new DBContext();
            //db.CheckLogin();
            //string qry = "select * from getbronsbyid(@p_job) as json";
            //var data = db.Database.SqlQuery<jsonvalue>(qry, new Npgsql.NpgsqlParameter { ParameterName = "@p_job", Value = Convert.ToInt64(jobid) }).ToList();
            var json = new List<object>();
            //foreach (var item in data)
            //{
            //    json.Add(JObject.Parse(item.json));
            //}
            return json;
        }

        [HttpPost]
        public object isdeleted(string jobid, string lotid)
        {
            //DBContext db = new DBContext();
            //db.CheckLogin();


            //var menudetails = db.Database.SqlQuery<jsonvalue>("select json_build_object('articalstatus', wa.article_status)as json from wkb_articleinfo wa inner join lot_master lm on lm.jobid=wa.jobid and lm.lotid=wa.lotid where lm.jobid=@jobid and lm.lotid=@lotid",
            //      new Npgsql.NpgsqlParameter { ParameterName = "@jobid", Value = jobid }, new Npgsql.NpgsqlParameter { ParameterName = "@lotid", Value = lotid }).ToList();
            var json = new List<object>();
            //foreach (var item in menudetails)
            //{
            //    json.Add(JObject.Parse(item.json));
            //}
            return json;

        }
        [HttpPost("test")]
        public object test()
        {
            return "done";
        }

        //[HttpPost]
        //public object getAllbronsdetails(string jobid_BUP)
        //{
        //    DBContext db = new DBContext();
        //    db.CheckLogin();
        //    string qry = "select * from getbronsNewbyid(@p_job) as json";
        //    var data = db.Database.SqlQuery<jsonvalue>(qry, new Npgsql.NpgsqlParameter { ParameterName = "@p_job", Value = Convert.ToInt64(jobid_BUP) }
        //       ).ToList();

        //    return data;
        //}




        //[HttpPost]
        //public object loadweblink(string jobid_o, long tranid)
        //{
        //    DBContext db = new DBContext();
        //    db.CheckLogin();
        //    var json = new List<object>();
        //    string jobid = getjobid(tranid);
        //    BLDatamanipulation db12 = new BLDatamanipulation();
        //    DataTable dt2 = db12.GetDataTable(db, "select isignoreable,websiteurl from wkb_job_details a where a.jobid = " + jobid + "", null);
        //    if (dt2.Rows.Count > 0)
        //    {
        //        string isignore = dt2.Rows[0]["isignoreable"].ToString().ToLower();
        //        string websiteurl = dt2.Rows[0]["websiteurl"].ToString().ToLower();
        //        json.Add(JObject.Parse("{\"isignoreable\":'" + isignore + "',\"websiteurl\":'" + websiteurl + "'}"));
        //    }
        //    return json;
        //}

        public string getjobid(long p_tranid)
        {
            try
            {
                //DataTable svrpath = getdatatable("usr_server_path_info", new List<Npgsql.NpgsqlParameter>(){ new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = p_tranid },
                //       new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "serverinfo" }});

                return "";// svrpath.Rows[0]["jobid"].ToString();
            }
            catch (Exception ex)
            {
                return string.Join("", "Error : ", ex.Message.ToString());
            }
        }



        //[HttpPost]
        //public object Checkout_transaction(lot_tran_info lotinfo)
        //{
        //    var trans_id = lotinfo.p_tranid;
        //    var checkout = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_only", "0", lotinfo.p_holdreason);
        //    if (checkout.Count > 0)
        //    {
        //        foreach (var item in checkout)
        //        {
        //            JobWorkflow_ obj = JsonConvert.DeserializeObject<JobWorkflow_>(item.json);
        //            List<StageData> lst = new List<StageData>();

        //            //******************* Get Next Stage Details **************
        //            lst = getNextStageDetails(obj.jobid, obj.jobworkflowid);
        //            //*******************

        //            List<StageData> newList = lst
        //             .Where(m => m.CURRENT == obj.jobworkflowid)
        //             .ToList();

        //            //******************* To Check Next Stage 
        //            foreach (var items in newList)
        //            {
        //                var next_workflow_id = "";
        //                if (items.NEXT != null)
        //                    next_workflow_id = items.NEXT;
        //                else if (items.PARALLEL != null)
        //                    next_workflow_id = items.PARALLEL;
        //                else if (items.MOVEBACKNO != null)
        //                    next_workflow_id = items.MOVEBACKNO;
        //                else if (items.MOVEBACKYES != null)
        //                    next_workflow_id = items.MOVEBACKYES;

        //                //*******************
        //                if (next_workflow_id != null)
        //                {
        //                    next_workflow_id = next_workflow_id.Trim();
        //                    List<StageData> checkParallalList = lst
        //                           .Where(m => m.NEXT == next_workflow_id || m.PARALLEL == next_workflow_id || m.MOVEBACKYES == next_workflow_id || m.MOVEBACKNO == next_workflow_id)
        //                           .ToList();

        //                    if (checkParallalList.Count > 0)
        //                    {
        //                        var if_check_parallel = true;
        //                        //***************** Only One Next Stage
        //                        if (checkParallalList.Count == 1)
        //                        {
        //                            var checkout_next = getCheckout(trans_id, lotinfo.p_userid, "R", "checkout_next", next_workflow_id, lotinfo.p_holdreason);
        //                            var json = new List<transout>();
        //                            foreach (var checkout_next_item in checkout_next)
        //                                json.Add(JsonConvert.DeserializeObject<transout>(checkout_next_item.json));
        //                            sendmail(lotinfo, json[0].p_tranid, obj.jobworkflowid);
        //                        }
        //                        //***************** More than One Next Stage
        //                        else
        //                        {
        //                            foreach (var item_checkParallalList in checkParallalList)
        //                            {
        //                                //***************** To Check All Parallal stage are completed or put Wait
        //                                var checkout_check_parallel = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_parallel_check", item_checkParallalList.CURRENT);
        //                                if (checkout_check_parallel.Count > 0)
        //                                {
        //                                    foreach (var parallel_item in checkout_check_parallel)
        //                                    {
        //                                        JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.json);
        //                                        if (parallel_item_obj.lotstatus == "P" || parallel_item_obj.lotstatus == "R" || parallel_item_obj.lotstatus == "W" || parallel_item_obj.lotstatus == "" || parallel_item_obj.lotstatus == null)
        //                                        {
        //                                            if_check_parallel = false;
        //                                        }
        //                                    }
        //                                }
        //                            }
        //                            if (if_check_parallel == true)
        //                            {
        //                                var checkout_next = getCheckout(trans_id, lotinfo.p_userid, "R", "checkout_next", next_workflow_id, lotinfo.p_holdreason);
        //                                var json = new List<transout>();
        //                                foreach (var checkout_next_item in checkout_next)
        //                                    json.Add(JsonConvert.DeserializeObject<transout>(checkout_next_item.json));
        //                                sendmail(lotinfo, json[0].p_tranid, obj.jobworkflowid.ToString());
        //                            }
        //                            else
        //                            { var checkout_next = getCheckout(trans_id, lotinfo.p_userid, "W", "checkout_next", next_workflow_id, lotinfo.p_holdreason); }
        //                        }
        //                    }
        //                }
        //                //*******************
        //            }
        //        }
        //    }
        //    return "Done";
        //}
        //public List<jsonvalue> getCheckout(string trans_id, string p_userid, string status, string option, string jobworkflowid, string p_comments = "")
        //{
        //    DBContext db1 = new DBContext();
        //    return db1.Database.SqlQuery<jsonvalue>("select * from usr_lot_tran_update_v2(@p_tranid,@p_userid,@p_status,@p_option,@jobworkflowid,@p_comments) as json",
        //            new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = trans_id },
        //            new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = p_userid },
        //            new Npgsql.NpgsqlParameter { ParameterName = "@p_status", Value = status },
        //            new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = option },
        //            new Npgsql.NpgsqlParameter { ParameterName = "@p_comments", Value = p_comments },
        //            new Npgsql.NpgsqlParameter { ParameterName = "@jobworkflowid", Value = jobworkflowid }).ToList();

        //    //List<Npgsql.NpgsqlParameter> Parmtr = new List<NpgsqlParameter>();
        //    //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = trans_id });
        //    //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = p_userid });
        //    //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_status", Value = status });
        //    //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = option });
        //    //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@jobworkflowid", Value = jobworkflowid });
        //    //string json = db.getdataJson("usr_lot_tran_update_v2", Parmtr);
        //    //return Newtonsoft.Json.JsonConvert.DeserializeObject<List<JobWorkflow_>>(string.Join("", json));
        //}
        public List<StageData> getNextStageDetails(string jobid, string jobworkflowid)
        {
            //BLDatamanipulation db = new BLDatamanipulation();
            //DBContext dbcontext_ = new DBContext();
            //string qry1 = @"select concat((case when jm.nextstage is not null and jm.movebackstage is null
            //        then
            //        concat('CURRENT:',cast(jm.jobworkflowid as text),',NEXT:',cast(nextjm.jobworkflowid as text)
            //        ,case when (select count(1) from job_workflow_master where parallelstage=jm.nextstage)>0
            //        then (select string_agg(concat(chr(10),',CURRENT:',cast(jm.jobworkflowid as text),',PARALLEL:',cast(jobWorkflowID as text)), '') from job_workflow_master where parallelstage=jm.nextstage)
            //        else '' end)
            //        else concat('CURRENT:',cast(jm.jobworkflowid as text)) end )
            //        , (case when backjm.jobworkflowid is null then ''         else concat(chr(10),',MOVEBACKYES:',cast(backjm.jobworkflowid  as text),chr(10),',MOVEBACKNO:',cast(nextjm.jobworkflowid  as text),
            //         case when (select count(1) from job_workflow_master where parallelstage=nextjm.jobworkflowid)>0 then
            //         (select concat(chr(10),'CURRENT:',cast(jm.jobworkflowid as text),'MOVEBACKNO:',cast(jobWorkflowID as text)) from job_workflow_master where parallelstage=nextjm.jobworkflowid) else '' end)  end)) as Flowchart
            //        from job_workflow_master jm
            //        inner join stage_type_master st on st.stagetypeid=jm.stage_type
            //        left join job_workflow_master nextjm on nextjm.jobworkflowid =jm.nextstage
            //        left join job_workflow_master backjm on backjm.jobworkflowid =jm.movebackstage
            //        where jm.jobid=" + jobid + " and jm.active=1  order by jm.stageorder";

            List<StageData> lst = new List<StageData>();
            //System.Data.DataTable data1 = db.GetDataTable(dbcontext_, qry1, null);
            //if (data1.Rows.Count > 0)
            //{
            //    for (int i = 0; i <= data1.Rows.Count - 1; i++)
            //    {
            //        var splite = data1.Rows[i][0].ToString().Split(',');
            //        if (splite.Length > 0)
            //        {
            //            var current = "";
            //            foreach (string word in splite)
            //            {
            //                var stemp = ""; StageData st = new StageData();
            //                var innersplite = word.ToString().Split(':');
            //                for (int j = 0; j <= innersplite.Length; j++)
            //                {
            //                    if (innersplite[0] == "CURRENT")
            //                        current = innersplite[1].Trim();
            //                }
            //                for (int j = 0; j <= innersplite.Length; j++)
            //                {
            //                    st.CURRENT = current;
            //                    if (innersplite[0] == "CURRENT")
            //                        stemp = "CURRENT";
            //                    else if (innersplite[0] == "NEXT")
            //                        st.NEXT = innersplite[1].Trim();
            //                    else if (innersplite[0] == "PARALLEL")
            //                        st.PARALLEL = innersplite[1].Trim();
            //                    else if (innersplite[0] == "MOVEBACKNO")
            //                        st.MOVEBACKNO = innersplite[1].Trim();
            //                    else if (innersplite[0] == "MOVEBACKYES")
            //                        st.MOVEBACKYES = innersplite[1].Trim();
            //                }
            //                if (stemp != "CURRENT")
            //                    lst.Add(st);
            //            }
            //        }
            //    }
            //}
            return lst;
        }
        public void sendmail(lot_tran_info lotinfo, string nexttranval, string jobworkflowid)
        {
            //  (HttpContext.Current.Session["UserID"] as string)
            long userId_t = Convert.ToInt64("4"); // need to add logged in userid
            RabbitMq sendmsg = new RabbitMq();
            sendmsg.SendMqMail(lotinfo.p_tranid.ToString(), jobworkflowid.ToString(), "2", nexttranval.ToString(), userId_t.ToString());

            //var JobMetaFields = GetJobMetaData(nexttranval.ToString(), lotinfo.p_tranid.ToString(), jobworkflowid);
            //Postmail_SignOff(nexttranval, jobworkflowid, "", lotinfo.p_tranid.ToString(), JobMetaFields);

            //TriggerMail(lotinfo.p_tranid.ToString(), "2", nexttranval);
            //System.Threading.Thread.Sleep(100);
            //TriggerMail(lotinfo.p_tranid.ToString(), "1", (HttpContext.Current.Session["UserID"] as string));
        }



        public List<jobmetafields> GetJobMetaData(string tranid, string completedtranid, string jobworkflowid)
        {
            //DBContext db = new DBContext();
            //BLDatamanipulation db1 = new BLDatamanipulation();
            var finalout = new List<jobmetafields>();
            //var workflowid = "";
            //var completed_workflowid = ""; var job_id = "";
            //DataTable dt = db1.GetDataTable(db, "select wfdid,jobid from job_workflow_master a where a.jobworkflowid = " + jobworkflowid + "", null);
            //if (dt.Rows.Count > 0)
            //{
            //    completed_workflowid = dt.Rows[0]["wfdid"].ToString();
            //    job_id = dt.Rows[0]["jobid"].ToString();
            //}

            //var str = "select b.jobmetafields as jobworkflow_metafields,b.wfdid,c.lotmastermetafields as lot_metafields from lot_transaction a left outer join job_workflow_master b on a.jobworkflowid = b.jobworkflowid left outer join lot_master c on c.lotid = a.lotid where a.transactionid = @tranid";
            //var jobmeta = db.Database.SqlQuery<lot_tran_metafields>(str, new Npgsql.NpgsqlParameter { ParameterName = "@tranid", Value = tranid }).ToList();
            //if (jobmeta.Count > 0)
            //{
            //    //jobworkflow_metafields
            //    var jobworkflow_metafields = new List<jobmetafields>();
            //    var lotmastermetafields = new List<jobmetafields>();

            //    foreach (var item in jobmeta)
            //    {
            //        if (item.jobworkflow_metafields != null)
            //        {
            //            dynamic json = JsonConvert.DeserializeObject(item.jobworkflow_metafields);
            //            workflowid = item.wfdid.ToString();
            //            for (int i = 0; i < json.Count; i++)
            //            {
            //                var jdata = new jobmetafields();
            //                foreach (var s in json[i])
            //                {
            //                    if (s.Name == "name")
            //                        jdata.name = string.Join(",", s);
            //                    else if (s.Name == "type")
            //                        jdata.type = string.Join(",", s);
            //                    else if (s.Name == "value")
            //                        jdata.value = string.Join(",", s);
            //                    else if (s.Name == "workflowdid")
            //                        jdata.workflowdid = string.Join(",", s);
            //                    else if (s.Name == "label")
            //                        jdata.label = string.Join(",", s);
            //                }
            //                jobworkflow_metafields.Add(jdata);
            //            }
            //            //lotmastermetafields
            //            dynamic json_ = JsonConvert.DeserializeObject(item.lot_metafields);
            //            for (int i = 0; i < json_.Count; i++)
            //            {
            //                var jdata = new jobmetafields();
            //                foreach (var s in json_[i])
            //                {
            //                    if (s.Name == "name")
            //                        jdata.name = string.Join(",", s);
            //                    else if (s.Name == "type")
            //                        jdata.type = string.Join(",", s);
            //                    else if (s.Name == "value")
            //                        jdata.value = string.Join(",", s);
            //                    else if (s.Name == "workflowdid")
            //                        jdata.workflowdid = string.Join(",", s);
            //                    else if (s.Name == "label")
            //                        jdata.label = string.Join(",", s);
            //                }
            //                lotmastermetafields.Add(jdata);
            //            }
            //        }
            //    }

            //    var completed_field = (from job in jobworkflow_metafields
            //                           join lot in lotmastermetafields on new { job.workflowdid, job.name } equals new { lot.workflowdid, lot.name } //where lot.workflowdid == completed_workflowid
            //                           select new
            //                           {
            //                               lot.name,
            //                               lot.type,
            //                               job.label,
            //                               lot.workflowdid,
            //                               lot.value,
            //                               lot.status
            //                           }).ToList();

            //    var current_field = (from job in jobworkflow_metafields
            //                         where job.workflowdid == workflowid
            //                         select new
            //                         {
            //                             job.name,
            //                             job.type,
            //                             job.label,
            //                             job.workflowdid,
            //                             job.value,
            //                             job.status
            //                         }).ToList();

            //    foreach (var item in completed_field)
            //    {
            //        var stemp = new jobmetafields();
            //        stemp.name = item.name;
            //        stemp.type = item.type;
            //        stemp.label = item.label.Replace("$$JobNo", job_id);
            //        stemp.workflowdid = item.workflowdid;
            //        stemp.value = item.value;
            //        stemp.status = "Completed";
            //        finalout.Add(stemp);
            //    }
            //    foreach (var item in current_field)
            //    {
            //        var stemp = new jobmetafields();
            //        stemp.name = item.name;
            //        stemp.type = item.type;
            //        stemp.label = item.label;
            //        stemp.workflowdid = item.workflowdid;
            //        stemp.value = item.value;
            //        stemp.status = "Current";
            //        finalout.Add(stemp);
            //    }

            //}
            return finalout;
        }
        private void CreateZip(string directoryPathToZip, string outputZipFileName)
        {
            //try
            //{
            //    if (File.Exists(outputZipFileName))
            //        File.Delete(outputZipFileName);
            //    using (ZipFile outputZip = new ZipFile(outputZipFileName))
            //    {
            //        outputZip.AddDirectory(directoryPathToZip);
            //        outputZip.Save();
            //    }
            //}
            //catch (Exception ex)
            //{ }

        }

        [Authorize]
        [HttpPost("saveOutputFile")]
        public object saveOutputFile()
        {
            try
            {
                var httpRequest = HttpContext.Request.Form;
                string filepath = string.Empty;
                string dirName = string.Empty;
                int charIndex = 0;
                string lottitles = string.Empty;
                string jobtitle = string.Empty;
                string filepath_name = string.Empty;
                string projectsubtitle = string.Empty;
                // string currentstagename = string.Empty;
                string retmsg = string.Empty;
                bool lottitle_ = false;
                string jobid = Request.Form["jobid"].ToString();
                string tranid = Request.Form["tranid"].ToString();
                string pdid = Request.Form["pdid"].ToString();
                string kvpmode = Request.Form["kvpmode"].ToString();
                string kvpvalue = Request.Form["kvpvalue"].ToString();
                string fileID = Request.Form["fileID"].ToString();
                string totalchunk = Request.Form["totalChunks"].ToString();
                string filename = Request.Form["filename"].ToString();
                string currentstagename = Request.Form["currentstagename"].ToString();
                string merged_lot = string.Empty;
                string templatefileserverpath = string.Empty;
                var titleqry = oWorkAreaService.spfiletypevalidation(tranid.ToString(), jobid);
                var titleqry_jsonList = new List<string>();

                if (currentstagename == "OCR1")
                {

                    //if (file == null || file.Length == 0)
                    //    return BadRequest("No file uploaded.");
                    // Read PDF bytes directly from the uploaded file
                    var file = HttpContext.Request.Form.Files.FirstOrDefault();
                    if (file == null || file.Length == 0)
                        return BadRequest("No file uploaded.");

                    // ✅ Check file extension
                    if (!file.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
                        return BadRequest("Only PDF files are supported.");

                    try
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            file.CopyTo(memoryStream);
                            memoryStream.Position = 0; // ✅ Reset stream before reading

                            // ✅ Validate PDF structure using iTextSharp
                            using (PdfReader reader = new PdfReader(memoryStream))
                            {
                                Dictionary<string, string> info = reader.Info;

                                string producer = info.ContainsKey("Producer") ? info["Producer"] : "Not available";
                                string creator = info.ContainsKey("Creator") ? info["Creator"] : "Not available";

                                // ✅ Check if it’s ABBYY FineReader
                                if ((producer?.IndexOf("ABBYY", StringComparison.OrdinalIgnoreCase) >= 0) ||
                                    (creator?.IndexOf("ABBYY", StringComparison.OrdinalIgnoreCase) >= 0))
                                {
                                    return Ok(new
                                    {
                                        Message = "Valid PDF. Created using ABBYY FineReader.",
                                        Producer = producer,
                                        Creator = creator
                                    });
                                }
                                else
                                {
                                    return BadRequest(new
                                    {
                                        Message = "Invalid PDF. Not created using ABBYY FineReader.",
                                        Producer = producer,
                                        Creator = creator
                                    });
                                }
                            }
                        }
                    }
                    catch (iTextSharp.text.exceptions.InvalidPdfException ex)
                    {
                        // 🚫 Handle “PDF signature not found” case
                        return BadRequest("Uploaded file is not a valid PDF or is corrupted.");
                    }
                    catch (Exception ex)
                    {
                        // 🧩 Handle other unexpected errors
                        return StatusCode(500, "An error occurred while validating the file: " + ex.Message);
                    }

                }

                if (titleqry != null)
                {
                    var titleqry_filetype = JsonConvert.DeserializeObject<object>(titleqry.ToString());
                    JArray titleqry_a_filetype = JArray.Parse(titleqry_filetype.ToString());
                    lottitles = titleqry_a_filetype[0]["titlecur"].ToString();
                    merged_lot = titleqry_a_filetype[0]["merged_lot"].ToString();
                    jobtitle = titleqry_a_filetype[0]["jobtitle"].ToString();
                    projectsubtitle = titleqry_a_filetype[0]["project_subtitle"].ToString();
                }

                //if (httpRequest.Files.Count > 0)
                // {
                string serverinfo = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
                string serverinpath = Path.Combine(serverinfo, "IN");
                string serverpath = Path.Combine(serverinfo, "OUT");
                var filetype = oWorkAreaService.getFileTypeOutput(tranid);
                var jsonList = new List<string>();
                var uploadExtentionList = new List<string>();
                string resultList = string.Empty;
                if (filetype != null)
                {
                    var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
                    JArray a_filetype = JArray.Parse(i_filetype.ToString());
                    foreach (var a in a_filetype)
                    {
                        JObject obj_filetype = JObject.Parse(a.ToString());
                        jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
                    }
                }

                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                    {
                        if (!Directory.Exists(serverpath))
                        {
                            Directory.CreateDirectory(serverpath);
                        }

                        string finalFilePath = Path.Combine(serverpath, filename);
                        string chunkFolder = Path.Combine("TempUploads", tranid.ToString());
                        using (var finalStream = new FileStream(finalFilePath, FileMode.Create))
                        {
                            for (int i = 0; i < Convert.ToInt64(totalchunk); i++)
                            {
                                string partPath = Path.Combine(chunkFolder, $"{i}.part");
                                using (var partStream = new FileStream(partPath, FileMode.Open))
                                {
                                    partStream.CopyTo(finalStream);
                                }
                            }
                        }

                        Directory.Delete(chunkFolder, true);
                    });
                }

                /*if (jsonList.Count != 0 && jsonList[0].ToString() != ".*")
                {
                    for (int i = 0; i < httpRequest.Files.Count; i++)
                    {
                        var outfile = httpRequest.Files[i];
                        uploadExtentionList.Add(Path.GetExtension(outfile.FileName));
                    }
                    //var jsonlist_filter = jsonList.Except(uploadExtentionList).ToArray();
                    var extentionlist_filter = uploadExtentionList.Except(jsonList).ToArray();
                    for (int i = 0; i < extentionlist_filter.Length; i++)
                    {
                        resultList = string.Concat(resultList, extentionlist_filter[i], ",");
                    }
                    if (!string.IsNullOrEmpty(resultList))
                    {
                        return Ok("Extra files with extension '" + resultList.TrimEnd(',') + "' are not allowed kindly remove it and then proceed.");
                    }
                }*/
                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                    {
                        // using (ServerInfo.GrantFolderPermission imp = new ServerInfo.GrantFolderPermission(jobid))
                        //  {
                        if (!Directory.Exists(serverpath))
                        {
                            Directory.CreateDirectory(serverpath);
                        }
                        var curr_stageid = oWorkAreaService.getCurrentStage(tranid);
                        string current_stageid = "";
                        if (curr_stageid != null)
                        {
                            var i_curr_stageid = JsonConvert.DeserializeObject<object>(curr_stageid.ToString());
                            JArray a_curr_stageid = JArray.Parse(i_curr_stageid.ToString());
                            JObject obj_curr_stageid = JObject.Parse(a_curr_stageid[0].ToString());
                            current_stageid = obj_curr_stageid["stageid"].ToString();
                        }
                        if (string.IsNullOrEmpty(kvpmode) && string.IsNullOrEmpty(kvpvalue))
                        {
                            for (int i = 0; i < httpRequest.Files.Count; i++)
                            {
                                var outfile = httpRequest.Files[i];
                                dirName = Path.GetDirectoryName(outfile.FileName);

                                if (jsonList.Count > 0)
                                {

                                    if (jsonList.Count == 1 && jsonList[0].ToString() == ".*")
                                    {
                                        if (dirName.Contains("\\"))
                                        {
                                            charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
                                            dirName = dirName.Substring(charIndex + 1);
                                            filepath = Path.Combine(serverpath, dirName, Path.GetFileName(outfile.FileName));
                                        }
                                        else
                                        {
                                            filepath = Path.Combine(serverpath, Path.GetFileName(outfile.FileName));
                                        }
                                        if (!Directory.Exists(Path.GetDirectoryName(filepath)))
                                        {
                                            Directory.CreateDirectory(Path.GetDirectoryName(filepath));
                                        }
                                        using (var stream = new FileStream(filepath, FileMode.Create))
                                        {
                                            outfile.CopyTo(stream);
                                        }

                                    }
                                    else
                                    {
                                        if (jsonList.Contains(Path.GetExtension(outfile.FileName).ToLower()))
                                        {
                                            if (dirName.Contains("\\"))
                                            {
                                                charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
                                                dirName = dirName.Substring(charIndex + 1);
                                                filepath = Path.Combine(serverpath, dirName, Path.GetFileName(outfile.FileName));
                                            }
                                            else
                                            {
                                                filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
                                            }
                                            if (!Directory.Exists(Path.GetDirectoryName(filepath)))
                                            {
                                                Directory.CreateDirectory(Path.GetDirectoryName(filepath));
                                            }
                                            using (var stream = new FileStream(filepath, FileMode.Create))
                                            {
                                                outfile.CopyTo(stream);
                                            }
                                            // outfile.SaveAs(filepath);
                                        }
                                    }
                                }
                                else
                                {
                                    if (dirName.Contains("\\"))
                                    {
                                        charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
                                        dirName = dirName.Substring(charIndex + 1);
                                        filepath = Path.Combine(serverpath.ToString(), dirName, Path.GetFileName(outfile.FileName));
                                    }
                                    else
                                    {
                                        filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
                                    }

                                    if (!Directory.Exists(Path.GetDirectoryName(filepath)))
                                    {
                                        Directory.CreateDirectory(Path.GetDirectoryName(filepath));
                                    }
                                    // outfile.SaveAs(filepath);
                                    using (var stream = new FileStream(filepath, FileMode.Create))
                                    {
                                        outfile.CopyTo(stream);
                                    }
                                }
                            }
                        }
                        else
                        {
                            lottitles = lottitles.Replace("-img", "");
                            lottitles = lottitles.Replace("-txt", "");
                            for (int i = 0; i < httpRequest.Files.Count; i++)
                            {
                                var outfile = httpRequest.Files[i];
                                dirName = Path.GetDirectoryName(outfile.FileName);
                                if (kvpmode == "file")
                                {
                                    if (dirName.Contains("\\"))
                                    {
                                        charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
                                        dirName = dirName.Substring(charIndex + 1);
                                        filepath = Path.Combine(serverpath.ToString(), dirName, Path.GetFileName(outfile.FileName));
                                    }
                                    else
                                    {
                                        filepath_name = Path.GetFileNameWithoutExtension(outfile.FileName);
                                        if (filepath_name.ToString().EndsWith(kvpvalue))
                                        {
                                            filepath = Path.Combine(serverpath.ToString(), lottitles, Path.GetFileName(outfile.FileName));
                                        }
                                        else
                                        {
                                            filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
                                        }

                                    }
                                }
                                else
                                {
                                    if (dirName.Contains("\\"))
                                    {
                                        charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
                                        dirName = dirName.Substring(charIndex + 1);
                                        filepath = Path.Combine(serverpath.ToString(), dirName, Path.GetFileName(outfile.FileName));
                                    }
                                    else
                                    {
                                        filepath_name = Path.GetExtension(outfile.FileName);
                                        if (filepath_name.ToString().EndsWith(".txt"))
                                        {
                                            filepath = Path.Combine(serverpath.ToString(), jobtitle + kvpvalue, Path.GetFileName(outfile.FileName));
                                        }
                                        else
                                        {
                                            filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
                                        }
                                    }
                                }
                                if (!Directory.Exists(Path.GetDirectoryName(filepath)))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(filepath));
                                }
                                // outfile.SaveAs(filepath);
                                using (var stream = new FileStream(filepath, FileMode.Create))
                                {
                                    outfile.CopyTo(stream);
                                }
                            }

                        }
                        //}

                    });
                }
                // }
                return Ok(1);
            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = "Error: " + ex.Message,
                    createdby = 0,
                    controller = "UploaderApi: Downloader"
                };
                oCommonRepository.addlog(data_input, "errorlog");
                return null;
            }
        }

        [HttpPost("chunk")]
        public async Task<IActionResult> UploadChunk([FromForm] IFormFile filechunk,
        [FromForm] string fileId,
        [FromForm] int index,
        [FromForm] int tranid)
        {
            try
            {
                var dir = Path.Combine("TempUploads", tranid.ToString());
                Directory.CreateDirectory(dir);

                var chunkPath = Path.Combine(dir, $"{index}.part");

                using (var stream = new FileStream(chunkPath, FileMode.Create, FileAccess.Write))
                {
                    await filechunk.CopyToAsync(stream);
                }
                return Ok(new { success = true });
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }
        }

        //  [Authorize]
        [HttpGet("GetAllFilesForDownload")]
        public List<FileDetails> GetAllFilesForDownload(int jobid, int tranid)
        {
            List<FileDetails> AllFiles = new List<FileDetails>();
            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
            {
                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                {
                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                    System.Console.WriteLine(useri.Name);
                    string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
                    serverpath = Path.Combine(serverpath, "IN");
                    var filetype = oWorkAreaService.getFileTypeInput(tranid.ToString());
                    var jsonList = new List<string>();
                    string[] inputfiles;
                    if (filetype != null)
                    {
                        var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
                        JArray a_filetype = JArray.Parse(i_filetype.ToString());
                        foreach (var a in a_filetype)
                        {
                            JObject obj_filetype = JObject.Parse(a.ToString());
                            jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
                        }
                    }
                    if (jsonList.Count() == 1 && jsonList[0].ToString().Contains(".*"))
                    {
                        inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).ToArray();
                    }
                    else
                    {

                        inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
                        if (inputfiles.Length == 0)
                        {
                            inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).ToArray();
                            //inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
                        }

                    }
                    foreach (var item in inputfiles)
                    {
                        FileDetails filedetails = new FileDetails();
                        filedetails.FileName = Path.GetFileName(item);
                        filedetails.FilePath = item;
                        AllFiles.Add(filedetails);
                    }
                });
            }
            return AllFiles;


        }



        //  [Authorize]
        [HttpGet("GetAllOutputFiles")]
        public List<FileDetails> GetAllOutputFiles(int jobid, int tranid)
        {
            List<FileDetails> AllFiles = new List<FileDetails>();
            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
            {
                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                {
                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                    System.Console.WriteLine(useri.Name);
                    var filetype = oWorkAreaService.getFileTypeOutput(tranid.ToString());
                    var jsonList = new List<string>();
                    string[] inputfiles;
                    if (filetype != null)
                    {
                        var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
                        JArray a_filetype = JArray.Parse(i_filetype.ToString());
                        foreach (var a in a_filetype)
                        {
                            JObject obj_filetype = JObject.Parse(a.ToString());
                            jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
                        }
                    }
                    //  using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(jobid.ToString()))
                    //  {
                    string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
                    serverpath = Path.Combine(serverpath, "OUT");
                    string[] outputfiles = null;

                    if (Directory.Exists(serverpath))
                    {
                        //outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
                        outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
                    }
                    else
                    {
                        AllFiles = null;
                    }

                    if (outputfiles.Length == 0)
                    {
                        // outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
                        outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
                    }
                    foreach (var item in outputfiles)
                    {
                        FileDetails filedetails = new FileDetails();
                        filedetails.FileName = Path.GetFileName(item);
                        filedetails.FilePath = item;
                        AllFiles.Add(filedetails);
                    }
                });
            }
            // }
            return AllFiles;
        }


        // [Authorize]
        [HttpGet("GetAllOutFilesForDownload")]
        public List<FileDetails> GetAllOutFilesForDownload(int jobid, int tranid)
        {

            List<FileDetails> AllFiles = new List<FileDetails>();
            string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
            serverpath = Path.Combine(serverpath, "OUT");
            var filetype = oWorkAreaService.getFileTypeOutput(tranid.ToString());
            var jsonList = new List<string>();
            if (filetype != null)
            {
                var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
                JArray a_filetype = JArray.Parse(i_filetype.ToString());
                foreach (var a in a_filetype)
                {
                    JObject obj_filetype = JObject.Parse(a.ToString());
                    jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
                }
            }


            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
            {
                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                {
                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                    System.Console.WriteLine(useri.Name);
                    string[] inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly)
                .Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
                    if (inputfiles.Length == 0)
                    {
                        inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories)
                            .Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
                    }
                    foreach (var item in inputfiles)
                    {
                        FileDetails filedetails = new FileDetails();
                        filedetails.FileName = Path.GetFileName(item);
                        filedetails.FilePath = item;
                        AllFiles.Add(filedetails);
                    }
                });
            }
            return AllFiles;
        }

        // [Authorize]
        [HttpPost("downloadInputFiles")]
        public IActionResult downloadInputFiles(dynamic fileData)
        {

            string jobid = fileData.jobid.ToString();
            string tranid = fileData.tranid.ToString();
            string type = fileData.type.ToString();
            string pdid = fileData.pdid.ToString();
            string code = fileData.code.ToString();
            string jobtitle = fileData.jobtitle.ToString();
            string serverpath;
            string zipname = string.Empty;
            var jsonList = new List<string>();
            string filepath = string.Empty;
            string[] inputfiles;

            //string current_stagename = db1.GetDataTable(db, @"select jw.stagename_alias from lot_transaction lt
            //          inner join job_workflow_master jw on jw.jobworkflowid = lt.jobworkflowid
            //          where lt.transactionid = '" + tranid + "'", null).Rows[0][0].ToString();
            // if (type == "stage")
            // {
            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
            {
                serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
                serverpath = Path.Combine(serverpath, "IN");
                zipname = jobtitle + "_" + tranid + ".zip";
                var filetype = oWorkAreaService.getFileTypeInput(tranid);
                if (filetype != null)
                {
                    var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
                    JArray a_filetype = JArray.Parse(i_filetype.ToString());
                    foreach (var a in a_filetype)
                    {
                        JObject obj_filetype = JObject.Parse(a.ToString());
                        jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
                    }
                }
                var curr_stageid = oWorkAreaService.getCurrentStage(tranid);
                string current_stageid = "";
                if (curr_stageid != null)
                {
                    var i_curr_stageid = JsonConvert.DeserializeObject<object>(curr_stageid.ToString());
                    JArray a_curr_stageid = JArray.Parse(i_curr_stageid.ToString());
                    JObject obj_curr_stageid = JObject.Parse(a_curr_stageid[0].ToString());
                    current_stageid = obj_curr_stageid["stageid"].ToString();
                }

                if (jsonList.Count > 0)
                {
                    string zipPath = Path.Combine(serverpath, zipname + ".zip");
                    string tempFolderName = "temp_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
                    string tempPath = Path.Combine(serverpath, tempFolderName);
                    if (!Directory.Exists(tempPath))
                        Directory.CreateDirectory(tempPath);
                    if (jsonList.Count == 1 && jsonList[0].ToString() == ".*")
                    {
                        ZipFile.CreateFromDirectory(tempPath, zipPath);
                        filepath = zipPath;
                        Directory.Delete(tempPath, true);
                        if (filepath != "" || filepath.Length > 0)
                        {

                            byte[] file = System.IO.File.ReadAllBytes(filepath);
                            System.IO.File.Delete(filepath);
                            return Ok(new { File = file });

                        }
                        else
                        {
                            return BadRequest(new { message = "File notfound" });
                        }
                    }
                    else
                    {
                        inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
                        if (inputfiles.Length == 0)
                        {
                            inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories)
                            .Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
                        }
                        byte[] fileBytes = null;
                        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                        {
                            using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
                            {
                                foreach (string f in inputfiles)
                                {
                                    // add the item name to the zip
                                    System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(Path.GetFileName(f) + "." + Path.GetExtension(f));
                                    // add the item bytes to the zip entry by opening the original file and copying the bytes
                                    using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(f)))
                                    {
                                        using (System.IO.Stream entryStream = zipItem.Open())
                                        {
                                            originalFileMemoryStream.CopyTo(entryStream);
                                        }
                                    }
                                }
                            }
                            fileBytes = memoryStream.ToArray();
                            return Ok(new { File = fileBytes });
                            // return Ok(new { File = File(fileBytes, "application/zip", zipname) });
                        }

                    }

                }
                else { return BadRequest(new { message = "File notfound" }); }

                //    }
            }
        }

        //  [Authorize]
        [HttpPost("DownloadInOutFiles")]



        public async Task<IActionResult> DownloadInOutFiles([FromBody] filedownload fileData)
        {
            string jobid = fileData.jobid.ToString() ?? "";
            string tranid = fileData.tranid.ToString() ?? "";
            string pdid = fileData.pdid.ToString() ?? "";
            string option = fileData.option.ToString() ?? "";
            string jobtitle = fileData.jobtitle.ToString() ?? "";

            if (string.IsNullOrWhiteSpace(tranid))
                return BadRequest("Transaction ID is required.");

            try
            {
                // ✅ Step 1: Build server path
                string serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
                if (!string.IsNullOrWhiteSpace(option))
                    serverpath = Path.Combine(serverpath, option);

                if (!Directory.Exists(serverpath))
                    return NotFound("Source folder not found.");

                // ✅ Step 2: Prepare ZIP name
                string zipFileName = (!string.IsNullOrEmpty(option) && (option.Contains("IN") || option.Contains("OUT")))
                    ? $"{jobtitle}_{tranid}_{option}.zip"
                    : $"{jobtitle}_{tranid}.zip";

                // ✅ Step 3: Create app-specific temporary folder (not C:\Windows\Temp)
                string tempBase = Path.Combine(System.AppContext.BaseDirectory, "TempZips");
                Directory.CreateDirectory(tempBase); // ensure it exists
                string tempZipPath = Path.Combine(tempBase, zipFileName);

                // Clean existing temp file if present
                if (System.IO.File.Exists(tempZipPath))
                    System.IO.File.Delete(tempZipPath);

                // ✅ Step 4: Use impersonation to access the server folder
                using (var permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                    await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
                    {
                        // Create ZIP under impersonated context (no compression = faster)
                        ZipFile.CreateFromDirectory(serverpath, tempZipPath, CompressionLevel.NoCompression, includeBaseDirectory: true);
                        await Task.CompletedTask; // keep async signature clean
                    });
                }

                // ✅ Step 5: Stream ZIP to client
                Response.ContentType = "application/zip";
                Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{zipFileName}\"");

                await using (var zipStream = new FileStream(tempZipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    await zipStream.CopyToAsync(Response.Body);
                }

                // ✅ Step 6: Clean up temporary ZIP safely
                try
                {
                    System.IO.File.Delete(tempZipPath);
                }
                catch
                {
                    // ignore cleanup errors
                }

                return new EmptyResult(); // response already written
            }
            catch (Exception ex)
            {
                // ✅ Step 7: Log and return error
                oCommonRepository.addlog(new
                {
                    errormessage = "Error: " + ex.Message,
                    createdby = 0,
                    controller = "WorkAreaApi: DownloadInOutFiles"
                }, "errorlog");

                return StatusCode(500, $"Error while downloading files: {ex.Message}");
            }
        }





        //public async Task<IActionResult> DownloadInOutFiles([FromBody] filedownload fileData)
        //{
        //    try
        //    {
        //        string jobid = fileData.jobid.ToString() ?? "";
        //        string tranid = fileData.tranid.ToString() ?? "";
        //        string pdid = fileData.pdid.ToString() ?? "";
        //        string option = fileData.option.ToString() ?? "";
        //        string jobtitle = fileData.jobtitle.ToString() ?? "";

        //        // Build server path
        //        string serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
        //        serverpath = Path.Combine(serverpath, option);

        //        // Build ZIP filename
        //        string zipname = (option.Contains("IN") || option.Contains("OUT"))
        //            ? $"{jobtitle}_{tranid}_{option}.zip"
        //            : $"{jobtitle}_{tranid}.zip";

        //        DirectoryInfo dirinfo = new DirectoryInfo(serverpath);

        //        if (!dirinfo.Exists)
        //            return NotFound("Source folder not found.");

        //        // Create in-memory zip (streamed, not loaded fully)
        //        var memoryStream = new MemoryStream();

        //        using (var permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
        //        {
        //            WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

        //            await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
        //            {
        //                using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        //                {
        //                    foreach (var file in dirinfo.GetFiles("*.*", SearchOption.AllDirectories))
        //                    {
        //                        string relativePath = file.FullName.Substring(dirinfo.FullName.Length + 1);

        //                        var entry = archive.CreateEntry(relativePath, CompressionLevel.Fastest);
        //                        using var entryStream = entry.Open();
        //                        using var fileStream = System.IO.File.OpenRead(file.FullName);

        //                        await fileStream.CopyToAsync(entryStream);
        //                    }
        //                }
        //            });
        //        }

        //        memoryStream.Position = 0; // reset stream for reading

        //        // Return the zip file to Angular
        //        return File(memoryStream, "application/zip", zipname);
        //    }
        //    catch (Exception ex)
        //    {
        //        oCommonRepository.addlog(new
        //        {
        //            errormessage = "Error: " + ex.Message,
        //            createdby = 0,
        //            controller = "WorkAreaApi: DownloadInOutFiles"
        //        }, "errorlog");

        //        return BadRequest(new { message = "Error: " + ex.Message });
        //    }
        //}


        //public IActionResult DownloadInOutFiles(filedownload fileData)
        //{
        //    try
        //    {
        //        // Extract file data from the request
        //        string jobid = fileData.jobid.ToString();
        //        string tranid = fileData.tranid.ToString();
        //        string pdid = fileData.pdid.ToString();
        //        string option = fileData.option.ToString();
        //        string jobtitle = fileData.jobtitle.ToString();
        //        string serverpath;

        //        // Get the server path based on the transaction ID and other parameters
        //        serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
        //        serverpath = Path.Combine(serverpath, option);

        //        // Generate the zip file name
        //        string zipname = string.Empty;
        //        if (option.Contains("IN") || option.Contains("OUT"))
        //        {
        //            zipname = $"{jobtitle}_{tranid}_{option}.zip";
        //        }
        //        else
        //        {
        //            zipname = $"{jobtitle}_{tranid}.zip";
        //        }

        //        // Get the directory info for the given path
        //        System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(serverpath);

        //        // Check if the directory exists
        //        if (!dirinfo.Exists)
        //        {
        //            return BadRequest(new { message = "Directory does not exist." });
        //        }

        //        // Create a list of file entries from the directory, including subdirectories
        //        FileInfo[] inputfiles = dirinfo.GetFiles("*.*", SearchOption.AllDirectories);

        //        if (inputfiles.Length == 0)
        //        {
        //            return BadRequest(new { message = "No files found in the directory." });
        //        }

        //        byte[] fileBytes = null;

        //        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        //        {
        //            using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
        //            {
        //                foreach (FileInfo file in inputfiles)
        //                {
        //                    // Create a zip entry for each file while maintaining the folder structure
        //                    string relativePath = file.FullName.Substring(dirinfo.FullName.Length + 1); // Get relative path of the file
        //                    System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(relativePath);

        //                    // Open the original file and copy its contents into the zip entry
        //                    using (System.IO.Stream originalFileStream = file.OpenRead())
        //                    {
        //                        using (System.IO.Stream entryStream = zipItem.Open())
        //                        {
        //                            originalFileStream.CopyTo(entryStream);
        //                        }
        //                    }
        //                }
        //            }
        //            // Convert memory stream to byte array
        //            fileBytes = memoryStream.ToArray();
        //        }

        //        // Return the zip file as byte array
        //        return Ok(new { File = fileBytes });

        //        // Alternatively, you can return the file directly as:
        //        // return File(fileBytes, "application/zip", zipname);
        //    }
        //    catch (Exception ex)
        //    {
        //        // Log the error
        //        var data_input = new
        //        {
        //            errormessage = "Error: " + ex.Message,
        //            createdby = 0,
        //            controller = "UploaderApi: Downloader"
        //        };
        //        oCommonRepository.addlog(data_input, "errorlog");

        //        // Return an error message
        //        return BadRequest(new { message = "An error occurred while processing the files." });
        //    }
        //}
        //public IActionResult DownloadInOutFiles(filedownload fileData)
        //{
        //    try
        //    {
        //        string jobid = fileData.jobid.ToString();
        //        string tranid = fileData.tranid.ToString();
        //        string pdid = fileData.pdid.ToString();
        //        string option = fileData.option.ToString();
        //        string jobtitle = fileData.jobtitle.ToString();
        //        string serverpath;
        //        serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
        //        serverpath = Path.Combine(serverpath, option);
        //        string zipname = string.Empty;
        //        if (option.IndexOf("IN") != -1 || option.IndexOf("OUT") != -1)
        //        {
        //            zipname = jobtitle + "_" + tranid + "_" + option + ".zip";
        //        }
        //        else
        //        {
        //            zipname = jobtitle + "_" + tranid + ".zip";
        //        }
        //        string[] inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).ToArray();
        //        byte[] fileBytes = null;
        //        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        //        {
        //            using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
        //            {
        //                foreach (string f in inputfiles)
        //                {
        //                    // add the item name to the zip
        //                    System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(Path.GetFileName(f) + "." + Path.GetExtension(f));
        //                    // add the item bytes to the zip entry by opening the original file and copying the bytes
        //                    using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(f)))
        //                    {
        //                        using (System.IO.Stream entryStream = zipItem.Open())
        //                        {
        //                            originalFileMemoryStream.CopyTo(entryStream);
        //                        }
        //                    }
        //                }
        //            }
        //            fileBytes = memoryStream.ToArray();
        //            return Ok(new { File = fileBytes });
        //            // return Ok(new { File = File(fileBytes, "application/zip", zipname) });
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        var data_input = new
        //        {
        //            errormessage = "Error: " + ex.Message,
        //            createdby = 0,
        //            controller = "UploaderApi: Downloader"
        //        };
        //        oCommonRepository.addlog(data_input, "errorlog");
        //        return BadRequest(new { message = "File notfound" });
        //    }

        //}
        [HttpGet("ValidateOutFileExist")]


        public object ValidateOutFileExist(int jobid, int tranid, string stagename_alias, int projectdefinitionid, string lottitle)
        {

            List<FileDetails> AllFiles = new List<FileDetails>();
            string[] outputfiles = null;
            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
            {
                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                {
                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                    System.Console.WriteLine(useri.Name);

                    //  using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(jobid.ToString()))
                    //  {
                    string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
                    serverpath = Path.Combine(serverpath, "OUT");


                    if (Directory.Exists(serverpath))
                    {
                        outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
                    }
                    else
                    {
                        AllFiles = null;
                    }


                });
            }
            if (outputfiles.Length == 0)
            {

                var json = new { result = false };
                return json;
            }
            else
            {

                if (stagename_alias == "LARE Review")
                {
                    int htmlFilesCount = outputfiles.Count(file => file.EndsWith(".html", StringComparison.OrdinalIgnoreCase));

                    if (htmlFilesCount == 0)
                    {

                        var json = new { result = false };
                        return json;
                    }

                    else
                    {
                        var json = new { result = true };
                        return json;
                    }

                }

                else if (
       (stagename_alias == "Redaction and Styling"
        || stagename_alias == "OCR and Styling")
       && projectdefinitionid == 366
   )
                {
                    int htmlFilesCount = outputfiles.Count(file => file.Contains(lottitle, StringComparison.OrdinalIgnoreCase) &&
                file.EndsWith(".xml", StringComparison.OrdinalIgnoreCase));

                    if (htmlFilesCount == 0)
                    {

                        var json = new { result = false };
                        return json;
                    }

                    else
                    {
                        var json = new { result = true };
                        return json;
                    }
                }
                else if (stagename_alias == "Redaction and Styling" && projectdefinitionid == 364)
                {
                    int htmlFilesCount = outputfiles.Count(file => file.EndsWith("_Redacted.pdf", StringComparison.OrdinalIgnoreCase));

                    if (htmlFilesCount == 0)
                    {

                        var json = new { result = false };
                        return json;
                    }

                    else
                    {
                        var json = new { result = true };
                        return json;
                    }
                }




                else
                {
                    var json = new { result = true };
                    return json;
                }

            }

        }

        // [Authorize]
        //[AllowAnonymous]
        [HttpPost("getdispatchid")]
        public object getdispatchid(long jobid, long tranid, long lotid, string projectsubtitle)
        {
            int jobWorkflowId = 0;
            int dispatchtranid = 0;
            int Allocationtranid = 0;
            string[] inputfiles;
            try
            {


                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    string query = @"
            SELECT lt.transactionid 
            FROM tbllottransaction lt 
            JOIN tbljobworkflowdefinition jwd ON jwd.jobworkflowid = lt.jobworkflowid
            WHERE jwd.stagename_alias = 'Dispatch' AND jwd.jobid = @jobid order by lt.starttime desc limit(1)";
                    var result = dbConnection.QueryFirstOrDefault<int>(query, new { jobid = jobid });
                    if (result != 0)
                    {
                        dispatchtranid = result;  // store the transactionid or use it further
                    }

                    string updateQuerys = @"
UPDATE tbllottransaction
SET lotstatus = 'W'
WHERE transactionid = @transactionid ;
";
                    int rowsAffecteds = dbConnection.Execute(updateQuerys, new { transactionid = dispatchtranid });


                    if (projectsubtitle == "LN_BPM")
                    {
                        string querys = @"
            SELECT lt.transactionid 
            FROM tbllottransaction lt 
            JOIN tbljobworkflowdefinition jwd ON jwd.jobworkflowid = lt.jobworkflowid
            WHERE jwd.stagename_alias = 'Allocation' AND jwd.jobid = @jobid AND lt.lotstatus='F'  order by lt.starttime desc limit(1)  ";
                        var result1 = dbConnection.QueryFirstOrDefault<int>(querys, new { jobid = jobid });
                        if (result1 != 0)
                        {
                            Allocationtranid = result1;  // store the transactionid or use it further
                        }

                        string updateQuery = @"
UPDATE tbllottransaction
SET active = '0'
WHERE transactionid = @transactionid ;
";
                        int rowsAffected = dbConnection.Execute(updateQuery, new { transactionid = Allocationtranid });
                    }

                    else
                    {
                        string querys = @"
            SELECT lt.transactionid 
            FROM tbllottransaction lt 
            JOIN tbljobworkflowdefinition jwd ON jwd.jobworkflowid = lt.jobworkflowid
            WHERE jwd.stagename_alias = 'XML Review' AND jwd.jobid = @jobid AND lt.lotstatus='F'  order by lt.starttime desc limit(1)  ";
                        var result1 = dbConnection.QueryFirstOrDefault<int>(querys, new { jobid = jobid });
                        if (result1 != 0)
                        {
                            Allocationtranid = result1;  // store the transactionid or use it further
                        }

                        string updateQuery = @"
UPDATE tbllottransaction
SET active = '0'
WHERE transactionid = @transactionid ;
";
                        int rowsAffected = dbConnection.Execute(updateQuery, new { transactionid = Allocationtranid });




                    }


                }
                string redactserverinfo = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
                string serverpaths = Path.Combine(redactserverinfo, "IN");
                inputfiles = Directory.GetFiles(serverpaths, "*.pdf", SearchOption.AllDirectories).ToArray();

                foreach (var file in inputfiles)
                {
                    using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid.ToString()))
                    {
                        WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
                        WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                        {
                            // using (ServerInfo.GrantFolderPermission imp = new ServerInfo.GrantFolderPermission(jobid))

                            string serverinfo = oWorkAreaService.GetServerPath(dispatchtranid.ToString(), false, "serverinfo");

                            string serverpath = Path.Combine(serverinfo, "IN");
                            string destinationFilePath = Path.Combine(serverinfo, "IN", Path.GetFileName(file));
                            if (!Directory.Exists(serverpath))
                            {
                                Directory.CreateDirectory(serverpath);
                            }
                            //string destinationFilePath = Path.Combine(serverpath, Path.GetFileName(file));
                            // try
                            // {
                            System.IO.File.Copy(file, destinationFilePath, true);
                            // }


                        });


                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { jobid = ex.Message });

            }

            return Ok(new { jobid = jobid });  // or any other return value you need
        }


        [HttpPost]
        [Route("forwardstage")]
        public IActionResult forwardstage([FromBody] JObject data)
        {



            Guid id = Guid.NewGuid();

            //int next_tranid = InsertLotTransaction(Convert.ToInt32(data1.Rows[0]["lotid"].ToString()), AIstage.ToString(), Path.GetFileNameWithoutExtension(inpath), tranid);

            //   var _listlt = oWorkAreaService.usrLotTransactionInsert(data.p_userid, data.p_lotid, data.p_jobworkflowid, id.ToString(), "insertlottransactiondetailonly");
            long tranid = 0;
            // Safely parse properties from JObject
            int userid = data["p_userid"]?.ToObject<int>() ?? 0;
            long lotid = data["p_lotid"]?.ToObject<long>() ?? 0;
            // long jobworkflowid = Convert.ToInt32(data.p_jobworkflowid) + 1;

            //      using (IDbConnection dbConnection = ConnectionBase.Connection)
            //      {
            //          dbConnection.Open();

            //          string querys = @"
            //SELECT jobworkflowid 
            //FROM tbljobworkflowdefinition 
            //WHERE jobid = @jobid 
            //AND stagename_alias='HTML Generation'";
            //          var jobworkflow = dbConnection.Query<int>(querys, new { jobid = data.p_jobid }).ToList();

            //          string sQry = "insert_lot_transaction_details_only";
            //          using (var cmd = new NpgsqlCommand(sQry, (NpgsqlConnection)dbConnection))
            //          {
            //              cmd.CommandType = CommandType.StoredProcedure;

            //              //cmd.Parameters.Add(new NpgsqlParameter("p_jobworkflowid", NpgsqlTypes.NpgsqlDbType.Bigint) { Value = Convert.ToInt64(jobworkflow) });
            //              if (jobworkflow != null && jobworkflow.Any())
            //              {
            //                  cmd.Parameters.Add(new NpgsqlParameter("p_jobworkflowid", NpgsqlTypes.NpgsqlDbType.Bigint)
            //                  {
            //                      Value = Convert.ToInt64(jobworkflow.First())
            //                  });
            //              }
            //              cmd.Parameters.Add(new NpgsqlParameter("p_lotid", NpgsqlTypes.NpgsqlDbType.Bigint) { Value = lotid });
            //              cmd.Parameters.Add(new NpgsqlParameter("p_lotkey", NpgsqlTypes.NpgsqlDbType.Uuid) { Value = Guid.Parse(id.ToString()) });

            //              object result = cmd.ExecuteScalar();

            //              // Replace modcommon.nz with your own null check or conversion
            //              if (result == null || result == DBNull.Value)
            //              {
            //                  tranid = 0;  // or default value you want
            //              }
            //              else
            //              {
            //                  tranid = Convert.ToInt64(result);
            //              }
            //          }
            //          long transactionId = Convert.ToInt64(data.p_tranid);
            //          string query = @"Update tbllottransaction set lotstatus='F' where transactionid=@transactionid"
            //      ;
            //          var lotIds = dbConnection.Query<int>(query, new { transactionid = transactionId }).ToList();


            //      }

            // var _listlt = oWorkAreaService.usrLotTransactionInsert(userid, lotid, jobworkflowid, id.ToString(), "insertlottransactiondetailonly");

            //string nextstage_serverpath = oCommonRepository.GetServerPath(data.p_tranid.ToString(), "serverinfo",true);


            //RabbitMq sendmsg = new RabbitMq(_requestClient);

            //sendmsg.SendMq_StageComplete(tranid.ToString(), "0", "checkin_apps", "server", "", "A", "");
            return Ok("Success");
        }





        //[Authorize]
        [HttpPost("DownloadSingleFile")]
        public IActionResult DownloadSingleFile(filedownload fileData)
        {
            try
            {
                string type = fileData.type.ToString();
                string path = fileData.path.ToString();
                string jobid = fileData.jobid.ToString();
                byte[] fileBytes = null;
                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                    {
                        WindowsIdentity useri = WindowsIdentity.GetCurrent();
                        fileBytes = System.IO.File.ReadAllBytes(path);
                        string fileName = Path.GetFileName(path);

                    });
                }
                return Ok(new { File = fileBytes });
            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = "Error: " + ex.Message,
                    createdby = 0,
                    controller = "UploaderApi: Downloader"
                };
                oCommonRepository.addlog(data_input, "errorlog");
                throw;
            }
        }



        // [Authorize]
        [HttpPost("DownloadSingleOutFile")]
        public IActionResult DownloadSingleOutFile(filedownload fileData)
        {
            try
            {
                string type = fileData.type.ToString();
                string path = fileData.path.ToString();
                string jobid = fileData.jobid.ToString();
                byte[] fileBytes = null;
                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                    {
                        WindowsIdentity useri = WindowsIdentity.GetCurrent();
                        fileBytes = System.IO.File.ReadAllBytes(path);
                        string fileName = Path.GetFileName(path);
                    });
                }
                return Ok(new { File = fileBytes });


            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = "Error: " + ex.Message,
                    createdby = 0,
                    controller = "UploaderApi: Downloader"
                };
                oCommonRepository.addlog(data_input, "errorlog");
                throw;
            }
        }
        //  [Authorize]
        [HttpPost("RemoveIOFiles")]
        public object RemoveIOFiles(dynamic fileData)
        {

            string path = fileData.path.ToString();
            string jobid = fileData.jobid.ToString();

            try
            {

                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                    {
                        WindowsIdentity useri = WindowsIdentity.GetCurrent();
                        System.IO.File.Delete(path);

                    });
                }
                var json = new { result = true, filename = Path.GetFileName(path) };
                return json;

            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = "Error: " + ex.Message,
                    createdby = 0,
                    controller = "UploaderApi: Downloader"
                };
                oCommonRepository.addlog(data_input, "errorlog");
                var json = new { result = false, filename = Path.GetFileName(path) };
                return json;

            }
        }
        // [Authorize]
        [HttpPost("DownloadFolder")]
        public IActionResult DownloadFolder(dynamic fileData)
        {
            try
            {
                string jobid = fileData.jobid.ToString();
                string FolderPath = fileData.path.ToString();
                string tranid = fileData.tranid.ToString();
                string jobtitle = fileData.jobtitle.ToString();
                string zipname = string.Empty;
                byte[] fileBytes = null;
                bool fail = false;
                zipname = jobtitle + "_" + tranid + ".zip";
                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                    {
                        WindowsIdentity useri = WindowsIdentity.GetCurrent();
                        if (Directory.Exists(FolderPath))
                        {

                            string[] inputfiles = Directory.GetFiles(FolderPath, "*.*", SearchOption.TopDirectoryOnly).ToArray();


                            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                            {
                                using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
                                {
                                    foreach (string f in inputfiles)
                                    {
                                        // add the item name to the zip
                                        System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(Path.GetFileName(f) + "." + Path.GetExtension(f));
                                        // add the item bytes to the zip entry by opening the original file and copying the bytes
                                        using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(f)))
                                        {
                                            using (System.IO.Stream entryStream = zipItem.Open())
                                            {
                                                originalFileMemoryStream.CopyTo(entryStream);
                                            }
                                        }
                                    }
                                }
                                fileBytes = memoryStream.ToArray();

                            }


                        }
                        else
                        {
                            fail = true;

                        }
                    });
                }
                if (!fail) { return Ok(new { File = File(fileBytes, "application/zip", zipname) }); }
                else
                {
                    return BadRequest(new { message = "Folder notfound" });
                }
            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = "Error: " + ex.Message,
                    createdby = 0,
                    controller = "UploaderApi: Downloader"
                };
                oCommonRepository.addlog(data_input, "errorlog");
                return BadRequest(new { message = "Folder notfound" });
            }

        }
        [HttpGet("GetOutfileExtension")]
        public object GetOutfileExtension(long tranid)
        {
            var filetype = oWorkAreaService.getFileTypeOutput(tranid.ToString());
            var jsonList = new List<string>();
            if (filetype != null)
            {
                var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
                JArray a_filetype = JArray.Parse(i_filetype.ToString());
                foreach (var a in a_filetype)
                {
                    JObject obj_filetype = JObject.Parse(a.ToString());
                    jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
                }


            }
            return Ok(jsonList);
        }
        [HttpGet("getOutfileupdated")]
        public object getOutfileupdated(long tranid, string option)
        {
            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString(), "", ""))
            {
                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                {
                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                    string renamedvalue = string.Empty;
                    string anyfiles = string.Empty;
                    string anyfolder = string.Empty;
                    var renametype = oWorkAreaService.getFilerenameInput(tranid.ToString());
                    var titleqry_jsonList = new List<string>();
                    if (renametype != null)
                    {
                        var titleqry_filetype = JsonConvert.DeserializeObject<object>(renametype.ToString());
                        JArray titleqry_a_filetype = JArray.Parse(titleqry_filetype.ToString());
                        renamedvalue = titleqry_a_filetype[0]["filename"].ToString();
                        string serverpath;
                        serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
                        serverpath = Path.Combine(serverpath, option);
                        if (Directory.Exists(serverpath))
                        {
                            string[] folderextensionFilters = new string[] { ".pdf", ".visf" };

                            string[] allfolder = Directory.GetDirectories(serverpath, "*.*", SearchOption.TopDirectoryOnly)
                                              .Where(filename => folderextensionFilters.Any(x =>
                                                    filename.EndsWith(x, StringComparison.OrdinalIgnoreCase))).ToArray();
                            if (allfolder.Count() > 1)
                            {
                                foreach (var folder in allfolder)
                                {
                                    anyfolder = string.Empty;
                                    anyfolder = folder;
                                    if (anyfolder.Contains(".pdf"))
                                    {
                                        anyfiles = string.Empty;
                                        anyfiles = Directory.GetFiles(anyfolder, "*.pdf", SearchOption.TopDirectoryOnly).FirstOrDefault();
                                        if (!string.IsNullOrEmpty(anyfiles) && System.IO.File.Exists(anyfiles))
                                        {
                                            string destinationPath = Path.Combine(anyfolder, renamedvalue + Path.GetExtension(anyfiles));
                                            System.IO.File.Move(anyfiles, destinationPath, true);
                                        }
                                    }
                                    else
                                    {
                                        anyfiles = Directory.GetFiles(anyfolder, "*.txt", SearchOption.TopDirectoryOnly).Where(x => !x.EndsWith("_Validation_report.txt")).FirstOrDefault();
                                        if (!string.IsNullOrEmpty(anyfiles) && System.IO.File.Exists(anyfiles))
                                        {
                                            string destinationPath = Path.Combine(anyfolder, renamedvalue + Path.GetExtension(anyfiles));
                                            System.IO.File.Move(anyfiles, destinationPath, true);
                                        }
                                    }
                                }

                            }
                            anyfiles = string.Empty;
                            anyfiles = Directory.GetFiles(serverpath, "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault();
                            if (!string.IsNullOrEmpty(anyfiles))
                            {
                                string destinationPath = Path.Combine(serverpath, renamedvalue + Path.GetExtension(anyfiles));
                                System.IO.File.Move(anyfiles, destinationPath, true);
                            }
                            //string actulavlue = Startup.Configuration.GetValue<string>("AppSettings:QA_File_type");
                            //actulavlue = Regex.Replace(actulavlue, @"&quot;", "\"", RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Singleline);

                            //string[] extensionFilters = new string[] { ".pdf", ".docx", ".zip" };
                            //string anyfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly)
                            //                    .Where(filename => extensionFilters.Any(x =>
                            //                           filename.EndsWith(x, StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
                            //if (!string.IsNullOrEmpty(anyfiles))
                            //{
                            //    try
                            //    {
                            //        string destinationPath = Path.Combine(serverpath, renamedvalue+Path.GetExtension(anyfiles));
                            //        System.IO.File.Move(anyfiles, destinationPath, true);
                            //    }
                            //    catch(Exception ex)
                            //    {

                            //    }
                            //}
                        }
                    }
                });
            }
            return Ok(1);
        }




        [AllowAnonymous]
        [HttpPost("pushback")]
        public IActionResult PushBack([FromForm] PushBackRequest request)
        {
            try
            {
                // Get base server path
                string serverinfo = oWorkAreaService
                    .GetServerPath(request.tranid.ToString(), false, "serverinfo");

                // Combine folder paths
                string outFolderPath = Path.Combine(serverinfo, "OUT");
                string inFolderPath = Path.Combine(serverinfo, "IN");

                using (CommonRepository.GrantFolderPermission permit =
                       new CommonRepository.GrantFolderPermission("", "", "", request.jobid.ToString()))
                {
                    WindowsIdentity newId = permit.GetImpartunate()?.AllowAccesstoServer();

                    if (newId == null)
                        return StatusCode(500, "Impersonation failed");

                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                    {
                        // Delete OUT folder files
                        if (Directory.Exists(outFolderPath))
                        {
                            var outFiles = Directory.GetFiles(outFolderPath);
                            foreach (var file in outFiles)
                            {
                                System.IO.File.Delete(file);
                            }
                        }

                        // Delete IN folder files
                        if (Directory.Exists(inFolderPath))
                        {
                            var inFiles = Directory.GetFiles(inFolderPath);
                            foreach (var file in inFiles)
                            {
                                System.IO.File.Delete(file);
                            }
                        }
                    });
                }

                var result = oWorkAreaService.PushBack(request);

                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }



        [AllowAnonymous]
        [HttpPost("workflowdecision")]
        public IActionResult workflowdecision([FromBody] object data)
        {
            var _list = oWorkAreaService.workflowdecision(data);
            return Ok(_list);
        }
        public class JobRequest
        {
            public long JobId { get; set; }
        }

        public class PushBackRequest
        {
            public long jobid { get; set; }
            public long lotid { get; set; }
            public long tranid { get; set; }
            public string lottitle { get; set; }
        }

    }
}








