<?php
//user_action.php
include('db_con.php');
if (isset($_SESSION['user_id'])) {
		$user_type = $_SESSION['user_type'];
		$user_id = $_SESSION['user_id'];
		$user_name = $_SESSION['user_name'];
		$branch_id = $_SESSION['branch_id'];
		$branch_name = $_SESSION['branch_name'];
		$store_id = $_SESSION['store_id'];
    $store_name = $_SESSION['store_name'];
}else{
	header('Location: login');
	die();
}
if(isset($_POST['btn_action']))
{
	if($_POST['btn_action'] == 'Add')
	{
		$dated = date('Y-m-d');
		$acc_type = $_POST['acc_type'];
		$acc_parent = $_POST['acc_parent'];
		if($acc_type=='Asset')
		{
			$sql = "select IFNULL(MAX(acc_id),1000) from accounts where acc_type='Asset'";
			$statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $acc_id = $statement->fetchColumn();
            if($acc_id < 1000){$acc_id=1000;}
           
            
		}
		if($acc_type=='Liability')
		{
			$sql = "select IFNULL(MAX(acc_id),2000) from accounts where acc_type='Liability'";
			$statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $acc_id = $statement->fetchColumn();
            if($acc_id < 2000){$acc_id=2000;}
           
            
		}
		if($acc_type=='Expense')
		{
			$sql = "select IFNULL(MAX(acc_id),3000) from accounts where acc_type='Expense'";
			$statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $acc_id = $statement->fetchColumn();
           	if($acc_id < 3000){$acc_id=3000;}
            
		}
		if($acc_type=='Equity')
		{
			$sql = "select IFNULL(MAX(acc_id),4000) from accounts where acc_type='Equity'";
			$statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $acc_id = $statement->fetchColumn();
           	if($acc_id < 4000){$acc_id=4000;}
            
		}
		if($acc_type=='Revenue')
		{
			$sql = "select IFNULL(MAX(acc_id),5000) from accounts where acc_type='Revenue'";
			$statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $acc_id = $statement->fetchColumn();
           	if($acc_id < 5000){$acc_id=5000;}
            
		}
		$acc_id++;
		$new_acc_no= $acc_parent .$acc_id;
		$dated = date('Y-m-d');
		
		$query = "
		INSERT INTO accounts (dated,acc_id,acc_no,acc_name,acc_type,acc_parent,op_balance,user_id,status)
        VALUES (:dated, :acc_id, :acc_no, :acc_name, :acc_type, :acc_parent, :op_balance, :user_id, :status)
    ";	
		$statement = $connect->prepare($query);
		$statement->execute(
			array(
          
          ':dated'             =>  $dated,
          ':acc_id'          =>  $acc_id,
          ':acc_no'          =>  $new_acc_no,
           ':acc_name'          =>  trim($_POST["acc_name"]),
          ':acc_type'          =>  trim($_POST["acc_type"]),          
          ':acc_parent'       =>  trim($_POST["acc_parent"]),
          ':op_balance'       => trim($_POST["op_balance"]),
          ':user_id'       =>  $user_id,
          ':status'       =>  trim($_POST["status"])
          
          )
		);
		
		$op_balance = $_POST['op_balance'];

		if($op_balance > 0)
		{
			$dated = date('Y-m-d');
			$sql = "SELECT MAX(jv_no) FROM jv WHERE branch_id = '".$branch_id."' and source ='acc'";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $jv_no = $statement->fetchColumn();
            settype($jv_no, "integer");
            $jv_no++;

            $ref_id = $new_acc_no;


    $source = 'acc';
    $description = 'Opening Balance For New Account '.$_POST['acc_name'];
    $statement = $connect->prepare("
      INSERT INTO jv 
        (jv_no,branch_id,dated,source,ref_id,description,user_id,status)
        VALUES (:jv_no, :branch_id, :dated, :source, :ref_id, :description, :user_id, :status)
    ");
    $statement->execute(
      array(
          ':jv_no'             =>  $jv_no,
          ':branch_id'             =>  $branch_id,
          ':dated'             =>  $dated,
          ':source'          =>  $source,
          ':ref_id'          =>  $ref_id,
          ':description'       =>  $description,              
          ':user_id'       =>  $user_id,
           ':status'       =>  'Active'
      )
    );
     $statement = $connect->query("SELECT LAST_INSERT_ID()");
      $jv_id = $statement->fetchColumn();
    
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,narr,debit,credit)
          VALUES(:jv_id, :acc_no,  :narr, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  $new_acc_no,
            ':narr'              =>  '',
            ':debit'          =>  $op_balance,
            ':credit'           =>  0
           
            
          )
        );

        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,narr,debit,credit)
          VALUES(:jv_id, :acc_no,  :narr, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  1000000,
            ':narr'              =>  '',
            ':debit'          =>  0,
            ':credit'           =>  $op_balance
           
            
          )
        );
    
     
		}
		
		$result = $statement->fetchAll();
		if(isset($result))
		{
			echo 'New Account Added';
		}
	}
	if($_POST['btn_action'] == 'fetch_single')
	{
		$query = "
		SELECT * FROM accounts WHERE acc_no = :acc_no";
		
		$statement = $connect->prepare($query);
		$statement->execute(
			array(
				':acc_no'	=>	$_POST["acc_no"]
			)
		);
		$result = $statement->fetchAll();
		foreach($result as $row)
		{
			
			
					 $output['acc_no']          =  $row['acc_no'];
           $output['acc_name']          =  $row['acc_name'];
          $output['acc_type']          =  $row['acc_type'];
          $output['acc_parent']       =  $row["acc_parent"];
          $output['op_balance']       =  $row["op_balance"];          
          $output['status']       =  $row["status"];
          
		}
		echo json_encode($output);
	}
	if($_POST['btn_action'] == 'Edit')
	{
		$dated = date('Y-01-01');
		$query = "
		UPDATE accounts
		SET acc_name = :acc_name,
		acc_type = :acc_type,
		acc_parent = :acc_parent,
		op_balance = :op_balance,
		status = :status
		WHERE acc_no = :acc_no
		";
		$statement = $connect->prepare($query);
		$statement->execute(
			array(
				':acc_name'	=>	$_POST['acc_name'],
				':acc_type'	=>	$_POST['acc_type'],
				':acc_parent'	=>	$_POST['acc_parent'],
				':op_balance'	=>	$_POST['op_balance'],
				':status'	=>	$_POST['status'],
				':acc_no'		=>	$_POST["acc_no"]
			)
		);	

		$ref_id = $_POST['acc_no'];

		$sql = "select jv_id from jv where source = 'acc' and ref_id = '".$ref_id."'";
		$statement = $connect->prepare($sql);
		$statement->execute();
		$jv_id = $statement->fetchColumn();

		if($jv_id > 0)
		{
		$sql = "delete from jv where jv_id = '".$jv_id."'";
		$statement = $connect->prepare($sql);
		$statement->execute();
		$sql = "delete from jv_detail where jv_id = '".$jv_id."'";
		$statement = $connect->prepare($sql);
		$statement->execute();
		}

		$op_balance = $_POST['op_balance'];
		if($op_balance > 0)
		{
			$dated = date('Y-01-01');
			$sql = "SELECT MAX(jv_no) FROM jv WHERE branch_id = '".$branch_id."' and source ='acc'";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $jv_no = $statement->fetchColumn();
            settype($jv_no, "integer");
            $jv_no++;


    $source = 'acc';
    $description = 'Opening Balance For New Account '.$_POST['acc_name'];
    $statement = $connect->prepare("
      INSERT INTO jv 
        (jv_no,branch_id,dated,source,ref_id,description,user_id,status)
        VALUES (:jv_no, :branch_id, :dated, :source, :ref_id, :description, :user_id, :status)
    ");
    $statement->execute(
      array(
          ':jv_no'             =>  $jv_no,
          ':branch_id'             =>  $branch_id,
          ':dated'             =>  $dated,
          ':source'          =>  $source,
          ':ref_id'          =>  $ref_id,
          ':description'       =>  $description,              
          ':user_id'       =>  $user_id,
           ':status'       =>  'Active'
      )
    );

     $statement = $connect->query("SELECT LAST_INSERT_ID()");
      $jv_id = $statement->fetchColumn();
    
     
    
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,narr,debit,credit)
          VALUES(:jv_id, :acc_no,  :narr, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  trim($_POST["acc_no"]),
            ':narr'              =>  '',
            ':debit'          =>  $op_balance,
            ':credit'           =>  0
           
            
          )
        );

        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,narr,debit,credit)
          VALUES(:jv_id, :acc_no,  :narr, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  1000000,
            ':narr'              =>  '',
            ':debit'          =>  0,
            ':credit'           =>  $op_balance
           
            
          )
        );
    
     
		}
			
		$result = $statement->fetchAll();
		if(isset($result))
		{
			echo 'Account Details Edited';
		}
	}
	if($_POST['btn_action'] == 'delete')
	{
		$status = 'Inactive';
		if($_POST['status'] == 'Active')
		{
			$status = 'Inactive';
		}
		$query = "
		UPDATE accounts
		SET status = :status 
		WHERE acc_no = :acc_no
		";
		$statement = $connect->prepare($query);
		$statement->execute(
			array(
				':status'	=>	$status,
				':acc_no'		=>	$_POST["acc_no"]
			)
		);	
		$result = $statement->fetchAll();	
		if(isset($result))
		{
			echo 'Account Status change to ' . $status;
		}
	}
}
?>