using System;
using System.Windows;
using System.Windows.Media.Imaging;

namespace RevitEstimate
{
    public partial class ActivationWindow : Window
    {
        public bool IsActivated { get; private set; } = false;

        public ActivationWindow()
        {
            InitializeComponent();
            LoadQrImage();

            // Auto-load Unique Machine ID
            TxtMachineId.Text = LicenseManager.GetMachineId();
        }

        private void LoadQrImage()
        {
            try
            {
                Uri resourceUri = new Uri("pack://application:,,,/RevitEstimate;component/Images/upi_qr.png", UriKind.Absolute);
                BitmapImage bitmap = new BitmapImage(resourceUri);
                ImgQrCode.Source = bitmap;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("QR Load Error: " + ex.Message);
            }
        }

        private void BtnCopyId_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Clipboard.SetText(TxtMachineId.Text);
                MessageBox.Show("Unique ID copied to clipboard!", "Copied", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to copy ID: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnActivate_Click(object sender, RoutedEventArgs e)
        {
            string enteredKey = TxtLicenseKey.Text.Trim();

            if (string.IsNullOrEmpty(enteredKey))
            {
                TxtStatus.Text = "Please enter a valid license key.";
                return;
            }

            if (LicenseManager.ValidateAndSaveLicense(enteredKey))
            {
                MessageBox.Show("License activated successfully! Thank you for choosing Pooja Enterprises.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                IsActivated = true;
                this.Close();
            }
            else
            {
                TxtStatus.Text = "Invalid Key for this PC. Please check and try again.";
            }
        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            if (!LicenseManager.IsLicensed())
            {
                MessageBox.Show(
                    "Kindly Buy License to proceed!\n\nA team worked hard for this software.",
                    "License Required - Pooja Enterprises",
                    MessageBoxButton.OK,
                    MessageBoxImage.Warning
                );
            }
            this.Close();
        }
    }
}