using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows;
using System.Windows.Controls;

namespace WpfApp1
{
    public partial class OrdersWindow : Window
    {
        private const string Conn = "Host=80.250.189.52;Port=5432;Database=dbwork;Username=kotov_aa;Password=0$s%MB3&F6#";

        public OrdersWindow()
        {
            InitializeComponent();
            LoadClients();
            LoadOrders(null, false);
        }

        private void LoadClients()
        {
            using var conn = new NpgsqlConnection(Conn);
            conn.Open();
            var cmd = new NpgsqlCommand("SELECT customerid, companyname FROM Customers ORDER BY companyname", conn);
            var adapter = new NpgsqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            cmbClients.ItemsSource = dt.DefaultView;
            cmbClients.SelectedIndex = -1;
        }

        private void LoadOrders(int? clientId, bool onlyLate)
        {
            string sql = "SELECT o.orderid, c.companyname, o.orderdate, o.plandate, o.factdate, o.status " +
                         "FROM Orders o JOIN Customers c ON o.customerid = c.customerid WHERE 1=1";

            var parameters = new List<NpgsqlParameter>();

            if (clientId.HasValue)
            {
                sql += " AND o.customerid = @cid";
                parameters.Add(new NpgsqlParameter("@cid", clientId.Value));
            }

            if (onlyLate)
            {
                sql += " AND (o.factdate > o.plandate OR (o.factdate IS NULL AND o.plandate < CURRENT_DATE))";
            }

            sql += " ORDER BY o.plandate DESC";

            using var conn = new NpgsqlConnection(Conn);
            conn.Open();
            using var cmd = new NpgsqlCommand(sql, conn);
            if (parameters.Count > 0) cmd.Parameters.AddRange(parameters.ToArray());

            var adapter = new NpgsqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            dgOrders.ItemsSource = dt.DefaultView;
        }

        private void BtnFilter_Click(object sender, RoutedEventArgs e)
        {
            int? clientId = cmbClients.SelectedValue != null ? Convert.ToInt32(cmbClients.SelectedValue) : null;
            bool onlyLate = chkLate.IsChecked == true;
            LoadOrders(clientId, onlyLate);
        }

        private void BtnReset_Click(object sender, RoutedEventArgs e)
        {
            cmbClients.SelectedIndex = -1;
            chkLate.IsChecked = false;
            LoadOrders(null, false);
        }
    }
}