<?php
include("db/cn.php");
include("common/tx.php");
ob_start();

if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

if ($_GET) {
    if (isset($_GET["cr_name"])) {
        $id = $_GET["cr_name"];

        // Use prepared statements to prevent SQL injection
        $stmt = $connection->prepare("DELETE FROM credit_note WHERE cr_name = ? AND user_name = ? AND user_role = ? AND outlet_name = ? AND outlet_address = ?");
        $stmt->bind_param("sssss", $id, $userName, $userRole, $outlet_name, $outlet_address);

        if ($stmt->execute()) {
            echo '<script type="text/javascript">window.location.href="view_creditor.php";</script>';
           // header("Location: credits.php");
            exit();
        } else {
            echo "Error: " . $stmt->error;
        }
        
        $stmt->close();
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["creditor"])) {
    $date_time32 = date("Y-m-d");
    $cr_name = $_POST["cr_name"];
    $cr_nickname = $_POST["cr_nickname"];
    $cr_address = $_POST["cr_address"];
    $phone_number = $_POST["phone_number"];
    $cr_id = $_POST["cr_id"];

    // Use prepared statements to prevent SQL injection
    $stmt = $connection->prepare("INSERT INTO credit_note (cr_name, cr_nickname, cr_address, phone_number, cr_id, user_name, user_role, outlet_name, outlet_address, date_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssss", $cr_name, $cr_nickname, $cr_address, $phone_number, $cr_id, $userName, $userRole, $outlet_name, $outlet_address, $date_time32);

    if ($stmt->execute()) {
         echo '<script type="text/javascript">window.location.href="credits.php";</script>';
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}
ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title><?php echo $tx; ?></title>

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
   <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
        <link href="../css/sb-admin-2.css" rel="stylesheet">
<!--<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>-->
</head>
<style>
body {
    font-family: 'Quicksand', sans-serif;
    
}
		    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
.bg-gradient-primary{
    
	background:#0A4657;
	color:#fff;	
	
	}

.btn-primary{
	background:#0A4657;
	color:#fff;
	 border:1px #0A4657 solid;
	
	}  
.btn-primary:hover{
  
  background:#fff;
  border:1px #0A4657 solid;
	color:#0A4657;
	
	}	 
    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
	
	.fa-download:hover{
		color:#953E39;
		}
		
 /* Custom styles for search bar */
    .search-container {
        display: flex;
        align-items: center;
       width:100%;
        margin: 2px auto;
        float:left;
	}

/* Updated hide class to apply to the overlay */
.sidebar.hide, .overlay.hide {
    transform: translateX(-100%);
}

    .search-input {
        width: 100%;
        padding: 10px 30px 10px 10px;
        /* Adjust padding to accommodate the icon */
        border: 1px solid #ccc;
        border-radius: 20px;
        font-size: 16px;
    }

    .search-icon {
        position: relative;
        left: -25px;
        /* Adjust the position of the icon */
        color: #aaa;
    }

    .search-icon i {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }
    tr{
        font-weight:700;
        background:#fff;
        
    }
    
  </style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php
        include("common/sd.php");
		?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>

                    <!-- Topbar Search -->
                    
  <?php include('common/log.php');  ?>

                    <!-- Topbar Navbar -->
                    
                </nav>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
  <?php
// Query: join creditor_closing and credit_note by matching creditor_name = cr_name
$query = "
    SELECT cc.creditor_name, cc.remain_balance
    FROM creditor_closing cc
    JOIN credit_note cn ON cn.cr_name = cc.creditor_name
";

$result = mysqli_query($connection, $query);
if (!$result) {
    die('Query Failed: ' . mysqli_error($connection));
}

$total_sum = 0;
?>  
<div class="container">
            <div class="row">
                <div class="col-sm-9">
                    <h3 style="color:#212529; font-weight:700;">
                        Customer Ledger</h3>
                   
                        <div class="search-container">
                        <input type="text" id="searchInput" class="form-control" placeholder="Search..." style="width:305px;">
                            
                            <div class="search-icon">
                                <i class="fas fa-search"></i>
                            </div>
                        </div>
                        
                </div>
                <div class="col-sm-3" style="background:#0A4657;color:#fff; padding:10px; border-radius:7px;">
 <center>
    <?php 
    while ($row = mysqli_fetch_assoc($result)) { 
        $total_sum += $row['remain_balance'];
    ?>
      
    <?php } ?>
  
    <p style="font-weight:700; font-size:20px;">
        Total Receivable<br>Rs <?php echo number_format(round($total_sum, 2), 2); ?>
    </p>
</center>
                </div>
            </div>
   
        </div>
   
        <div class="container-fluid">
            <div class="row">
            <div class="col-sm-1"></div>
                <div class="col-sm-10" style="" id="table-container-wrapper">
                    <div class="row text-center">
                        
                        
                        <table class="table table-hover table-stripped table-sm bg-white">
                        <thead>
                        <tr class="bg-dark text-white text-center">
                        <td>Sr</td>
                        <td>ID</td>
                        <td>Name</td>
                        <td>Cell</td>
                        <td>Closing Balance(Rs)</td>
                        <td>Detail</td>
                        
                        <td>Delete</td>
                        </tr>
                        </thead>
                        <tbody id="supplierTableBody">
<?php 
ob_start();

// Join the credit_note table with the creditor_closing table and retrieve necessary fields
$rec = mysqli_query($connection, 
    "SELECT credit_note.cr_id, credit_note.cr_name, credit_note.phone_number, creditor_closing.remain_balance, creditor_closing.creditor_name 
     FROM credit_note
     LEFT JOIN creditor_closing ON credit_note.cr_name = creditor_closing.creditor_name
     GROUP BY credit_note.cr_name"
);

if (!$rec) {
    die("Error: " . mysqli_error($connection));
}
$sr_no = 1;
while($row = mysqli_fetch_array($rec)) {
    $customerName = $row["cr_name"];
?>
    <tr style=" color:#000;">
    <td><?php echo $sr_no++; ?></td>
        <td style="font-weight:700; color:#300;"><?php echo $row["cr_id"]; ?></td>
        <td class="text-capitalize" style="font-weight:600;"><?php echo $customerName; ?></td>
        <td><?php echo $row["phone_number"]; ?></td>
        <td style="font-weight:500;"><?php echo number_format(round($row["remain_balance"], 2), 2); ?></td>
        <td><a href="creditor_detail.php?customer_name=<?php echo $customerName; ?>"><button type="button" class="btn btn-dark btn-sm"><i class="fas fa-clipboard fa-1x"></i></button></a></td>
        <!--<td><a href="credits_edit.php?cr_name=<?php echo $customerName; ?>"><button type="button" class="btn btn-dark btn-sm">-->
        <!--Edit</button></a></td>-->
        <td>
          <a href="view_creditor.php?cr_name=<?php echo $customerName; ?>" 
             class="delete-btn">
             <button type="button" class="btn btn-danger btn-sm">x</button>
          </a>
        </td>

    </tr>
<?php 
} 
ob_end_flush();
?>
</tbody>
  </table>
                    </div>
                </div>
                <div class="col-sm-1"></div>

                </div>
            </div>
        </div>
            <br><br>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php");  ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

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

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>

      
   <!--<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>-->
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
    var searchInput = document.getElementById('searchInput');
    var rows = document.querySelectorAll("#supplierTableBody tr");

    searchInput.addEventListener("keyup", function(event) {
        var term = event.target.value.toLowerCase();
        rows.forEach(function(row) {
            var cells = row.getElementsByTagName("td");
            var found = false;
            Array.from(cells).forEach(function(cell) {
                if (cell.textContent.toLowerCase().indexOf(term) > -1) {
                    found = true;
                }
            });
            if (found) {
                row.style.display = "";
            } else {
                row.style.display = "none";
            }
        });
    });
});

</script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    // ✅ Search bar ka code
    var searchInput = document.getElementById('searchInput');
    var rows = document.querySelectorAll("#supplierTableBody tr");

    searchInput.addEventListener("keyup", function(event) {
        var term = event.target.value.toLowerCase();
        rows.forEach(function(row) {
            var cells = row.getElementsByTagName("td");
            var found = false;
            Array.from(cells).forEach(function(cell) {
                if (cell.textContent.toLowerCase().indexOf(term) > -1) {
                    found = true;
                }
            });
            row.style.display = found ? "" : "none";
        });
    });

    // ✅ Delete button confirmation
    document.querySelectorAll(".delete-btn").forEach(function(button) {
        button.addEventListener("click", function(e) {
            e.preventDefault(); // Stop direct redirect
            var link = this.getAttribute("href"); // Get delete link

            Swal.fire({
                title: "Are you sure?",
                text: "You want to delete the Ledger!",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#d33",
                cancelButtonColor: "#3085d6",
                confirmButtonText: "Yes, delete it!",
                cancelButtonText: "Cancel"
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = link; // Proceed with delete
                }
            });
        });
    });
});
</script>

</body>

</html>