<?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;border: 1px solid #000; font-size: 12px;" cellpadding="5px" cellspacing="0px" ><thead>
  <tr style="">';
  foreach ($table_columns as $columns) {
    if ($columns == 'sr_no') {
      $table .= '<th style="width:30px;border-right: 1px solid black;border-top: 1px solid black; border-bottom: 1px solid black;text-align:center">No.</th>';
    } else if ($columns == 'name') {
      $table .= '<th style=";width:190px;border-right: 1px solid black;border-top: 1px solid black; border-bottom: 1px solid black;">Name</th>';
    } else if ($columns == 'hsn') {
      $table .= '<th style="width:100px;border-right: 1px solid black;;border-top: 1px solid black; border-bottom: 1px solid black;">HSN/SAC</th>';
    } else if ($columns == 'qty') {
      $table .= '<th style="width:100px;text-align:center;border-right: 1px solid black;;border-top: 1px solid black; border-bottom: 1px solid black;">Qty.</th>';
    } else if ($columns == 'units') {
      $table .= '<th style="width:95px;text-align:center;border-right: 1px solid black;;border-top: 1px solid black; border-bottom: 1px solid black;">Unit</th>';
    } else if ($columns == 'price') {
      $table .= '<th style="width:120px;text-align:center;border-right: 1px solid black;border-top: 1px solid black; border-bottom: 1px solid black;">Price</th>';
    } else if ($columns == 'amount') {
      $table .= '<th style="width:110px;text-align:center;;border-top: 1px solid black;border-bottom: 1px solid black;">Amount</th>';
    }
  }
  $table .= '</tr></thead>';

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

    $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="border-right: 1px solid black;border-bottom: 1px solid black;text-align:center" 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="border-right: 1px solid black;border-bottom: 1px solid black" rowspan="' . $rowspan . '">' . strtoupper($item['hsn_code']) . '</td>';
    $table .= '<td style="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="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) . '</td></tr>';

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

  $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 && !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($stocks) . '" 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 && !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>';
        $table .= '</tr>';
      }
    }

    $table .= '<tr><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></tr>';
  }

  $table .= ' </tbody></table>';
  //  print_r($table);die();
  return $table;
}
// $detailed_tax_summary = [
//     [
//         'tax_ledgerid' => 1,
//         'tax_name' => '',
//         'tax_percentage' => '',
//         'hsn_codes' => [],
//         'total_amount' =>
//     ],
//     [
//         'tax_ledgerid' => 1,
//         'tax_name' => '',
//         'tax_percentage' => '',
//         'hsn_codes' => [],
//         'total_amount' =>
//     ]
// ]

//$detailed_tax_summary = [];


//foreach ($stocks as $element) {
    # code...
    // first create a row for this stock
        // iterate on table columns
            // if column == sr_no print $sr_counter;
            // if column == name....

            // if column == tax
                // foreach on ledger_entries for this element
                //only choose the duties and tax ledgerhead, also check that is_add for that should be 1 and display their name and the percentage if apllicable or received
                // when you are displaying this, 
                    // if in_array($tax_ledgerid, $detailed_tax_ids) {
                        // foreach on detailed_tax_summary as tax_element
                            // if tax_element.tax_ledgerid == $tax_ledgerid {
                                // add the hsn code and add to the amount
                                // $detailed_tax_summary[array_search($tax_ledgerid, $detailed_tax_ids).''] = $detailed_tax_summary[array_search($tax_ledgerid, $detailed_tax_ids).'']['hsn'][] = $hsn_code,
                                //  $detailed_tax_summary[array_search($tax_ledgerid, $detailed_tax_ids).''] = $detailed_tax_summary[array_search($tax_ledgerid, $detailed_tax_ids).'']['amount'] = $detailed_tax_summary[array_search($tax_ledgerid, $detailed_tax_ids).'']['amount']+=$amount_for tax
                                // break;
                            // }
                    // }
                    // else {
                        // this means tax has not been added to it, so follow the steps below
                        // $detailed_tax_ids[] = $tax_ledgerid;
                        // $detailed_tax_summary[] = [
                            // 'tax_ledgerid' => $tax_ledgerid,
                            // 'tax_name' => $tax_ledger_name,
                            // 'tax_percentage' => $tax_percentage,
                            // 'hsn_codes' => [$hsn_code] for the item,
                            // 'total_amount' => $amount_for_tax
                        // ]
                    // }

    // $sr_counter++;
    // close the tr tag
//}
