//+------------------------------------------------------------------+
//|                                           SymbolTradeReport.mq5  |
//+------------------------------------------------------------------+

#property script_show_inputs

//--- Includes
#include <Pdfreport/TradeStat.mqh>
#include <Pdfreport/TradeStatCalculator.mqh>
#include <Pdfreport/PdfBuilder.mqh>
#include <Pdfreport/ReportLayout.mqh>

//--- Inputs
input string   InpSymbol         = "";   // Symbol (empty = current chart symbol)
input long     InpMagic          = 0;    // Magic filter (0 = all magic numbers)
input datetime InpFrom           = 0;    // Start date (0 = earliest available)
input datetime InpTo             = 0;    // End date (0 = now)
input string   InpOutputFilename = "";   // Output filename (empty = <symbol>_report.pdf)

//+------------------------------------------------------------------+
//| Script entry point: compute statistics and write the PDF report. |
//+------------------------------------------------------------------+
void OnStart()
  {
//--- resolve defaults
   string symbol = (InpSymbol == "") ? _Symbol : InpSymbol;
   datetime from = InpFrom;
   datetime to   = (InpTo == 0) ? ::TimeCurrent() : InpTo;

   if(from >= to)
     {
      ::PrintFormat("SymbolTradeReport: invalid range - from (%s) must be before to (%s).",
                    ::TimeToString(from), ::TimeToString(to));
      return;
     }

   string filename = (InpOutputFilename == "")
                     ? (symbol + "_report.pdf")
                     : InpOutputFilename;

   uint t_start = ::GetTickCount();

//--- compute statistics from live history
   CTradeStatCalculator calc;
   calc.Init(symbol, InpMagic);

   CTradeStat stat;
   if(!calc.Calculate(from, to, stat))
     {
      ::Print("SymbolTradeReport: statistics calculation failed. Check the Experts tab.");
      return;
     }

   if(stat.total_trades == 0)
     {
      ::PrintFormat("SymbolTradeReport: no closed trades found for %s in the given range.",
                    symbol);
      return;
     }

//--- lay out the report page using the shared layout function and
//--- write the finished PDF to disk
   string generated_at = ::TimeToString(::TimeCurrent(),
                                        TIME_DATE | TIME_MINUTES | TIME_SECONDS);

   CPdfBuilder pdf;
   BuildReportContent(pdf, stat, generated_at);

   if(!pdf.Save(filename))
     {
      ::Print("SymbolTradeReport: PDF write failed. Check the Experts tab for details.");
      return;
     }

   uint elapsed = ::GetTickCount() - t_start;
   ::PrintFormat("SymbolTradeReport: %s - %d trades, net %.2f, win rate %.1f%%. "
                 "Report: MQL5/Files/%s (%d ms)",
                 symbol, stat.total_trades, stat.net_profit, stat.win_rate,
                 filename, elapsed);
  }
//+------------------------------------------------------------------+