\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{kiviletter}[2019/10/10 Letter Layouts for Kivitendo]

\newif\if@kivi@infobox
\DeclareOption{reffields}{\@kivi@infoboxfalse}
\DeclareOption{infobox}{\@kivi@infoboxtrue}
\@kivi@infoboxtrue

\newif\if@kivi@faketable
\DeclareOption{faketable}{\@kivi@faketabletrue}

\ProcessOptions\relax


\RequirePackage{expl3}
\RequirePackage{iftex}
% Schriftart, Eingabelayout der Tastatur
\ifPDFTeX
\RequirePackage[utf8]{inputenc}% Nur notwendig, wenn Basis älter als TL2018
\RequirePackage[T1]{fontenc}
\else
\RequirePackage{fontspec}
\fi

%\RequirePackage{xltabular}
\RequirePackage{tabularx}
\RequirePackage{longtable}
\RequirePackage{booktabs}
\PassOptionsToPackage{table}{xcolor}

\RequirePackage{xcolor}
\RequirePackage{graphicx}

\ifPDFTeX
\RequirePackage{eurosym}
\DeclareUnicodeCharacter{20AC}{\euro}
\fi

\RequirePackage[fromlogo,fromalign=right,
	firstfoot=false,%Für einheitliche Randeinstellungen
	]{scrletter}
\LoadLetterOption{DIN}

\usepackage{geometry}

\ExplSyntaxOn
\dim_new:N \g_kivi_margin_dim
\dim_gset:Nn \g_kivi_margin_dim {\useplength{toaddrhpos}}
\geometry{a4paper,margin=\g_kivi_margin_dim,heightrounded}
\savegeometry{kivi.letter@default}
%Scratch variables
\int_new:N \l_kivi_tmp_int
\bool_new:N \l_kivi_tmp_bool
\bool_new:N  \g_kivi_TableFoot_bool
\dim_new:N \g_kivi_orig@textheight_dim
\int_new:N \g_PricingTabular_firstpage_int
\ExplSyntaxOff

\newsavebox{\shippingAddressBox}


\DeclareNewLayer[
foreground,
hoffset=\useplength{toaddrhpos},
voffset=\dimexpr\useplength{toaddrvpos}+\useplength{toaddrheight}+\baselineskip,
contents={\usebox\shippingAddressBox}
]{kivitendo.shippingaddress}


\ExplSyntaxOn
\DeclareNewLayer[
foreground,
mode=picture,
hoffset=\g_kivi_margin_dim,
voffset=\g_kivi_margin_dim,
align=tl,
height=\box_ht:N \g_kivi_LT@head_box,
contents={\box_use:N \g_kivi_LT@head_box},
]{kivitendo.TableHead}


\DeclareNewLayer[
foreground,
textarea,
mode=picture,
voffset=\dim_eval:n {\paperheight-\g_kivi_margin_dim},
height=\box_ht:N \g_kivi_LT@foot_box,
contents=\bool_if:NT \g_kivi_TableFoot_bool {\box_use:N \g_kivi_LT@foot_box},
align=bl,
]{kivitendo.TableFoot}

\AtBeginLetter{\dim_gset:Nn \g_kivi_orig@textheight_dim {\textheight}}
\ExplSyntaxOff

\DeclareNewPageStyleByLayers{kivitendo.letter.PricingTable}{
	kivitendo.TableHead,
	kivitendo.TableFoot
}
\DeclareNewPageStyleByLayers{kivitendo.letter.first}{
	kivitendo.shippingaddress,
	kivitendo.TableFoot
}

\setkomavar{backaddress}{\firma\ $\cdot$ \strasse\ $\cdot$ \ort}
\@setplength{locwidth}{6cm}

\ExplSyntaxOn
\dim_new:N \g_kivi_tab_pos_dim
\dim_gset:Nn \g_kivi_tab_pos_dim {3.5ex}
\dim_new:N \g_kivi_tab_id_dim
\dim_gset:Nn \g_kivi_tab_id_dim {4em}
\dim_new:N \g_kivi_tab_num_dim
\dim_gset:Nn \g_kivi_tab_num_dim {5em}
\dim_new:N \g_kivi_tab_price_dim
\dim_gset:Nn \g_kivi_tab_price_dim {7em}
\dim_new:N \g_kivi_tab_desc_dim

\dim_new:N \g_kivi_tabcolsep_dim
\dim_gset:Nn \g_kivi_tabcolsep_dim {.5\tabcolsep}
\newcommand*{\CalcTabCols}{
	\dim_gset:Nn \g_kivi_tab_desc_dim {\textwidth-\g_kivi_tab_pos_dim -\g_kivi_tab_id_dim-\g_kivi_tab_num_dim - 2\g_kivi_tab_price_dim - 10\g_kivi_tabcolsep_dim}
}

\newcolumntype{P}{>{\raggedleft\arraybackslash}p{\g_kivi_tab_price_dim}<{\,\currency}}

%\if@kivi@faketable
\RequirePackage{tcolorbox}
\tcbuselibrary{breakable, skins}
\seq_new:N \l_kivi_PricingTable_seq
\seq_new:N \g_kivi_extraDescription_seq
\newcommand{\FakeTable}[1]{
	\par
	\CalcTabCols
	\seq_set_split:Nnn \l_kivi_PricingTable_seq {\tabularnewline} {#1}
	\begingroup
	\setlength{\tabcolsep}{\g_kivi_tabcolsep_dim}
	\seq_map_inline:Nn \l_kivi_PricingTable_seq {
	\seq_gclear:N \g_kivi_extraDescription_seq
	\exp_args:NnV \use:n {\tabular[t]}\g_kivi_Pricing_colspec_tl
	##1
	\endtabular
	\seq_if_empty:NTF \g_kivi_extraDescription_seq
	{\par\nointerlineskip}
	{\par\nointerlineskip
	\begin{tcolorbox}[
		empty,
		left=\dim_eval:n {\g_kivi_tab_pos_dim+ \g_kivi_tab_id_dim +4\g_kivi_tabcolsep_dim},
		right=\dim_eval:n {\g_kivi_tab_num_dim+ 2\g_kivi_tab_price_dim +6\g_kivi_tabcolsep_dim},top=0pt,bottom=0pt,
		boxsep=0pt,
		breakable,
		lines~before~break=1,
	]
	\seq_use:Nn \g_kivi_extraDescription_seq {\\}
	\end{tcolorbox}
	\nointerlineskip
	}
	}
	\endgroup
}


\tl_new:N \g_kivi_Pricing_colspec_tl
\tl_gset:Nn \g_kivi_Pricing_colspec_tl {@{}p{\g_kivi_tab_pos_dim}p{\g_kivi_tab_id_dim}p{\g_kivi_tab_desc_dim}>{\raggedleft\arraybackslash}p{\g_kivi_tab_num_dim}*2{P}@{}}


\clist_map_inline:nn {head, foot, firsthead, lastfoot} {%TODO reduce
	\box_new:c {g_kivi_LT@#1_box}
}

\AtBeginDocument{
	\csname kivi_setup_LT_boxes:\endcsname
	\geometry{a4paper,
		hmargin=\g_kivi_margin_dim,
		top=\dim_eval:n {\g_kivi_margin_dim + \box_ht:N \g_kivi_LT@head_box},
		bottom=\dim_eval:n {\g_kivi_margin_dim + \box_ht:N \g_kivi_LT@foot_box},
		heightrounded}
	\savegeometry{kivi.letter@table}
	\loadgeometry{kivi.letter@default}
}

\cs_new:Nn \kivi_setup_LT_boxes: {
	\CalcTabCols
	\hbox_gset:Nn \g_kivi_LT@head_box {
	\setlength{\tabcolsep}{\g_kivi_tabcolsep_dim}
	\exp_args:NnV \use:n {\tabular[b]}\g_kivi_Pricing_colspec_tl
	\toprule
	\bfseries\position & \bfseries\artikelnummer & \bfseries\bezeichnung & \bfseries\menge &\multicolumn{1}{P}{\bfseries\einzelpreis}&\multicolumn{1}{P@{}}{\bfseries\gesamtpreis}\\
	\midrule
	\endtabular
	}
	\hbox_gset:Nn \g_kivi_LT@foot_box {
	\raisebox{\depth}{
	\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}}r@{}}
	\midrule
	\strut\weiteraufnaechsterseite
	\end{tabular*}
	}
	}
}


%Macht es sinn hier eine Variante zu machen, in der alle Spalten Belegbar sind?
\newenvironment{PricingTotal}{
	\tabular[t]{@{}p{\dim_eval:n {\linewidth-\g_kivi_tab_price_dim-2\tabcolsep}}P@{}}
	\midrule
}{
	\bottomrule\endtabular
}

\newcommand{\ExtraDescription}[1]{\seq_gput_right:Nn \g_kivi_extraDescription_seq {#1}}
%\else
\newenvironment{PricingTabular}[1][]{
	\begingroup
	\setlength{\tabcolsep}{\g_kivi_tabcolsep_dim}
	\CalcTabCols
	\exp_args:NV \longtable \g_kivi_Pricing_colspec_tl
	% Tabellenkopf
	\toprule
	\bfseries\position & \bfseries\artikelnummer & \bfseries\bezeichnung & \bfseries\menge &\multicolumn{1}{P}{\bfseries\einzelpreis}&\multicolumn{1}{P@{}}{\bfseries\gesamtpreis}\\
	\midrule
	\endhead
	\midrule
	\multicolumn{6}{@{}r@{}}{\weiteraufnaechsterseite}\\
	\endfoot
}{
	\endlongtable
	\endgroup
}

\usepackage{afterpage}

\cs_new:cpn {PricingTabular*}{
	\bool_gset_true:N \g_kivi_inTable_bool
	\endgroup
	\@nameuse{Gm@restore@@kivi.letter@table}%
	\Gm@changelayout
	\begingroup
	\def \@currenvir {PricingTabular*}\edef \@currenvline {\on@line }
	\int_gset:Nn \g_PricingTabular_firstpage_int {\c@page}
	\addtolength{\vsize}{-\box_ht:N \g_kivi_LT@foot_box}
	\pagegoal\vsize
	\widowpenalty0
	\clubpenalty0
	\bool_gset_true:N \g_kivi_TableFoot_bool
	\pagestyle{kivitendo.letter.PricingTable}
	\leavevmode\box_use:N \g_kivi_LT@head_box
	\par\nointerlineskip\ignorespaces
}

\cs_new:cpn {endPricingTabular*} {
	\int_compare:nNnF \g_PricingTabular_firstpage_int = \c@page {\thispagestyle{kivitendo.letter.PricingTable}}
	\bool_gset_false:N \g_kivi_TableFoot_bool
	\@nameuse{Gm@restore@@kivi.letter@default}
	\Gm@changelayout
	\bool_gset_true:N \g_kivi_restore_geometry_bool
	\afterpage{
		\kivi_conditional_restore_geometry:
	}
}

\cs_new:Nn \kivi_conditional_restore_geometry: {
	\bool_if:NT \g_kivi_restore_geometry_bool
	{
	\@nameuse{Gm@restore@@kivi.letter@default}
	\Gm@changelayout
	}
	\bool_gset_false:N \g_kivi_restore_geometry_bool
}
%\ExplSyntaxOff

\if@kivi@infobox
\newkomavar{locationtitle}
\setkomavar{location}{
	\begin{flushright}
		\bfseries
		\LARGE
		\usekomavar{locationtitle}
	\end{flushright}
	\par
	\medskip
	\begin{tabularx}{\linewidth}{@{}l<{:}>{\raggedright\arraybackslash}X@{}}
		\datum&\usekomavar{date}\\
		\kundennummer&\usekomavar{customer}\\
		\ansprechpartner&\usekomavar{fromname}
		\ifkomavarempty{fromphone}{}{\\\textTelefon&\usekomavar{fromphone}}
		\ifkomavarempty{fromemail}{}{\\\textEmail&\usekomavar{fromemail}}
	\end{tabularx}
}
\removereffields

%\ExplSyntaxOn
\AtBeginLetter{
	\ifkomavarempty{title}{}{
		\exp_args:Nno\setkomavar{locationtitle}{\scr@title@var}
		\setkomavar{title}{}
	}
}
\ExplSyntaxOff
\fi



\renewcommand*{\raggedsignature}{\raggedright}

\endinput
