<?php include "includes/header.php";?>

<?php include "includes/navbar.php";?>

  <div id="wrapper">

    <!-- Sidebar -->
   <?php include "includes/sidebar.php";?>

    <div id="content-wrapper">

      <div class="container-fluid">

        <!-- Breadcrumbs-->
        <ol class="breadcrumb">
          <li class="breadcrumb-item">
            <a href="#">Ola</a>
          </li>
          <li class="breadcrumb-item active"><?php echo $_SESSION['nome'];?></li>
        </ol>

        <!-- Icon Cards-->
        <div class="row">
       
	
	   <div class="container">

       </div></div>
<hr>
<?php
if(isset($_GET['cliente']) && !empty($_GET['cliente'])){
       
    $cliente = $_GET['cliente'];
  
}
            
        ?>
            

       <h5><i class="fa fa-shopping-cart" aria-hidden="true"></i>Plano de amortização de <font color='red'><?php echo $cliente;?></font></h5>
        
      
        <table class="table">
             <thead>
                <tr>
                    <th>Prestação</th>
                    <th>Capital</th>
                    <th>Juros de capital</th>
                    <th>Total</th>
                    <th>Previsão</th>
                    <th>Alerta</th>
                    <th>Dias em atraso</th>
                     <th>Juros de mora</th>
                      <th>Pagar</th>
                </tr>
            </thead>
            <tbody>   
            <?php 
     if(isset($_GET['id']) && !empty($_GET['id'])){
       $id = $_GET['id'];
        $customer = $database->query("SELECT * FROM creditos WHERE id='$id'");
        while($row = $database->fetch_assoc($customer)){

            $cliente = $row['cliente'];
            $prestacao = $row['prestacoes'];
            $capital = $row['valor'];
            $juros = $row['juros'];
            $taxas = $row['taxas'];

            $tipo_pay = $row['tipo_pagamento'];

            $data_previsao = $row['data'];
            $tipo_credito = $row['tipo'];

          $totalLoan = $row['total'];
          
          $estado = $row['status'];


            $buscarMora = $database->query("SELECT * FROM tipos_creditos WHERE tipo_credito = '$tipo_credito'");
            $findTax = $database->fetch_assoc($buscarMora);
             
            //$juros_de_mora = $findTax['juros_de_mora'];
            
            $novo_credito = $capital + $juros;
            $novo_juro = $novo_credito * $taxas;
            $total2 = $novo_credito + $novo_juro;
            

               if($tipo_credito =="Diario"){
                $numero_dias  = 1;
               }elseif($tipo_credito =="Semanal"){
                $numero_dias  = 7;
               }elseif($tipo_credito == "Mensal"){
                $numero_dias = 30;
               }elseif($tipo_credito == "Quinzenal"){
                $numero_dias = 15;
               }else{
                $numero_dias = 0;
               }

	  



          

                $Dias = "30";
               
                $date = new DateTime($data_previsao);
                 $date->modify('+' .$Dias. 'day');
                 $mudanca_frente_1 = $date->format('Y-m-d');
 
                 $nova_data = $mudanca_frente_1;

                 $now = date('Y-m-d');

                //ACTUALIZAR CREDITOS APOS VENCIMENTO DA DATA DA PRESTACAO.

                  if($now > $nova_data){
                  $url = "creditos.php";
                  $message = "Prestação vencida no dia $nova_data, a recapitalizar o crédito...";
                  echo "<script>window.open('alertas/alertas_bad.php?url={$url}&&message={$message}','_self')</script>";

                  if($updateCredito = $database->query("UPDATE creditos SET valor ='$novo_credito',v_prest='$total2',
                  juros='$novo_juro',total='$total2',data='$now' WHERE id='$id'")){
                    $url2 = "creditos.php";
                    $message2 = "Credito recapitalizado.";
                    echo "<script>window.open('alertas/alertas_good.php?url={$url2}&&message={$message2}','_self')</script>";
                  }
                 }


                 $date1=date_create($nova_data);
                   $date2=date_create($now);
                  $diff=date_diff($date1,$date2);
                  
                   if($date2 > $date1){
                    $diasAtraso = $diff->format("%a");
                $moraTotal = $totalLoan / 30 * ($diasAtraso);


                        }else{
                             $diasAtraso =0;
                             $moraTotal=0;

                         }
            $totalLoanPlusmoraTotal =  $totalLoan + $moraTotal;


     ?>
           <tr>
            <td>1</td>
            <td><?php echo number_format($capital,2,",",".");?></td>
            <td><?php echo number_format($juros,2,",",".");?></td>
            <td><?php echo number_format($totalLoan,2,",",".");?></td>
            <td><?php echo $nova_data;?></td>
  <td>
<?php
    $dataAtual = new DateTime();
    $dataPrevista = new DateTime($nova_data);
    $intervalo = $dataAtual->diff($dataPrevista);
    $diasRestantes = (int)$intervalo->format('%r%a'); // %r mantém sinal negativo

    if ($diasRestantes < 0) {
        // Crédito vencido
        echo '<span class="alert-sinal vermelho piscar">🔴 Vencido</span>';
    } elseif ($diasRestantes <= 5) {
        // 5 dias ou menos para o vencimento
        echo '<span class="alert-sinal amarelo piscar">🟡 ' . $diasRestantes . ' dias restantes</span>';
    } else {
        // Dentro do prazo
        echo '<span class="alert-sinal verde">🟢 ' . $diasRestantes . ' dias restantes</span>';
    }
?>
</td>


            
            
        
           




             <td><?php echo $diasAtraso;?></td>
            <td><?php echo number_format($moraTotal,2,",",".");?></td>
            <?php
            if($estado =='Pago'){
                echo "<td><font color='red'>N/A</font></td>";
            }else{
            ?>
            
  <td><button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#exampleModalLong1<?php echo $id;?>">
  <span><i class="fa fa-coins" aria-hidden="true"></i></span>
</button></td>
         
          

<!-- Modal -->
<div class="modal fade" id="exampleModalLong1<?php echo $id;?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Total da prestação por pagar: <font color="red"><?php echo $totalLoanPlusmoraTotal;?></font></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="container">
            <div class="col-sm-8">
                <form action="loanValidation.php" method="post">
                    <div class="form-group">
                        <label for="valor">Valor</label>
                        <input type="number" class="form-control" name="valor" value="<?php echo $totalLoanPlusmoraTotal;?>" required/>
                    </div>
                    <div class="form-group">
                        <label for="conta">Conta capital</label>
                        <select required name="conta" class="form-control">
                            <option></option>
                            <?php selectConta();?>
                        </select>
                    </div>
                    <input type="hidden" name="valorMulta" value="<?php echo $totalLoanPlusmoraTotal;?>"/>
                    <input type="hidden" name="id" value="<?php echo $id;?>"/>
                    <input type="hidden" name="juros_de_mora" value="<?php echo $moraTotal;?>"/>
                    <div class="form-group">
                        <button type="submit" name="payLoan" class="btn btn-primary btn-sm"><span>Pagar</span></button>
                    </div>
                </form>
            </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancelar</button>
      </div>
    </div>
  </div>
</div>
<?php } ?>
           </tr>
        
           
     <?php 
     
    }
    }?>  
            </tbody>
        </table>
        
        <hr>
        <h3><center>Lista de pagamentos</center></h3>
        <table class="table">
          <thead>
            <tr>
              <th>item</th>
              <th>Nome do cliente</th>
              <th>Valor pago</th>
              <th>Data</th>
              <th>Recibo</th>
            </tr>
          </thead>
          <tbody>
            <?php 
            $item=1;
            $sql = $database->query("SELECT * FROM pagamentos WHERE nome_cliente='$cliente'");
            while($payments = $database->fetch_assoc($sql)){
            ?>
            <tr>
              <td><?php echo $item++;?></td>
              <td><?php echo $payments['nome_cliente'];?> </td>
              <td><?php echo number_format($payments['valor_pago'],2,",",".");?> </td>
              <td><?php echo $payments['data'];?> </td>
              
              <?php if($estado =="Pago"){?>
              <td><button type="button" class="btn btn-info btn-sm"><a href="recibo.php?id=<?php echo $payments['id'];?>" target="_blank" style="text-decoration:none;color:white;"><span>Recibo</span></a></button></td>
             <?php }else{?>
            <td><button type="button" class="btn btn-warning btn-sm"><a href="reciboParcial.php?id=<?php echo $payments['id'];?>" target="_blank" style="text-decoration:none;color:white;"><span>Recibo parcial</span></a></button></td>

             <?php }?>
             
              </tr>
              <?php }?>
          </tbody>
        </table>
          <button type="button" class="btn btn-info btn-sm"><span><a href="finalizarLoan.php?id=<?=$id;?>" style="text-decoration:none; color:white">Finalizar credito</a></span></button>     

        </div>
       


        

      </div>
      <!-- /.container-fluid -->

      <!-- Sticky Footer -->
      <?php include "includes/footer.php";?>

    </div>
    <!-- /.content-wrapper -->

  </div>
  <!-- /#wrapper -->

  <!-- Scroll to Top Button-->
  <a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
  </a>

  <!-- Logout Modal-->
 <?php include "includes/logout_modal.php";?>
<?php include "includes/sweatscripFooter.php";?>
