<?php
require_once("dbconnection.php");
session_start();

$student_id = $_GET['student_id'];
$cid= $_GET['cid'];

if($_SERVER['REQUEST_METHOD']=="GET")
{
    $q_payemnt="SELECT * FROM payments WHERE s_id ='$student_id' AND c_id = '$cid'";
    $r_payment=$con->query($q_payemnt);
    
    while($row=$r_payment->fetch_array(MYSQLI_ASSOC))
    {
      
       //$total_price= $row['total_price'];
       //$received_amount= $row['received_amount'];
       $end_date= $row['end_date'];
       $p_amount= $row['p_amount'];
       
    }
    
}

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    

    $user_id = $_SESSION['emp_id'];
    $student_id = intval($_GET['student_id']);

    // Get POST data
    
    $receive_amount = $_POST['receive_amount'];
    $borrow_amount = $_POST['borrow_amount'];
    $bill_no = $_POST['bill_no'];
    $cash_id = $_POST['cash_id'];
    $p_status = $_POST['p_status'];
    $date = $_POST['date'];
    $end_date = $_POST['end_date'];

    // 1. Insert into payments
    $q1 = "INSERT INTO loan_r_details (p_received_amount, p_borrow_amount, p_date, bill_no, s_id, cp_id,c_id)
           VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt = $con->prepare($q1);
    $stmt->bind_param("ddsiiii", $receive_amount, $borrow_amount, $date, $bill_no,$student_id,$cash_id,$cid);

    if ($stmt->execute()) {
        // 2. Update loan
        $sqlloan = "UPDATE loan SET total_price = total_price + ?, received_amount = received_amount + ?, borrow_amount = ? WHERE s_id = ? AND c_id = ?";
        $stmt_loan = $con->prepare($sqlloan);
        $stmt_loan->bind_param("dddii", $receive_amount, $receive_amount, $borrow_amount, $student_id,$cid);
        $stmt_loan->execute();

        // 3. Insert into cash_point
        $sqlcashpoint = "INSERT INTO cash_point (cp_id, deposit_amount, details, emp_id, date,bill_no) VALUES (?, ?, ?, ?, ?,?)";
        $stmt_cash = $con->prepare($sqlcashpoint);
        $stmt_cash->bind_param("idiisi", $cash_id,$receive_amount, $cid, $user_id, $date,$bill_no);
        $stmt_cash->execute();

       // 2. Update payments status
        $sqlstatus = "UPDATE payments SET p_status = ? ,end_date = ? WHERE c_id = ?";
        $stmt_status = $con->prepare($sqlstatus);
        $stmt_status->bind_param("ssi", $p_status,$end_date, $cid);
        $stmt_status->execute();

        // Redirect to student details page
        header("Location: print2.php?cid=" . $cid . "&student_id=" . $student_id . "&bill_no=" . $bill_no);
        exit();
    } else {
        echo "Error inserting payment: " . $stmt->error;
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="keywords" content="admin, dashboard">	
	<meta name="robots" content="index, follow">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!-- PAGE TITLE HERE -->
	<title>ثبت نام جدید</title>
	<!-- FAVICONS ICON -->
	<link rel="shortcut icon" type="image/png" href="images/favicon.png">
	
	<link href="vendor/jquery-nice-select/css/nice-select.css" rel="stylesheet">
	<link rel="stylesheet" href="vendor/nouislider/nouislider.min.css">
	<!-- Style css -->
    <link href="css/style.css" rel="stylesheet">
    <link href="vendor/sweetalert2/dist/sweetalert2.min.css" rel="stylesheet">
		<link href="vendor/jquery-nice-select/css/nice-select.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link rel="stylesheet" href="dist/sweetalert.css"> 
    
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
     <script>
  document.addEventListener("keydown", function(event) {
    if (event.key === "Escape") {
      // Use a short delay to ensure smooth behavior
      setTimeout(() => {
        window.history.back();
      }, 100);
    }
  });
</script>
</head>
<body>

    <!--*******************
        Preloader start
    ********************-->
    <div id="preloader">
        <div class="waviy">
        <span style="--i:1">N</span>
		   <span style="--i:2">A</span>
		   <span style="--i:3">I</span>
		   <span style="--i:4">M</span>
		   <span style="--i:5">-</span>
		   <span style="--i:5">A</span>
		   <span style="--i:5">R</span>
		   <span style="--i:6">I</span>
           <span style="--i:6">A</span>
		   <span style="--i:7">-</span>
           <span style="--i:8">E</span>
		   <span style="--i:9">D</span>
           <span style="--i:10">U</span>
		</div>
    </div>
    <!--*******************
        Preloader end
    ********************-->

    <!--**********************************
        Main wrapper start
    ***********************************-->
    <div id="main-wrapper">

        <!--**********************************
            Nav header start
        ***********************************-->
        <div class="nav-header">
            <a href="index.html" class="brand-logo">
            <img src="images/logo1.png" alt="" height="70" width="70">
            </a>
            <div class="nav-control">
                <div class="hamburger">
                    <span class="line"></span><span class="line"></span><span class="line"></span>
                </div>
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->
		
		<!--**********************************
            Header start
        ***********************************-->
        <div class="header">
            <div class="header-content">
                <nav class="navbar navbar-expand">
                    <div class="collapse navbar-collapse justify-content-between">
                        <div class="header-left">
							<div class="dashboard_bar">
                 ثبت نام جدید صنف : <?php
                                         
                                         $q4="SELECT c_id,c_name FROM course_type WHERE c_id='$cid'";
                                         $r1=$con->query($q4);
                            while($row=$r1->fetch_array(MYSQLI_ASSOC))
                            {
                              echo $row["c_name"]; 
                          
                            }
                            ?>
                            </div>
                        </div>
       
                    </div>
				</nav>
			</div>
		</div>
        <!--**********************************
            Header end ti-comment-alt
        ***********************************-->

        <!--**********************************
            Sidebar start
        ***********************************-->
     <div class="dlabnav">
            <div class="dlabnav-scroll">
				<ul class="metismenu" id="menu">
					<li class="dropdown header-profile">
						<a class="nav-link" href="javascript:void(0);" role="button" data-bs-toggle="dropdown">
							<img src="images/profile/profile.png" width="20" alt="">
							<div class="header-info ms-3">
								<span class="font-w600 "><?php echo $_SESSION['emp_name']; ?></span>
								<small class="text-end font-w400"><?php echo $_SESSION['emp_email']; ?></small>
							</div>
						</a>
						<div class="dropdown-menu dropdown-menu-end">
							<a href="app-profile.php" class="dropdown-item ai-icon">
								<svg id="icon-user1" xmlns="http://www.w3.org/2000/svg" class="text-primary" width="18" height="18" viewbox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
								<span class="ms-2">پروفایل</span>
							</a>
							<a href="logout.php" class="dropdown-item ai-icon">
								<svg id="icon-logout" xmlns="http://www.w3.org/2000/svg" class="text-danger" width="18" height="18" viewbox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path><polyline points="16 17 21 12 16 7"></polyline><line x1="21" y1="12" x2="9" y2="12"></line></svg>
								<span class="ms-2">خروج از سیتم </span>
							</a>
						</div>
					</li>
              
					<li><a class="ai-icon" href="index.php" aria-expanded="false" style='font-size:20px;font-weight: bold;'>
						<i class="flaticon-025-dashboard"></i>
						<span class="nav-text">صفحه اصلی</span>
					</a>
				
				</li>
                    <li><a class="has-arrow ai-icon" href="javascript:void()" aria-expanded="false" style='font-size:20px;font-weight: bold;'>
						<i class="icon-user"></i>
							<span class="nav-text">لیست محصلین</span>
							
						</a>
                        <ul aria-expanded="false">
                            <li><a href="add_student.php" style='font-size:20px;font-weight: bold;'>اضافه محصل</a></li>
							<li><a href="view_student.php" style='font-size:20px;font-weight: bold;'>مشاهده محصل</a></li>
							<li><a href="view_all_student.php" style='font-size:20px;font-weight: bold;'>مشاهده محصلین</a></li>
							
                        </ul>
                    </li>
                  

  
                    <li><a class="has-arrow ai-icon" href="javascript:void()" aria-expanded="false">
							<i class="fa fa-book"></i>
							<span class="nav-text" style='font-size:20px;font-weight: bold;'>بخش صنف</span>
						</a>
                        <ul aria-expanded="false">
							<li><a href="add_course.php" style='font-size:20px;font-weight: bold;'>اضافه صنف جدید </a></li>
							<li><a href="view_course.php" style='font-size:20px;font-weight: bold;'>مشاهده صنوف</a></li>

                        </ul>
                    </li>
					<li><a class="has-arrow ai-icon" href="javascript:void()" aria-expanded="false" style='font-size:20px;font-weight: bold;'>
						<i class="icon-user"></i>
							<span class="nav-text">بخش اساتید</span>
							
						</a>
                        <ul aria-expanded="false">
                            <li><a href="view_teacher.php" style='font-size:20px;font-weight: bold;'>مشاهده</a></li>
							
							
                        </ul>
                    </li>
					<li><a  class="has-arrow ai-icon" aria-expanded="false">
							<i class="fa fa-file-invoice-dollar"></i>
							<span class="nav-text" style='font-size:20px;font-weight: bold;'>بخش پول صیف</span>
						</a>
						<ul aria-expanded="false">
                            
                            <li><a href="view_cash_point_details.php" style='font-size:20px;font-weight: bold;'>راپور صیف</a></li>
							<li><a href="add_view_expenses.php" style='font-size:20px;font-weight: bold;'>اضافه و مشاهده مصارف</a></li>
							
							
                        </ul>
					</li>

					<li><a  class="has-arrow ai-icon" aria-expanded="false">
							<i class="fa fa-calendar"></i>
							<span class="nav-text" style='font-size:20px;font-weight: bold;'>مشاهده راپور ها</span>
						</a>
						<ul aria-expanded="false">
                            
                            <li><a href="cash_point_report.php" style='font-size:20px;font-weight: bold;'>راپور صیف</a></li>
							<li><a href="student_report.php" style='font-size:20px;font-weight: bold;'>راپور محصلین</a></li>

							
                        </ul>
					</li>

                </ul>
			<div class="copyright">
					<p><strong>Student MIS Admin Dashboard</strong> © 2025 All Rights Reserved</p>
					<p class="fs-12">Made with <span class="heart"></span> by Dynamic & Cryptic</p>
				</div>
			</div>
        </div>
        <!--**********************************
            Sidebar end
        ***********************************-->


		
		<!--**********************************
            Content body start
        ***********************************-->
		<div class="content-body">
            <div class="container-fluid">
				<div class="row page-titles">
					<ol class="breadcrumb">
						<li class="breadcrumb-item active"><a href="javascript:void(0)">صفحه</a></li>
						<li class="breadcrumb-item"><a href="javascript:void(0)">پرداخت فیس</a></li>
					</ol>
                </div>
				
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                          
                            <div class="card-body">
                               
							<div class="basic-form">
                                    <form  name="insert" method="post" dir="rtl">
                                     <div class="mb-3 row">
                                            <label class="col-sm-3 col-form-label" style="font-size:20px;">تاریخ ختم ثبت نام</label>
                                            <div class="col-sm-9">
                                                <input type="date" name="end_date" id="end_date"  value="<?php echo $end_date ?>" class="form-control" placeholder="" style="font-size:25px;"><span id="lblError" style="color: red"></span>
                                            </div>
                                        </div>   
                                    
                                        <div class="mb-3 row">
                                            <label class="col-sm-3 col-form-label" style="font-size:20px;">مبلغ فیس</label>
                                            <div class="col-sm-9">
                                                <input type="text" name="fee_amount" id="fee_amount" value="<?php echo $p_amount ?>" class="form-control" placeholder="" style="font-size:25px;" readonly="readonly"><span id="lblError" style="color: red"></span>
                                            </div>
                                        </div>
                                    
                                       
                                        <div class="mb-3 row">
                                            <label class="col-sm-3 col-form-label" style="font-size:20px;">مبلغ پرداخت</label>
                                            <div class="col-sm-9">
                                                <input type="text" name="receive_amount" id="receive_amount"  class="form-control" placeholder="" style="font-size:25px;"><span id="lblError" style="color: red"></span>
                                            </div>
                                        </div>
                                        <div class="mb-3 row">
                                            <label class="col-sm-3 col-form-label" style="font-size:20px;">مبلغ باقی </label>
                                            <div class="col-sm-9">
                                                <input type="text" name="borrow_amount" id="borrow_amount"  class="form-control" placeholder="" style="font-size:25px;" readonly="readonly"><span id="lblError" style="color: red"></span>
                                            </div>
                                        </div>
                                           <div class="mb-3 row">
                                            <label class="col-sm-3 col-form-label" style="font-size:20px;">حالت پرداخت</label>
                                            <div class="col-sm-9">
                                               <select name="payment_status" id="payment_status" class="form-control"> 
                                                <option value="">انتخاب کنید</option>
                                                <option value="درجریان">درجریان</option>
                                                <option value="تکمیل">تکمیل</option>
                                               </select>
                                               <input type="hidden" name="p_status" id="p_status">

                                            </div>
                                        </div>
                                             <input type="hidden" class="form-control" id="bill_no" name="bill_no" readonly="readonly">
                                                        <script>
    
                                                        let now = Math.floor(Math.random()* 1000000000);
                                                        document.getElementById("bill_no").value = now;

                                                        </script>

                                                              <input type="hidden" class="form-control" id="cash_id" name="cash_id" readonly="readonly">
                                                        <script>
    
                                                        let cp = Math.floor(Math.random()* 1000000);
                                                        document.getElementById("cash_id").value = cp;

                                                        </script>
                                        <div class="col-lg-12">
                               <input type="hidden" style='font-size:20px;' name="date" id="date" class="form-control" value=" <?php
                                                    date_default_timezone_set('Asia/Kabul'); 
                                                        $now = new DateTime();
                                                        echo $now->format('Y-m-d');    // MySQL datetime format
                                                    
                                                        ?>" required="">
                    </div>
                                  
                                      
                                        <div class="mb-3 row">
                                            <div class="col-sm-10">
                                                <button style="font-size:20px;" type="submit" id="submit" value="ثبت سیستم" class="btn btn-primary btn sweet-success">ثبت سیستم</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
			
            </div>
        </div>
        <!--**********************************
            Content body end
        ***********************************-->
		
        <!--**********************************
            Footer start
        ***********************************-->
    <div class="footer">
		
            <div class="copyright">

            </div>
        </div>
        <!--**********************************
            Footer end
        ***********************************-->

		


	</div>
    <!--**********************************
        Main wrapper end
    ***********************************-->

    <!--**********************************
        Scripts
    ***********************************-->
    <!-- Required vendors -->
    <script src="vendor/global/global.min.js"></script>
	<script src="vendor/chart.js/Chart.bundle.min.js"></script>
	<script src="vendor/jquery-nice-select/js/jquery.nice-select.min.js"></script>
	
	
	
	<!-- Dashboard 1 -->
	<script src="js/dashboard/dashboard-1.js"></script>
    <script src="js/custom.min.js"></script>
	<script src="js/dlabnav-init.js"></script>
	<script src="js/demo.js"></script>
    <script src="js/styleSwitcher.js"></script>
    <!--Sweet Alert--->
    <script src="vendor/sweetalert2/dist/sweetalert2.min.js"></script>
    <script src="js/plugins-init/sweetalert.init.js"></script>
    <script src="dist/sweetalert.min.js"></script>
	<script src="vendor/jquery-nice-select/js/jquery.nice-select.min.js"></script>
    <script>

       
$("#payment_status").on('change',function(){
    var getValue=$(this).val();
    $("#p_status").val(getValue);
  });

        $("#submit").click(function(){
   
        var  receive_amount=$("#receive_amount").val();
        var  p_status=$("#p_status").val();
        var  end_date=$("#end_date").val();
    
        if(end_date == null || end_date == ""){
        sweetAlert("اخطاریه","تاریخ ختم ثبت نام لازمی میباشد","warning");  
        return false;  
      }
      else if(receive_amount == null || receive_amount == ""){
        sweetAlert("اخطاریه","مبلغ رسید لازمی میباشد","warning");  
        return false;  
      }
      else if(p_status == null || p_status == ""){
        sweetAlert("اخطاریه","انتخاب حالت پرداخت لازمی میباشد","warning");  
        return false;  
      }
      else
      swal("معلومات شما موفقانه ثبت سیستم شد","","success")
                window.setTimeout(function(){ 
                    form.submit();              ;
            } ,1500);
        
        });


        $(function () {
$("#fee_amount,#receive_amount,#borrow_amount").keyup(function () {
    
    var fee_amount = parseFloat($("#fee_amount").val());
    var receive_amount = parseFloat($("#receive_amount").val());

    var result = fee_amount- receive_amount;
    $("#borrow_amount").val(result);

 });
});


    </script>
	
</body>
</html>
