<div class="container" style="background-color:#e0a3a3;padding:8px;">
  <ul class="nav nav-pills nav-justified">
    <li <?php if(isset($_GET['Type']) && $_GET['Type']=="FD") echo'class="active"';?>>
      <a href="View_AC?Type=FD">Fixed Deposits</a>
    </li>
    <li <?php if(isset($_GET['Type']) && $_GET['Type']=="Loan") echo'class="active"';?>>
      <a href="View_AC?Type=Loan">Loan A/C</a>
    </li>
    <li <?php if(isset($_GET['Type']) && $_GET['Type']=="Closed-Acc") echo'class="active"';?>>
      <a href="View_AC?Type=Closed-Acc">Closed Loan</a>
    </li>
    <li <?php if(isset($_GET['Type']) && $_GET['Type']=="Recurring") echo'class="active"';?>>
      <a href="View_AC?Type=Recurring">Recurring A/Cs</a>
    </li>
    <li <?php if(isset($_GET['Type']) && $_GET['Type']=="Matured-Recurring") echo'class="active"';?>>
      <a href="View_AC?Type=Matured-Recurring">Matured Recurring</a>
    </li>
  </ul>
</div>

<?php
    function countCycles($cycle, $createDate, $totalInstallment, $accountType) {
      $today = new DateTime();
      $startDate = new DateTime($createDate);
      
      $cycle = strtoupper(trim($cycle));

      if ($cycle === "D") {
          // দৈনিক চক্র: ক্রিয়েশন ডেট থেকেই শুরু
          if($accountType === 'Recurring'){
              $firstPaymentDate = clone $startDate; // সেই দিনই শুরু
          } elseif($accountType === 'Loan') {
              $firstPaymentDate = (clone $startDate)->modify('+1 day'); // পরের দিন থেকে
          }
          
          if ($firstPaymentDate > $today) {
              $count = 0;
          } else {
              $diff = $firstPaymentDate->diff($today);
              $count = $diff->days + 1; // +1 because diff->days doesn't include start day
          }
      } elseif ($cycle === "W") {
          if($accountType === 'Recurring'){
              $firstPaymentDate = clone $startDate;
          }elseif($accountType === 'Loan'){
              // সাপ্তাহিক চক্র: ৭ দিন পরে প্রথম EMI
              $firstPaymentDate = (clone $startDate)->modify('+7 days');
          }
          
          if ($firstPaymentDate > $today) {
              $count = 0;
          } else {
              $diff = $firstPaymentDate->diff($today);
              $count = floor($diff->days / 7) + 1;
          }
      } elseif ($cycle === "M") {
          if($accountType === 'Recurring'){
              $firstPaymentDate = clone $startDate;
          }elseif($accountType === 'Loan'){
              // মাসিক চক্র: পরের মাসের同一天 প্রথম EMI
              $firstPaymentDate = (clone $startDate)->modify('+1 month');
          }
          
          
          // যদি পরের মাসে同一天 না থাকে (যেমন 31st Jan থেকে 28/29th Feb)
          if ($firstPaymentDate->format('d') != $startDate->format('d')) {
              $firstPaymentDate->modify('last day of this month');
          }
          
          if ($firstPaymentDate > $today) {
              $count = 0;
          } else {
              $count = 1; // প্রথম EMI already due
              $nextPaymentDate = clone $firstPaymentDate;
              
              // পরের মাসগুলির জন্য গণনা
              while ($nextPaymentDate <= $today) {
                  $nextPaymentDate->modify('+1 month');
                  
                  // তারিখ adjust করাが必要 হলে
                  if ($nextPaymentDate->format('d') != $firstPaymentDate->format('d')) {
                      $nextPaymentDate->modify('last day of this month');
                  }
                  
                  if ($nextPaymentDate <= $today) {
                      $count++;
                  }
              }
          }
      } else {
          $count = 0;
      }

      return min($count, $totalInstallment);
  }
function view_list_ac($type) {
  echo '
    <div class="container" style="margin-top: 70px;">
    <h5>VIEW CUSTOMERS</h5><hr>
    </div>
    <div style="padding: 0 15px; overflow-x: scroll;">
    <table class="table table-striped table-bordered table-hover table-responsive" style="overflow-x: scroll;">
      <tr>
        <th>SL</th>
        <th>Type</th>';
        if ($_SESSION['type'] === 'admin') {
            echo '<th>Agent</th>';
        }
        if(isset($_GET['Type']) && $_GET['Type']=="Recurring" || $_GET['Type']=="Matured-Recurring"){
          echo '
            <th>AC No</th>
            <th>Name</th>
            <th>Account Creation Date</th>
            <th>Maturity Amount</th>
            <th>PHONE</th>
            <th>Balance</th>
            <th>Total Installment</th>
            <th>Paid Installment</th>
            <th>Deu Installment Till Date</th>
            <th>Installment Amount</th>
            <th>Due Amount</th>
          </tr>';
        }elseif(isset($_GET['Type']) && $_GET['Type']=="Loan" || $_GET['Type']=="Closed-Acc"){
            echo '
            <th>AC No</th>
            <th>Name</th>
            <th>Account Creation Date</th>
            <th>Loan Amount</th>
            <th>PHONE</th>
            <th>Balance</th>
            <th>Total EMI</th>
            <th>Paid EMI</th>
            <th>Deu EMI Till Date</th>
            <th>EMI Amount</th>
            <th>Due Amount</th>
          </tr>';
        }


        
  // <th>Due after Fine</th>
  $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }
  
  // Build SQL query based on user type and account type
  if($_SESSION['type'] === 'agent') {
    if($type === 'Closed-Acc') {
      // Only Closed Loan
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='Loan' AND `STATUS`='closed' AND `AA_AGENT`='".$_SESSION['user_id']."' ORDER BY `AA_ID` DESC";
    } elseif($type === 'Matured-Recurring') {
      // Only Matured Recurring
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='Recurring' AND `STATUS`='matured' AND `AA_AGENT`='".$_SESSION['user_id']."' ORDER BY `AA_ID` DESC";
    } elseif($type === 'Loan') {
      // Loan except Closed (include NULL)
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='Loan' AND (`STATUS` IS NULL OR `STATUS`!='closed') AND `AA_AGENT`='".$_SESSION['user_id']."' ORDER BY `AA_ID` DESC";
    } elseif($type === 'Recurring') {
      // Recurring except Matured (include NULL)
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='Recurring' AND (`STATUS` IS NULL OR `STATUS`!='matured') AND `AA_AGENT`='".$_SESSION['user_id']."' ORDER BY `AA_ID` DESC";
    } else {
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='".$type."' AND `AA_AGENT`='".$_SESSION['user_id']."' ORDER BY `AA_ID` DESC";
    }
  } elseif($_SESSION['type'] === 'admin' || $_SESSION['type'] === 'bm') {
    if($type === 'Closed-Acc') {
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='Loan' AND `STATUS`='closed' ORDER BY `AA_ID` DESC";
    } elseif($type === 'Matured-Recurring') {
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='Recurring' AND `STATUS`='matured' ORDER BY `AA_ID` DESC";
    } elseif($type === 'Loan') {
      // Loan except Closed (include NULL)
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='Loan' AND (`STATUS` IS NULL OR `STATUS`!='closed') ORDER BY `AA_ID` DESC";
    } elseif($type === 'Recurring') {
      // Recurring except Matured (include NULL)
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='Recurring' AND (`STATUS` IS NULL OR `STATUS`!='matured') ORDER BY `AA_ID` DESC";
    } else {
      $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='".$type."' ORDER BY `AA_ID` DESC";
    }
  }

  
  $result = $conn->query($sql);

  if ($result->num_rows > 0) {
      while($row = $result->fetch_assoc()) {
          $tt = $row["AA_ID"] - 10;
          $date1 = date_create($row["AA_DATE"]);
          $date2 = date_create(date("Y/m/d"));
          $diff = date_diff($date1, $date2);

          if($type === 'Loan') {
            $no_paid_inst = ($row["AA_MATURE_VALUE"] + $row["AA_BAL"]) / $row["AA_INSTALLMENT"];
          } else {
            $no_paid_inst = $row["AA_BAL"] / $row["AA_INSTALLMENT"];
          }
          
          if ($row["AA_ACTYPE"] == 'D') {
            $diff = $diff->format("%a"); 
            $diff = (int)$diff;
            $due_i = $diff - $no_paid_inst;
          } else {
            $diff = $diff->format("%m"); 
            $diff = (int)$diff;
            $due_i = $diff - $no_paid_inst;
          }
          
          if($row['AA_TYPE'] === 'Loan'){
                $paidInstallment = ($row['AA_MATURE_VALUE'] + $row['AA_BAL']) / $row['AA_INSTALLMENT'];
                $paidInstallment = number_format($paidInstallment, 2, '.', '');
                
                $deuEMITillDate = countCycles($row['AA_ACTYPE'], $row['AA_DATE'], $row['AA_NO_OF_PAYMENT'], $row['AA_TYPE']) - $paidInstallment;
                // $deuEMITillDate = abs($deuEMITillDate);
                $deuEMITillDate = number_format($deuEMITillDate, 2, '.', '');

                $totalDEUEMI = $row['AA_BAL'] / $row['AA_INSTALLMENT'];
                $totalDEUEMI = number_format($totalDEUEMI, 2, '.', '');

                

            }elseif($row['AA_TYPE'] === 'Recurring'){
                $paidInstallment = $row['AA_BAL'] / $row['AA_INSTALLMENT'];
                $paidInstallment = number_format($paidInstallment, 2, '.', '');

                $deuEMITillDate = countCycles($row['AA_ACTYPE'], $row['AA_DATE'], $row['AA_NO_OF_PAYMENT'], $row['AA_TYPE']) - $paidInstallment;
                // $deuEMITillDate = abs($deuEMITillDate);
                $deuEMITillDate = number_format($deuEMITillDate, 2, '.', '');

                // $totalDEUEMI = ($row["AA_MATURE_VALUE"] - $row['AA_BAL']) / $row['AA_INSTALLMENT'];
                $totalDEUEMI = $row["AA_NO_OF_PAYMENT"] - $paidInstallment;
                $totalDEUEMI = number_format($totalDEUEMI, 2, '.', '');

            }
          $totalDeuAmount = $totalDEUEMI * $row["AA_INSTALLMENT"];
          
          echo "<tr>
                  <td>".$tt."</td>
                  <td>".$row["AA_ACTYPE"].",".$row["AA_TYPE"]."</td>";
          
          if ($_SESSION['type'] === 'admin') {
              echo "<td>".$row["AA_AGENT"]."</td>";
          }

          echo "<td><a href='./Details?no=".$row["AA_ACNO"]."&type=".$row["AA_TYPE"]."'>".$row["AA_ACNO"]."</a> &nbsp;&nbsp; <a href='./Trans_New?no=".$row["AA_ACNO"]."&type=".$row["AA_TYPE"]."'>Transact</a></td>
          <td>".$row["AA_NAME"]."</td>
          <td>".$row["AA_DATE"]."</td>
          <td>".$row["AA_MATURE_VALUE"]."</td>
          <td>".$row["AA_PHONE"]."</td>
          <td>".$row["AA_BAL"]. "</td>
          <td>".$row["AA_NO_OF_PAYMENT"]."</td>
          <td>".$paidInstallment."</td>
          <td>".$deuEMITillDate."</td>
          <td>".$row["AA_INSTALLMENT"]."</td>";
          if($row["AA_TYPE"] === 'Recurring'){
            echo "<td class='".($totalDeuAmount > 0 ? "alert danger text-danger" : "alert success text-success")."'>".($totalDeuAmount > 0 ? $totalDeuAmount : "All Clear")."</td>";
          }elseif($row["AA_TYPE"] === 'Loan'){
            echo "<td class='".($totalDeuAmount >= 0 ? "alert success text-success" : "alert danger text-danger")."'>".($totalDeuAmount < 0 ? $totalDeuAmount : "All Clear")."</td>";
          }
      

                  // $totalDeuAmount
          
          // if ($due_i > 0) {
          //   $due_amount = $due_i * $row["AA_INSTALLMENT"];
          //   echo "<td class='alert danger text-danger'>".$due_amount."</td>";
          // } else {
          //   $due_amount = 'All Clear';
          //   echo "<td class='alert success text-success'>".$due_amount."</td>";
          // }
          
          // if ($due_i > 0 && $type == "Recurring") {
          //   $due_amount = $due_i * $row["AA_INSTALLMENT"];
          //   $due_amount = (($due_amount) * 20)/100;
          //   echo "<td class='alert danger text-danger'>".$due_amount."</td>";
          // } elseif ($due_i > 0 && $type == "Loan") {
          //   $due_amount = $due_i * $row["AA_INSTALLMENT"];
          //   $due_amount = (($due_amount) * 40)/100;
          //   echo "<td class='alert danger text-danger'>".$due_amount."</td>";
          // } else {
          //   $due_amount = 'Up to Date!!';
          //   echo "<td class='alert success text-success'>".$due_amount."</td>";
          // }

          echo "</tr>";            
      }
  } else {
      echo "<tr><td colspan='".($_SESSION['type'] === 'admin' ? '15' : '14')."'>0 results</td></tr>";
  }
  $conn->close();

  echo '</table></div>';
}

if(isset($_GET['Type'])) {
  switch($_GET['Type']) {
    case "Loan":
      view_list_ac('Loan');
      break;
    case "Recurring":
      view_list_ac('Recurring');
      break;
    case "Matured-Recurring":
      view_list_ac('Matured-Recurring');
      break;
    case "FD":
      view_list_ac('FD');
      break;
    case "Closed-Acc":
      view_list_ac('Closed-Acc');
      break;
  }
}
?>
