<?php 
ob_start();
session_start();
include "../config/config.php";
include "../config/session.php";


/*include_once('../config/custom-functions.php');
$fn = new custom_functions;
$db = new Database();*/






if(isset($_POST['type']) && $_POST['type']=='create_customer_scheme'){
     try{
         
        $pdo->beginTransaction(); 
        
            $customer_id = $_POST['customer_id'];
            $scheme_id = $_POST['scheme_id'];
            $scheme_amount = $_POST['scheme_amount'];
            $sales_man_id = $_POST['sales_man_id'];
            $location_id = $_POST['location_id'];
            // $created_user_id = $_POST['created_user_id'];
            
            
        $unique_id = "10000";
	    $statement = $pdo->prepare("SHOW TABLE STATUS WHERE `name` = 'tbl_customer_scheme'");
        $statement->execute();
        $memeber_id_result = $statement->fetchAll(PDO::FETCH_ASSOC); 
        foreach ($memeber_id_result as $result) {
	        $unique_id = $unique_id + $result['Auto_increment'];
        }
        
        $unique_id = "SCM_".$unique_id;
        
        
         
        $statementsss = $pdo->prepare("SELECT * FROM `tbl_schemes` WHERE id=?");
        $statementsss->execute(array($scheme_id));
        $resultsss = $statementsss->fetchAll(PDO::FETCH_ASSOC);
        $totalsss = $statementsss->rowCount();  
        
        if($totalsss>0){
            $scheme_month = $resultsss[0]['month'];
            $scheme_type = $resultsss[0]['type'];
        }
        
        
        $scheme_completed_date = "0000-00-00";
        
        $statement = $pdo->prepare("INSERT INTO `tbl_customer_scheme`(`customer_id`, `scheme_id`, `scheme_no`, `scheme_added_date`, `scheme_completed_date`, 
                                    `scheme_months`, `created_by`, `scheme_amount`,
                                    `type`, `sales_man_id`, `created_employee`, `location_id`) VALUES (?,?,?,?,?,
                                    ?,?,?,
                                    ?,?,?,?)");
      
    	$result = $statement->execute(array($customer_id, $scheme_id, $unique_id, $today_date, $scheme_completed_date, 
                                	$scheme_month, $session_id, $scheme_amount,
                                	$scheme_type, $sales_man_id, $session_id, $location_id));
    
 
        
 
    
        if($result){
            
            $customer_id = $pdo->lastInsertId();
            

    	    
    	    $pdo->commit();
    	    $return_arr['scheme_id']= $customer_id;
            $return_arr['message']='Customer Scheme Added Successfully...';
            $return_arr['status']=200;

        }
        else
        {
            $return_arr['message']='Something Went Wrong..';
            $return_arr['status']=400;
        }
            
            
             
     }catch(PDOException $e){
        $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
        }   
    echo json_encode($return_arr);
}

if(isset($_POST['type']) && $_POST['type']=='update_customer_scheme'){
     try{
         
        $pdo->beginTransaction(); 
        
            $ids = $_POST['ids'];
            $customer_id = $_POST['customer_id'];
            $scheme_id = $_POST['scheme_id'];
            $scheme_completed_date = $_POST['completed_date'];
            $scheme_amount = $_POST['scheme_amount'];
            

         
        $statementsss = $pdo->prepare("SELECT * FROM `tbl_schemes` WHERE id=?");
        $statementsss->execute(array($scheme_id));
        $resultsss = $statementsss->fetchAll(PDO::FETCH_ASSOC);
        $totalsss = $statementsss->rowCount();  
        if($totalsss>0){
            $scheme_month = $resultsss[0]['month'];
            /*$scheme_amount = $resultsss[0]['amount'];*/
        }
        
        
        
        
        $statement = $pdo->prepare("UPDATE `tbl_customer_scheme` SET `customer_id`=?, `scheme_id`=?, `scheme_completed_date`=?, 
        `scheme_months`=?, `updated_by`=?, `scheme_amount`=? WHERE id=?");
      
    	$result = $statement->execute(array($customer_id, $scheme_id, $scheme_completed_date, 
    	$scheme_month, $session_id, $scheme_amount, $ids));
    
 
        
 
    
        if($result){
            
            

    	    
    	    $pdo->commit();
            $return_arr['message']='Customer Scheme Updated Successfully...';
            $return_arr['status']=200;

        }
        else
        {
            $return_arr['message']='Something Went Wrong..';
            $return_arr['status']=400;
        }
            
            
             
     }catch(PDOException $e){
        $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
        }   
    echo json_encode($return_arr);
}


if(isset($_POST['type']) && $_POST['type']=='add_payment'){
     try{
         
        $pdo->beginTransaction(); 
        
            $customer_id = $_POST['customer_id'];
            $scheme_id = $_POST['scheme_id'];
            $scheme_amount = $_POST['scheme_amount'];
            $payment_year = date("Y");
            $payment_date = $_POST['payment_date'];
            $type = "Credit";
            $accounts = 3;
            
            
 
        
            
        
        
         
    
        
        for($i=0; $i<count($_POST['payment_month']); $i++){
            
            $payment_month = $_POST['payment_month'][$i];
            $payment_amount = $_POST['payment_amount'][$i];
            $product_weight = $_POST['product_weight'][$i];
            $payment_type = $_POST['payment_type'][$i];
            $reference_no = $_POST['reference'][$i];
            $notes = $_POST['notes'][$i];
            $per_gm_amount = $_POST['per_gm_amount'][$i] ?? 0;
            
            
            
                    if(isset($customer_id) && $customer_id!="" && isset($scheme_id) && $scheme_id!="" && isset($payment_month)){
                                                        
                        $statementsss = $pdo->prepare("SELECT 
                                                        COALESCE(SUM(amount),0) as payment_scheme_amount 
                                                        FROM `tbl_payments` 
                                                        WHERE customer_id=? and scheme_id=? and accounts=? and month=? and year=?");
                        $statementsss->execute(array($customer_id, $scheme_id, 3, $payment_month, $payment_year));
                        $resultsss = $statementsss->fetchAll(PDO::FETCH_ASSOC);
                        $totalsss = $statementsss->rowCount();    
                        
                        if($totalsss>0){
                            
                            $payment_scheme_amount = $resultsss[0]['payment_scheme_amount'];
                            
                            error_log("Data Found: ".$payment_scheme_amount);
                            
                            if($payment_scheme_amount>=$scheme_amount){
                                $return_arr['status']=400;
                                $return_arr['error'] = true;
                                $return_arr['message'] = "This Customer ".date("F", mktime(0, 0, 0, $payment_month, 10))." Month Already Paid!";
                                print_r(json_encode($return_arr));
                                return false;
                                exit(); 
                            }
                            
                            
                        }else{
                            error_log("No Data Found: ".$scheme_amount);
                        }
                    }
            
        
                    $statement = $pdo->prepare("INSERT INTO `tbl_payments`(`date`, `type`, `amount`, `month`, `year`, 
                                        `customer_id`, `scheme_id`, `accounts`, `payment_type`, `reference_no`, `notes`, 
                                        `created_date`, `created_by`, `scheme_weight`,
                                        `per_gm_amount`) VALUES (?,?,?,?,?,
                                        ?,?,?,?,?,?,?,?,?,
                                        ?)");
              
            	    $result = $statement->execute(array($payment_date, $type, $payment_amount, $payment_month, $payment_year, 
            	                        $customer_id, $scheme_id, $accounts, $payment_type, $reference_no, $notes, 
            	                        $today_date, $session_id, $product_weight,
            	                        $per_gm_amount));
     
        }
        
        
    	
    	if($result){
    	    $payment_id = $pdo->lastInsertId();
    	}
    	
    
    
        
 
    
        if($result){
           
    	    
    	    $pdo->commit();
    	    $return_arr['row_id'] = $scheme_id;
            $return_arr['message']='Customer Scheme Payment Added Successfully...';
            $return_arr['status']=200;

        }else{
            $return_arr['message']='Something Went Wrong..';
            $return_arr['status']=400;
        }
            
            
             
    }catch(PDOException $e){
        $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
    }   
    echo json_encode($return_arr);
}




if(isset($_POST['type']) && $_POST['type']=='create_scheme'){
     try{
         
         $pdo->beginTransaction(); 
         
        // Details Here
        $name = $_POST['name'];
        $scheme_type = $_POST['scheme_type'];
        $month = $_POST['month'];
         
        $statement = $pdo->prepare("INSERT INTO `tbl_schemes`(`name`, `type`, `month`) VALUES (?,?,?)");
        $result = $statement->execute(array($name, $scheme_type, $month));
         
        if($result){    
            $pdo->commit();
            $return_arr['message']='Scheme Details Added Successfully...';
            $return_arr['status']=200;
        }else{
            $return_arr['message']='Something Went Wrong..';
            $return_arr['status']=400;
        }
    }catch(PDOException $e){
        $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
    }   
    echo json_encode($return_arr);
}


if(isset($_POST['type']) && $_POST['type']=='update_scheme'){
     try{
         
         $pdo->beginTransaction(); 
         
        // Details Here
        $ids = $_POST['ids'];
        $name = $_POST['name'];
        $scheme_type = $_POST['scheme_type'];
        $month = $_POST['month'];
         
        $statement = $pdo->prepare("UPDATE `tbl_schemes` SET `name`=?, `type`=?, `month`=? WHERE id=?");
        $result = $statement->execute(array($name, $scheme_type, $month, $ids));
         
         
         
        if($result){    
            $pdo->commit();
            $return_arr['message']='Scheme Details Updated Successfully...';
            $return_arr['status']=200;
        }else{
            $return_arr['message']='Something Went Wrong..';
            $return_arr['status']=400;
        }
    }catch(PDOException $e){
        $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
    }   
    echo json_encode($return_arr);
}

?>