<?php
include("db/cn.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

//session_start();

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

$customer_name = isset($_GET['school_name']) ? trim($_GET['school_name']) : '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $school_name = $customer_name;
    $class_name = $_POST['class_name'];
    $course_names = $_POST['course_name'] ?? [];
    $rack_numbers = $_POST['rack_number'] ?? [];
    $companies = $_POST['company'] ?? [];
    $publishers = $_POST['publisher'] ?? [];
    $trade_prices = $_POST['trade_price'] ?? [];
    $prices = $_POST['price'] ?? [];
    $percentages = $_POST['percentage'] ?? [];
    $per_amounts = $_POST['per_amount'] ?? [];

    // Validate all input fields
    $totalCourses = count($course_names);
    if (
        !empty($school_name) && 
        !empty($class_name) && 
        $totalCourses > 0 &&
        $totalCourses === count($rack_numbers) &&
        $totalCourses === count($companies) &&
        $totalCourses === count($publishers) &&
        $totalCourses === count($trade_prices) &&
        $totalCourses === count($prices) &&
        $totalCourses === count($percentages) &&
        $totalCourses === count($per_amounts)
    ) {
        // Validation for trade_price and other numeric fields
        foreach ($trade_prices as $price) {
            if (!is_numeric($price) || $price < 0) {
                echo "Invalid trade price value detected.";
                exit;
            }
        }

        $courseStmt = $connection->prepare(
            "INSERT INTO courses (school_name, class_name, course_name, rack_number, company, publisher, trade_price, price, percentage, per_amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        );

        if ($courseStmt === false) {
            die("Error preparing statement: " . $connection->error);
        }

        foreach ($course_names as $index => $course_name) {
            $rack_number = $rack_numbers[$index];
            $company = $companies[$index];
            $publisher = $publishers[$index];
            $trade_price = $trade_prices[$index];
            $price = $prices[$index];
            $percentage = $percentages[$index];
            $per_amount = $per_amounts[$index];

            $courseStmt->bind_param(
                "ssssssssss", // Corrected type specifiers
                $school_name,
                $class_name,
                $course_name,
                $rack_number,
                $company,
                $publisher,
                $trade_price,
                $price,
                $percentage,
                $per_amount
            );

            if (!$courseStmt->execute()) {
                echo "Error executing statement: " . $courseStmt->error;
                exit;
            }
        }

        echo "Courses added successfully for school: " . htmlspecialchars($school_name);
    } else {
        echo "Please fill in all fields and ensure course details are consistent.";
    }
}
?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Courses - Detail</title>
    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="css/custom_css.css" />


</head>

<style>
 #table-container-wrapper {
    max-height: 400px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
/* Custom styles for sidebar */    /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
        background: linear-gradient(360deg, #060606, #3C2F23);
        position: fixed;
        bottom: 0;
        top: 60px;
        transition: transform 0.3s ease-in-out;
        transform: translateX(0);
        z-index: 1;
        height: 100%;
        border-radius: 0px;
		   transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
    }.sidebar.hide {
      transform: translateX(-100px); /* Move sidebar out of the viewport when it is hidden */
    }
      .sidebar .nav-item {
    padding: 10px 0 ;
    text-align: center;
    position: relative;
	font-size:12px;
}
    .sidebar .nav-link {
      color: #fff;
      position: relative; /* Ensure icon and text are positioned relative to the nav link */
      z-index: 2; /* Ensure the text and icon are above the hover background */
    }
    .sidebar .nav-link i {
      margin-bottom: 5px; /* Adjust the margin of the icon */
    }
    /* Custom styles for hover effect */
    .sidebar .nav-item:hover:after {
      background-color: #fff;
      content: '';
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      z-index: 1; /* Ensure the hover background is below the text and icon */
    }
    .sidebar .nav-item:hover .nav-link {
      color: #503F2E;
    }
    /* Custom styles for divider */
    .sidebar .nav-item:after {
      content: "";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 1px;
      background-color: #fff;
      transition: height 0.3s ease-in-out; /* Transition effect for smooth animation */
    }
    /* Custom styles for header */ 
	   .header {
        background: linear-gradient(270deg, #060606, #3C2F23);
        color: #fff;
        padding: 10px;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 2;
        height: 69px;
        box-shadow: #FFF 2px 0px 0px 0px;
        /* Ensure header appears above sidebar */
    }
    .header .navbar-toggler {
      color: #fff;
    }
    .header .navbar-toggler-icon {
      color: #fff; /* Set the color of the toggle button to white */
    }
    .header .navbar-toggler.white {
      color: #fff !important; /* Ensure the toggle button is white */
    }
    .header .navbar-brand {
      color: #fff; /* Set navbar brand text color to white */
    }
    .header .nav-item .nav-link {
      color: #fff; /* Set nav link text color to white */
    }
    .main-content {
      margin-top: 50px; /* Height of fixed header + padding */
      margin-left: 100px; /* Width of sidebar */
      padding-top: 30px; /* Height of fixed header */
    }
	/* Custom styles for search bar */
    .search-container {
      display: flex;
      align-items: center;
      width: 300px;
      margin: 2px auto;
    }
    .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%);
    }
.btn-dark
         {
			 background:#503F2E;
			 color:#fff;
			 border: 1px solid #503F2E;
                 	}
		.btn-dark:hover{
			background:#fff;
			 color:#503F2E;
			 border:1px solid #503F2E;
			}	
			.bg-dark2{
			background:#503F2E;
			color:#fff;	
				}	
	
	 .modal-content {
            animation: modal-animation 0.5s;
        }

        @keyframes modal-animation {
            from {
                opacity: 0;
                transform: scale(0.8);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }
		
		/* Basic styling */
    .tab {
        display: none;
        padding: 20px;
    }
    .active {
        display: block;
    }
    .tab-buttons {
        display: flex;
    }
    .tab-button {
        cursor: pointer;
        padding: 10px 10px;
        background-color: #ffff;
        border: 1px solid #0A5064;
        border-radius: 5px 5px 0 0;
        margin-right: 5px;
		color:#212529;
    }
    .tab-button.active {
        background-color: #212529;
		color:#fff;
    }

    /* Background colors for tab content */
    #tab1 {
        background-color: #fff;
		color:#212529;
		padding:20px;
    }
    #tab2 {
        color:#212529;
		background-color: ;
    }
    #tab3 {
		color:#212529;
        background-color: ;
    }
</style>

<body>

<?php include("common/hd.php");?>
<!-- Sidebar -->
<?php include("common/sd.php"); ?>
<div class="main-content">
<br />
<div class="container">
    <div class="row">
        <div class="col-sm-4">
            <h3 class="mb-2 mt-2">Courses Detail</h3>
            
        </div>
        <div class="col-sm-5"></div>
        <div class="col-sm-3">
            <h3 style="background:#060606; padding:20px; border-radius:10px;font-size:18px; color:#fff; font-weight:600; text-align:center;"><?php echo $customer_name; ?></h3>
            
        </div>
        
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-sm-9">
            <?php
            $rec = mysqli_query($connection,"select * from courses where school_name = '$customer_name' GROUP BY class_name ");
            ?>
            <table class="table table-bordered table-hover text-center text-uppercase">
                <tr class="bg-dark text-white">
                    <th>Sr#</th>
                    <th>Class Name</th>
                    <th>View</th>
                    <th>Edit</th>
                    <th>Sale</th>
                </tr>
                <?php 
                $sr_no = 1;
                while($row = mysqli_fetch_array($rec)){
                ?>
                <tr>
                    <td><?php echo $sr_no++; ?></td>
                    <td><?php echo $row["class_name"]; ?></td>
                    <td><a href="view_course.php?class_name=<?php echo $row["class_name"]; ?>&&school_name=<?php echo $customer_name;?>"><button type="button" class="btn btn-dark btn-sm">View</button></a></td>
                    <td><a href="edit_course.php?class_name=<?php echo $row["class_name"]; ?>&&school_name=<?php echo $customer_name;?>"><button type="button" class="btn btn-dark btn-sm">Edit</button></a></td>
                    <td><a href="sale_course.php?class_name=<?php echo $row["class_name"]; ?>&&school_name=<?php echo $customer_name;?>"><button class="btn btn-dark btn-sm">Sale</button></a></td>
                </tr>
                <?php
                }
                ?>
            </table>
            
            
        </div>
        <div class="col-sm-3">
            <button type="button" class="btn btn-dark" data-toggle="modal" data-target="#addCoursesModal">
                Add Courses for a School
            </button>
            <br>
            <a href="course.php"><button type="button" class="btn btn-dark btn-sm" style="margin-top:10px;">Back</button></a>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="addCoursesModal" tabindex="-1" aria-labelledby="addCoursesModalLabel" aria-hidden="true" style="">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addCoursesModalLabel">Add Courses for a School</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form action="course_detail.php?school_name=<?php echo $customer_name; ?>" method="post" id="courseForm" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="school_name">School Name:</label>
                            <select class="form-control" id="school_name" name="school_name" required style="width:304px;">
                                <option value="<?php echo $customer_name; ?>"><?php echo $customer_name; ?></option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="school_name">Class Name:</label>
                            <input type="text" class="form-control" id="class_name" name="class_name" required style="width:304px;">
                                
                        </div>

                        <h5>Course Details</h5>
                            <table class="table" id="courseTable" style="width:700px;">
                                <thead>
                                    <tr>
                                        <th>Course Name</th>
                                        
                                        <th>Company</th>
                                        <th>Supplier</th>
                                        <th>Trade Price</th>
                                        <th>Price(Rs)</th>
                                        <th>Percentage</th>
                                        <th>% Amount</th>
                                        <th>Rack Number</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Dynamic rows will be added here -->
                                </tbody>
                            </table>
                            <button type="button" class="btn btn-success" id="addCourseRow">Add Course</button>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary" form="courseForm">Save Courses</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>

</div>    
</body>
<script>
   document.addEventListener("DOMContentLoaded", function () {
    const addCourseRowButton = document.getElementById("addCourseRow");
    const courseTableBody = document.querySelector("#courseTable tbody");

    // Add a new row when clicking the Add Course button
    if (addCourseRowButton) {
        addCourseRowButton.addEventListener("click", function () {
            const newRow = document.createElement("tr");

            newRow.innerHTML = `
                <td><input type="text" name="course_name[]" class="form-control" required placeholder="Course Name"></td>
                <td><input type="text" name="company[]" class="form-control" required placeholder="Company"></td>
                <td><input type="text" name="publisher[]" class="form-control" required placeholder="Supplier"></td>
                <td><input type="text" name="trade_price[]" class="form-control" required placeholder="Trade Price"></td>
                <td><input type="number" name="price[]" class="form-control price" required placeholder="Price"></td>
                <td><input type="number" name="percentage[]" class="form-control percentage" required placeholder="Percentage"></td>
                <td><input type="number" name="per_amount[]" class="form-control per_amount" readonly placeholder="Amount"></td>
                <td><input type="text" name="rack_number[]" class="form-control" required placeholder="Rack No"></td>
                <td><button type="button" class="btn btn-danger removeCourseRow">x</button></td>
            `;

            courseTableBody.appendChild(newRow);
        });
    }

    // Add event delegation to handle dynamic percentage calculations
    courseTableBody.addEventListener("input", function (event) {
        if (event.target.classList.contains("percentage") || event.target.classList.contains("price")) {
            const row = event.target.closest("tr");
            const priceInput = row.querySelector(".price");
            const percentageInput = row.querySelector(".percentage");
            const amountInput = row.querySelector(".per_amount");

            const price = parseFloat(priceInput.value) || 0;
            const percentage = parseFloat(percentageInput.value) || 0;

            // Calculate the percentage amount
            const amount = (price * percentage) / 100;

            // Update the % Amount field
            amountInput.value = amount.toFixed(2);
        }
    });

    // Add event delegation to handle removing rows
    courseTableBody.addEventListener("click", function (event) {
        if (event.target && event.target.classList.contains("removeCourseRow")) {
            const rowToRemove = event.target.closest("tr");
            if (rowToRemove) {
                courseTableBody.removeChild(rowToRemove);
            }
        }
    });
});

</script>
<script>
 // Function to switch between tabs
    function openTab(evt, tabName) {
        // Get all elements with class="tab" and hide them
        var tabs = document.getElementsByClassName("tab");
        for (var i = 0; i < tabs.length; i++) {
            tabs[i].style.display = "none";
        }

        // Get all elements with class="tab-button" and remove the class "active"
        var tabButtons = document.getElementsByClassName("tab-button");
        for (var i = 0; i < tabButtons.length; i++) {
            tabButtons[i].classList.remove("active");
        }

        // Show the current tab, and add an "active" class to the button that opened the tab
        document.getElementById(tabName).style.display = "block";
        evt.currentTarget.classList.add("active");
    }
  document.addEventListener("DOMContentLoaded", function () {
    var sidebar = document.getElementById("sidebar");
    var overlay = document.createElement("div");
    overlay.classList.add("overlay");
    document.body.appendChild(overlay);

    function toggleSidebar() {
        sidebar.classList.toggle("hide");
        overlay.classList.toggle("hide");

        var mainContent = document.querySelector(".main-content");
        if (sidebar.classList.contains("hide")) {
            mainContent.style.marginLeft = "0";
        } else {
            mainContent.style.marginLeft = "100px"; // Width of the sidebar
        }
    }

    overlay.addEventListener("click", function () {
        toggleSidebar();
    });

    // Add toggle functionality to navbar toggler
    var navbarToggler = document.querySelector(".navbar-toggler");
    navbarToggler.addEventListener("click", function () {
        toggleSidebar();
    });

    // Automatically hide sidebar on all screen sizes
    // sidebar.classList.add("hide");
    // overlay.classList.add("hide");
    
    // Add class to body to prevent scrolling when sidebar is open
    // document.body.classList.add("noscroll");

    // Check if screen size is larger than a certain threshold (e.g., 768px for desktop screens)
    function checkScreenSize() {
        if (window.innerWidth > 768) {
            sidebar.classList.remove("hide");
            overlay.classList.remove("hide");
        } else {
            sidebar.classList.add("hide");
            overlay.classList.add("hide");
        }
    }

    // Check screen size on initial load and whenever the window is resized
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
});
 
	</script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</html>