<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Laybuy.php';
require_once __DIR__ . '/../../classes/Branch.php';

$record_id	= $_GET['record_id'];
$balance	= $_GET['balance'];
$total_paid	= $_GET['total_paid'];

$database = new Database();
$conn = $database->getConnection();


//$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
//$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);



if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    //$record_id = $_POST['username'];
    $body_amount=$_POST['top_up_amount'];
	$payment_date=$_POST['payment_date'];
	$notes=$_POST['notes'];
	$payment_date=$_POST['payment_date'];
	$payment_date=$_POST['payment_date'];
	
	$laybuy = new Laybuy($conn);
    if  (($laybuy->updateLayBuyHeader($body_amount, $record_id, $total_paid )) &&  ($laybuy->register($body_amount, $record_id, $payment_date, $total_paid, $notes))) {
        header('Location: pay_loan_or_laybuy.php?record_id='.$record_id);
        exit();
		    } else { 
        echo "<div class='alert alert-danger'>Failed to register user.</div>";
    }
}


?>
<?php include __DIR__ . '/../../includes/header.php'; ?>
    <div class="container mt-5">
        <h1 class="mb-4">Edit Payment</h1>
        <form method="POST">
            <div class="form-group">
                <label for="payment_date">Payment date</label>
                <input type="date" class="form-control" id="payment_date" name="payment_date"  required>
            </div>
			
            <div class="form-group">
                <label for="top_up_amount"> Top-up Amount </label>
                <input type="text" class="form-control" id="top_up_amount" name="top_up_amount" onKeyUp="updateNewBal()" required>
            </div>
			
			<div class="form-group">
                <label for="notes"> Notes </label>
                <input type="text" class="form-control" id="notes" name="notes" required>
            </div>
			
			
             <button type="submit" class="btn btn-primary">Edit Payment</button>
            <a href="pay_loan_or_laybuy.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
<script>
	function updateNewBal(){
		const balance = "<?php echo $balance ?>";
		const top_up_amount = document.getElementById('top_up_amount').value;
		document.getElementById('new_balance').value=balance-top_up_amount;
	}

</script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>