<?php
function createStockTable($stocks, $ledgerrecord, $table, $currencySystem, $number_of_decimal_places)
{

  $tax_column_counter = 0;
  $tax = [];
  $table_columns = ['sr_no', 'name', 'hsn', 'qty', 'units', 'price'];

  $detailed_tax_ids = []; //add like taxid.taxpercentage
  $detailed_tax_summary = [];
  $summarytotalamount = 0;


  $table_columns[] = 'amount';

  // forming table headers
  $table .= '<table style="width: 100%;margin-top:5px; font-size: 12px;" cellpadding="5px" cellspacing="0px"><thead>
  <tr style="">';
  foreach ($table_columns as $columns) {
    if ($columns == 'sr_no') {
      $table .= '<td style="width:2px;border-right: 1px solid black;border-top: 1px solid black; border-bottom: 1px solid black;">No.</td>';
    } else if ($columns == 'name') {
      $table .= '<td style=";border-right: 1px solid black;border-top: 1px solid black; border-bottom: 1px solid black;">Name</td>';
    } else if ($columns == 'hsn') {
      $table .= '<td style="width:70px;border-right: 1px solid black;;border-top: 1px solid black; border-bottom: 1px solid black;">HSN/SAC</td>';
    } else if ($columns == 'qty') {
      $table .= '<td style="text-align:center;width:30px;border-right: 1px solid black;;border-top: 1px solid black; border-bottom: 1px solid black;">Qty.</td>';
    } else if ($columns == 'units') {
      $table .= '<td style="text-align:center;width:10px;border-right: 1px solid black;;border-top: 1px solid black; border-bottom: 1px solid black;">Unit</td>';
    } else if ($columns == 'price') {
      $table .= '<td style="text-align:center;border-right: 1px solid black;border-top: 1px solid black; border-bottom: 1px solid black;">Price</td>';
    } else if ($columns == 'amount') {
      $table .= '<td style="text-align:center;;border-top: 1px solid black;border-bottom: 1px solid black">Amount</td>';
    }
  }
  $table .= '</tr></thead>';

  // now creating table body with data
  $sr_counter = 0;
  $grand_total = 0.00;
  $table .= '<tbody>';
  foreach ($stocks as $item) {
    // print_r($stocks);
    $hsn_code = $item['hsn_code'];

    // getting the ledgerrecord count
    // $rowspan = (isset($item['ledger_entries']) and is_array($item['ledger_entries']) and  count($item['ledger_entries']) > 0) ? (count($item['ledger_entries']) + 2) : 1;    
    $rowspan = (isset($item['ledger_entries']) and is_array($item['ledger_entries']) and  count($item['ledger_entries']) > 0) ? 2 : 1;

    $temp_amount = floatval($item['total_amount']);

    // first is sr no
    $sr_counter++;
    $table .= '<tr>';
    $table .= '<td style="width:2px;border-right: 1px solid black;border-bottom: 1px solid black" rowspan="' . $rowspan . '">' . $sr_counter . '</td>';
    $table .= '<td style=";border-right: 1px solid black;border-bottom: 1px solid black" rowspan="' . $rowspan . '">' . ucwords($item['stock_name']);
    if ($item['description'] != '') {
      $table .= '<br/><i>' . $item['description'] . '</i>';
    }
    $table .= '</td>';
    $table .= '<td style="width:30px;border-right: 1px solid black;border-bottom: 1px solid black" rowspan="' . $rowspan . '">' . strtoupper($item['hsn_code']) . '</td>';
    $table .= '<td style="width:10px;border-right: 1px solid black;border-bottom: 1px solid black">';
    // if($item['boolean_inventory'] == '1') {
    $table .= formatCurrency($item['qty'], $currencySystem, $number_of_decimal_places, null) . '</td>';
    // } else {
    // $table .= '- </td>';
    // }
    $table .= '<td style="width:10px;border-right: 1px solid black;border-bottom: 1px solid black">' . $item['unit_name'] . '</td>';
    $table .= '<td style="text-align: right;;border-right: 1px solid black;border-bottom: 1px solid black">' . formatCurrency($item['per_price'], $currencySystem, $number_of_decimal_places, null) . '</td>';

    if ($rowspan == 1) {
      // final amount
      $table .= '<td style="text-align: right;border-bottom: 1px solid black">' . formatCurrency($item['total_amount'], $currencySystem, $number_of_decimal_places, null) . '</td></tr>';
      $grand_total += $item['total_amount'];
    } else {
      foreach ($item['ledger_entries'] as $element) {
        // adding to calculations for stock price
        if ($element['is_add'] == 1) {
          $temp_amount += floatval($element['total_amount']);
        } else {
          $temp_amount -= floatval($element['total_amount']);
        }

        // for detailed tax summary
        if ($element['ledger_main_ledgerhead'] === 'Duties & Taxes' and $element['is_add'] == 1) {
          $temp_tax_ledgerid = $element['ledgerid'];
          $temp_tax_name = $element['ledger_name'];
          $temp_tax_percentage = $element['percentage'];

          $unique_temp_taxid = $temp_tax_ledgerid . "" . $temp_tax_percentage;
          if (in_array($unique_temp_taxid, $detailed_tax_ids)) {
            $detailed_tax_summary[array_search($unique_temp_taxid, $detailed_tax_ids) . '']['hsn_codes'] = [...$detailed_tax_summary[array_search($unique_temp_taxid, $detailed_tax_ids) . '']['hsn_codes'], $hsn_code];
            $detailed_tax_summary[array_search($unique_temp_taxid, $detailed_tax_ids) . '']['total_amount'] += $element['total_amount'];
          } else {
            $detailed_tax_ids[] = $unique_temp_taxid;
            $detailed_tax_summary[] = [
              'tax_ledgerid' => $temp_tax_ledgerid,
              'tax_name' => $temp_tax_name,
              'tax_percentage' => $temp_tax_percentage,
              'hsn_codes' => [$hsn_code],
              'total_amount' => $element['total_amount']
            ];
          }
        }
      }

      $table .= '<td style="text-align: right;;border-bottom: 1px solid black" rowspan="' . $rowspan . '">' . formatCurrency($temp_amount, $currencySystem, $number_of_decimal_places, null) . '</td></tr>';

      $grand_total += $temp_amount;

      $table .= '<tr><td colspan="3" style="border-right: 1px solid black; border-bottom: 1px solid black; text-align:right; font-size: 11px; font-style: italic;">';
      foreach ($item['ledger_entries'] as $element) {
        if ($element['is_add'] == 1) {
          $temp_amount += floatval($element['total_amount']);
        } else {
          $temp_amount -= floatval($element['total_amount']);
        }
        $table .= $element['ledger_name'] . "&nbsp;&nbsp;";
        if ($element['is_add'] == 0) {
          $table .= " - ";
        }
        $table .= formatCurrency($element['total_amount'], $currencySystem, $number_of_decimal_places, null) . ' <br>';
      }
      $table .= '</td><tr>';
    }
  }

  if ($ledgerrecord != null) {
    $table .= '<tr><td style="text-align: right;border-bottom: 1px solid black;" colspan="7"><strong>' . formatCurrency($grand_total, $currencySystem, $number_of_decimal_places, null) . '</strong></td></tr>';
    foreach ($ledgerrecord as $element) {

      if ($element['is_add'] == 1) {
        $temp_amount += floatval($element['total_amount']);
      } else {
        $temp_amount -= floatval($element['total_amount']);
      }
      $grand_total += $temp_amount;
      $table .= '<tr><td style="text-align: right;border-bottom: 1px solid black;" colspan="6">';

      $table .= $element['ledger_name'] . '&nbsp;&nbsp;</td><td style="text-align: right;border-bottom: 1px solid black;">';
      if ($element['is_add'] == 0) {
        $table .= " - ";
      }
      $table .= formatCurrency($element['total_amount'], $currencySystem, $number_of_decimal_places, null) . ' <br>';

      // adding to detailed tax summary
      if ($element['is_add'] == 1 and $element['ledger_main_ledgerhead'] == 'Duties & Taxes') {
        $detailed_tax_summary[] = array(
          'tax_name' => $element['ledger_name'],
          'tax_percentage' => ($element['percentage'] != null and !empty($element['percentage'])) ? $element['percentage'] : 0,
          'total_amount' => $element['total_amount']
        );
      }
    }
    $table .= '</td></tr>';
  }

  $table .= '<tr><td  colspan="7" style="text-align:right;border-bottom: 1px solid black"><strong>Grand Total&nbsp; &nbsp; ' . formatCurrency($grand_total, $currencySystem, $number_of_decimal_places, null) . '<strong></td></tr>';

  $amount_in_words = convertNumberToIndianWords($grand_total);
  $table .= '<tr><td style="border-bottom: 1px solid black;" colspan="7">Amount in words <br><strong> ' . $amount_in_words . ' only</strong></td></tr>';

  if (!empty($detailed_tax_summary)) {

    $table .= '<tr><td style="border-right: 1px solid black;border-bottom: 1px solid black;" colspan="7">Tax Summary</td></tr>
    <tr>
    <td style="border-right: 1px solid black;border-bottom: 1px solid black;" colspan="2">HSN</td>
    <td style="border-right: 1px solid black;border-bottom: 1px solid black; text-align:right;">Name</td>
    <td style="border-right: 1px solid black;border-bottom: 1px solid black;">Percentage</td>
    <td style="border-right: 1px solid black;border-bottom: 1px solid black; text-align:right;" colspan="3">Amount</td>
    </tr>';
    // this is for tax summary without hsn codes
    $count = 0;
    foreach ($detailed_tax_summary as $tax_entry) {
      // Check if $tax_entry is not null and is an array
      if (is_array($tax_entry) && isset($tax_entry['total_amount'])) {
        $summarytotalamount += $tax_entry['total_amount'];
        // Check if 'hsn_codes' key exists and is an array

        if (isset($tax_entry['hsn_codes']) && is_array($tax_entry['hsn_codes'])) {
          $hsn_code = implode(", ", $tax_entry['hsn_codes']);
          $table .= ' <tr><td style="border-right: 1px solid black;border-bottom: 1px solid black" colspan="2"> ' . $hsn_code . ' </td>';
        } else {
          if ($count == 0) {
            $hsn = [];
            foreach ($stocks as $element_stocks) {
              if ($element_stocks['hsn_code'] != null and !empty($element_stocks['hsn_code'])) {
                $hsn[] = trim($element_stocks['hsn_code']);
              }
            }
            $hsn_code = implode(", ", $hsn);
            $table .= ' <tr><td style="border-right: 1px solid black;border-bottom: 1px solid black" rowspan="' . count($detailed_tax_summary) . '" colspan="2"> ' . $hsn_code . ' </td>';
          }
          else
          {
              
              $table .= ' <tr>';
              
          }
          $count++;
        }

        // Check if 'tax_name' and 'tax_percentage' keys exist
        if (isset($tax_entry['tax_name']) && isset($tax_entry['tax_percentage'])) {
          $table .= '<td style="text-align:right;border-right: 1px solid black;border-bottom: 1px solid black">' . $tax_entry['tax_name'] . '</td>';
          if ($tax_entry['tax_percentage'] != 0 and !empty($tax_entry['tax_percentage'])) {
            $table .=   '<td style="border-right: 1px solid black;border-bottom: 1px solid black; text-align: right;">' . $tax_entry['tax_percentage'] . '% </td>';
          } else {
            $table .=  '<td style="border-bottom: 1px solid black"></td>';
          }
        }

        $table .= '<td style="border-right: 1px solid black;border-bottom: 1px solid black; text-align: right" colspan="3">' . formatCurrency($tax_entry['total_amount'], $currencySystem, $number_of_decimal_places, null) . '</td> </tr>';
      }
    }

    $table .= ' <tr>';
    $table .= '<td style="text-align:right; border-right: 1px solid black; border-bottom: 1px solid black; font-weight:bold" colspan="7">Total Tax : ' . formatCurrency($summarytotalamount, $currencySystem, $number_of_decimal_places, null)  . '</td>';
    $table .= ' </tr>';
  }
  $table .= ' </tbody></table>';
  return $table;
}
