<?php session_start();
if ($_SESSION['company'] == "") {
    exit("Please Login");
}
if ($_SESSION['CURRENT_USER'] == "") {
    exit("Please Login");
}
require_once ("connection_sql.php");
header('Content-Type: text/xml');
$date = $_POST['date'];
$time=strtotime($date);
$month=date("m",$time);
$year=date("Y",$time);


$account = $_POST['account'];

$sql = "SELECT COUNT(*) AS total FROM a_bank_bal WHERE month(bdate) > '$month' and year(bdate) > '$year' and code='$account'";
$result = $conn->query($sql);
$upCount = $result->fetch();


if ($upCount['total'] == 0) {
    $sql ="SELECT * FROM a_bank_bal WHERE code = $account AND month(bdate) = '$month' and year(bdate) = '$year' ";
    $result = $conn->query($sql);
    $bal_record = $result->fetch();

    $sql ="SELECT * FROM a_lock_bank_rec WHERE bank_code ='$account' and  month(lock_date_to) = '$month' and year(lock_date_to) = '$year'";
    $result = $conn->query($sql);
    $lock_record = $result->fetch();

    if ($bal_record && $lock_record) {

        $date_from = new DateTime($lock_record['lock_date_from']);
        $date_to = new DateTime($lock_record['lock_date_to']);
        $date_to->modify('first day of last month')->modify('last day of this month');
        $date_from->modify('first day of last month')->modify('last day of this month');

        $new_lock_date_to = $date_to->format('Y-m-d');
        $new_lock_date_from = $date_from->format('Y-m-d');

        $sql="UPDATE a_lock_bank_rec SET lock_date_from='$new_lock_date_from',lock_date_to='$new_lock_date_to' WHERE bank_code='$account' ";
        $result = $conn->query($sql);

        $sql = "DELETE FROM a_bank_bal WHERE id = '$bal_record[id]'";
        $result = $conn->query($sql);
       echo "Unlock successfully.";
    }  else{
        echo "Locked Month Not Found !!!!!!!!!";
    }


} else {
    echo "Please unlock Last lock Month";
}