<?php
    include_once('../header.php');
    if(!check_login()){
        header("Location: " . WEB_URL . "logout.php");
        die();
    }
    if($_SERVER["REQUEST_METHOD"] === "POST"){
        $data = post_input_serilization();
        $security_deposit_result = $link->query("SELECT * FROM security_deposit WHERE id = $data[security_deposit_id]");
        if($security_deposit = mysqli_fetch_assoc($security_deposit_result)){
            $security_deposit_id = $security_deposit["id"];
        }
        else{
            $_SESSION["message"] = "Error Saving Payment";
            $_SESSION["message_type"] = "error";
            $url = WEB_URL . 'security_deposit/security_deposit_list.php';
            header("Location: $url");	
            exit; 
        }

        $link->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
        if(floatval($data["amount_paid"]) + floatval($security_deposit["amt_paid"]) > floatval($security_deposit["rate"])){
            $link->query("UPDATE security_deposit SET amt_paid = $security[rate], bill_status = 1 WHERE id = $security_deposit_id");
         
        }else{
            $link->query("UPDATE security_deposit SET amt_paid = amt_paid + $data[amount_paid] WHERE id = $security_deposit_id");
            
        }
        
        $link->query("INSERT INTO security_deposit_payment_updates(security_deposit_id, amount, added_by) VALUES($security_deposit_id, $data[amount_paid], $_SESSION[user_id])");
        
        $result = $link->commit();
        if($result){
            $_SESSION["message"] = "Payment Added Successfully";
            $url = WEB_URL . 'security_deposit/security_deposit_list.php';
            header("Location: $url");	
            exit;
        }else{
            $_SESSION["message"] = "Failed to Add Payment";
            $url = WEB_URL . 'security_deposit/security_deposit_list.php';
            header("Location: $url");
            exit;
        }
    }else{
        $url = WEB_URL . 'security_deposit/security_deposit_list.php';
        header("Location: $url");
    }