using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using QRCoder;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System.Xml;

namespace Neshina1703
{
    public static class QRCodeHelper
    {
        private static readonly string QRCodeFolder = Path.Combine(
            Application.StartupPath, "QRCodes");
        public static string BaseUrl = "http://localhost:5000/medication/";

        static QRCodeHelper()
        {
            if (!Directory.Exists(QRCodeFolder))
                Directory.CreateDirectory(QRCodeFolder);
        }

        public static string GenerateQRCodeForMedication(int medicationId, string medicationName)
        {
            try
            {
                var medicationInfo = GetMedicationInfo(medicationId);
                string qrData = CreateQRCodeData(medicationInfo);
                using (var qrGenerator = new QRCodeGenerator())
                using (var qrCodeData = qrGenerator.CreateQrCode(qrData, QRCodeGenerator.ECCLevel.Q))
                using (var qrCode = new PngByteQRCode(qrCodeData))
                {
                    string fileName = $"medication_{medicationId}.png";
                    string filePath = Path.Combine(QRCodeFolder, fileName);
                    File.WriteAllBytes(filePath, qrCode.GetGraphic(20));
                    SaveQRCodePath(medicationId, filePath);
                    return filePath;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка генерации QR-кода: {ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

   
        private static string CreateQRCodeData(MedicationInfo info)
        {
            var qrData = new
            {
                id = info.Id,
                name = info.Name,
                price = info.Price,
                stock = info.StockQuantity,
                supplier = info.Supplier,
                status = info.DispensingStatus,
                instructions = info.Instructions,
                analogs = info.Analogs,
                generated = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            };

            return JsonConvert.SerializeObject(qrData, Newtonsoft.Json.Formatting.Indented);
        }


        private static MedicationInfo GetMedicationInfo(int medicationId)
        {
            var query = @"SELECT 
                m.id,
                m.medication_name,
                m.price,
                m.stock_quantity,
                m.instructions,
                m.has_analog,
                s.supplier_name,
                ds.status_name,
                (SELECT GROUP_CONCAT(m2.medication_name SEPARATOR ', ')
                 FROM medications m2
                 WHERE m2.id != m.id 
                 AND EXISTS (
                     SELECT 1 FROM medications m3 
                     WHERE m3.medication_name LIKE CONCAT('%', SUBSTRING_INDEX(m.medication_name, ' ', 1), '%')
                     AND m3.id = m2.id
                 )
                ) as analogs
                FROM medications m
                LEFT JOIN suppliers s ON m.supplier_id = s.id
                LEFT JOIN dispensing_statuses ds ON m.dispensing_status_id = ds.id
                WHERE m.id = @id";

            var parameters = new MySqlParameter[]
            {
                new MySqlParameter("@id", medicationId)
            };
            var table = DB.ExecuteQuery(query, parameters);

            if (table.Rows.Count == 0)
                throw new Exception("Товар не найден");
            var row = table.Rows[0];
            return new MedicationInfo
            {
                Id = Convert.ToInt32(row["id"]),
                Name = row["medication_name"].ToString(),
                Price = Convert.ToDecimal(row["price"]),
                StockQuantity = Convert.ToInt32(row["stock_quantity"]),
                Supplier = row["supplier_name"]?.ToString(),
                DispensingStatus = row["status_name"]?.ToString(),
                Instructions = row["instructions"]?.ToString() ?? "Инструкция не указана",
                Analogs = row["analogs"] != DBNull.Value ? row["analogs"].ToString() : "Аналоги не найдены"
            };
        }

        private static void SaveQRCodePath(int medicationId, string filePath)
        {
            var query = @"UPDATE medications SET qr_code_path = @path WHERE id = @id";
            var parameters = new MySqlParameter[]
            {
                new MySqlParameter("@path", filePath),
                new MySqlParameter("@id", medicationId)
            };

            DB.ExecuteCommand(query, parameters);
        }

 
        public static void GenerateAllQRCodes()
        {
            var query = "SELECT id, medication_name FROM medications";
            var medications = DB.ExecuteQuery(query);

            int count = 0;
            foreach (System.Data.DataRow row in medications.Rows)
            {
                int id = Convert.ToInt32(row["id"]);
                string name = row["medication_name"].ToString();

                GenerateQRCodeForMedication(id, name);
                count++;
            }

            MessageBox.Show($"Сгенерировано QR-кодов: {count}", "Готово",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static void ShowQRCodeInfo(string qrCodePath)
        {
            if (!File.Exists(qrCodePath))
            {
                MessageBox.Show("QR-код не найден", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            string fileName = Path.GetFileName(qrCodePath);
            if (fileName.StartsWith("medication_") && fileName.EndsWith(".png"))
            {
                string idStr = fileName.Replace("medication_", "").Replace(".png", "");
                if (int.TryParse(idStr, out int medicationId))
                {
                    var info = GetMedicationInfo(medicationId);
                    DisplayMedicationInfo(info);
                }
            }
        }

        private static void DisplayMedicationInfo(MedicationInfo info)
        {
            string message = $@"
💊 {info.Name}

💰 Цена: {info.Price} ₽
📦 На складе: {info.StockQuantity} шт.
🏢 Поставщик: {info.Supplier}
📋 Отпуск: {info.DispensingStatus}

📖 Инструкция:
{info.Instructions}

🔄 Аналоги:
{info.Analogs}
";
            MessageBox.Show(message, "Информация о препарате",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }


    public class MedicationInfo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int StockQuantity { get; set; }
        public string Supplier { get; set; }
        public string DispensingStatus { get; set; }
        public string Instructions { get; set; }
        public string Analogs { get; set; }
    }
}