<?php 
// Include main file
include_once('../libs/main.php');
// Check admin Login
include_once('checkLogin.php');
// Logical section of page
$subscription_productObj =  new  subscription_product();
$subscription_planObj = new subscription_plans();
$subscription_master_planObj = new subscription_master_plans();
$stripeObj   = new stripePay();
$adminlogObj = new admin_log();
$modulepagesObj = new module_pages();
$filename=basename($_SERVER['SCRIPT_FILENAME']);
if($filename == 'productadd.php')
{
    $module_id = $adminlogObj->getModuleId($filename);
    $page_id = $adminlogObj->getPageId($filename);
    $allpages = $modulepagesObj->fromId($page_id);
    $pagename = $allpages->page;
}

$subscription_productObj->resultAs = 'array';
$subproductfields  = array('subscription_product_clinic_id','subscription_product_id');
if($_REQUEST['subscription_product_id'] == '')
{
    $subproductwhere = '1=1';    
}else{
    $subproductwhere = "subscription_product_id NOT IN (".$_REQUEST['subscription_product_id'].")";
}

$subproductArg    = array('fields'=>$subproductfields,'where' => $subproductwhere);
$subproductData = $subscription_productObj->getAllRecords($subproductArg);
if(isset($subproductData) && count($subproductData) > 0)
{
    //$prodclinicid = array();
    $prodclinicid = '';
    foreach($subproductData as $key => $subprodval)
    {
        if(isset($subprodval['subscription_product_clinic_id']) && $subprodval['subscription_product_clinic_id'] != '')
        {
            //array_push($prodclinicid, $subprodval['subscription_product_clinic_id']);
            $prodclinicid .= $subprodval['subscription_product_clinic_id'].",";
        }
    }
}

if(isset($prodclinicid) && $prodclinicid != '')
{
    $all_prodclinicid = rtrim($prodclinicid,",");
}

$clinicObj = new clinic();
if(isset($all_prodclinicid) && $all_prodclinicid != '')
{
    
    $clinicwhere = " clinic_status = '1' and clinic_id NOT IN (".$all_prodclinicid.")";
    $clinicArg    = array('where' => $clinicwhere);
    $allClinic = $clinicObj->getAllRecords($clinicArg);
}else
{
    
    $allClinic = $clinicObj->getAllRecords();
}


if(isset($_REQUEST['act']) && $_REQUEST['act']=='edit' && isset($_REQUEST['subscription_product_id'])){
    $productDetail = $subscription_productObj->fromId($_REQUEST['subscription_product_id']);
}


if(isset($_REQUEST['act']) && $_REQUEST['act']=='validate_defult_data' && isset($_REQUEST['product_id']) && $_REQUEST['product_id'] != "")
{
    if(isset($_REQUEST['product_id']) && $_REQUEST['product_id'] != '')
    {
        
        
        if(!empty($_POST['clinics']))
        {
            $subscription_productObj->resultAs = 'array';
            $subproductchkfields  = array('subscription_product_clinic_id','subscription_product_id');
            
            $subproductchkwhere = "subscription_product_id NOT IN (".$_REQUEST['product_id'].") AND subscription_product_status = '1' ";
            $subproductchkArg    = array('fields'=>$subproductchkfields,'where' => $subproductchkwhere);
            $subproductchkData = $subscription_productObj->fromFields($subproductchkArg);
            
            if($subproductchkData['subscription_product_id'] == '')
            { 
                echo "Please atleast one product defult";
                exit;   
            }else{
                echo 'success';
                exit;
            }
        }else
        {
            echo 'success';
                exit;
        }
    }    

    return true;

}

//if(isset($_POST['submit'])){
if(isset($_REQUEST['act']) && $_REQUEST['act']=='load' && isset($_REQUEST['product_name']) && $_REQUEST['product_name'] != "")
{
    $product_mode = $_POST['product_mode'];
    $data=array(
        'subscription_product_name' => trim($_POST['product_name']),
    );
    
    if (isset($_REQUEST['product_id']) && $_REQUEST['product_id'] != '')
    {
        $proddetails = '<b>Edit Product Old</b>';
        $productstatus = $subscription_productObj->fromId($_REQUEST['product_id']);
        
        if(isset($_POST['clinics']))
        {
            
            $data['subscription_product_clinic_id'] = implode(',', $_POST['clinics']);
            $clinicupdata = implode(',', $_POST['clinics']);
            //$data['subscription_product_status'] = '2';
        }else{
            $data['subscription_product_clinic_id'] = '';
            /*if($productstatus['subscription_product_status'] == '2')
            {
                $data['subscription_product_status'] = '0';    
            }*/
        }
        $data['subscription_product_stripe_id'] = $productstatus['subscription_product_stripe_id'];
        
        //$updateProducts = $stripeObj->updateProduct($data);
        $updateProducts = '1';
        
        if($productstatus['subscription_product_name'] != $_REQUEST['product_name'])
        {
            
            $proddetails .= " <b>Product Name</b>: "." ".$productstatus['subscription_product_name']." <b>To</b> ".$_REQUEST['product_name']." and ";
            
            $chages_data = true;
        }
        
        //if($updateProducts->id)
        if($updateProducts)
        {
            $data['subscription_product_stripe_response'] = json_encode($updateProducts);
           
            $id=$_POST['product_id'];
            
            $new_all_clinic = explode(",",$clinicupdata);
            $old_all_clinic = explode(",",$productstatus['subscription_product_clinic_id']);
            
            $result_clinic=array_diff($old_all_clinic,$new_all_clinic);
            
            if(!empty($result_clinic))
            {
                $proddetails .= " <b>Clinic</b> : ".$productstatus['subscription_product_clinic_id']." <b>To Clinic</b>: ".rtrim($clinicupdata,",");
                $chages_data = true;  
            }else{
                if(!empty($new_all_clinic) && !empty($old_all_clinic))
                {
                    if(count($new_all_clinic) > count($old_all_clinic))
                    {
                        $proddetails .= " <b>Clinic</b> : ".$productstatus['subscription_product_clinic_id']." <b>To Clinic</b>: ".rtrim($clinicupdata,",");
                        $chages_data = true; 
                    }
                }
            }
            $rs=$subscription_productObj->updateRecords($data,$id);
            if ($rs){
                
                if(!empty($clinicupdata))
                {
                    $allclinicdata = explode(",",$productstatus['subscription_product_clinic_id']);

                    
                    $clinicObj = new clinic();
                    $cliniclogfields = array('clinic_name','clinic_id');
                    $clinicObj->resultAs = 'array';
                    $wherelogclinic = "clinic_id IN (".$clinicupdata.") ";
                    $cliniclogArg = array('fields'=>$cliniclogfields,'where' => $wherelogclinic);
                    $allclinic_log = $clinicObj->getAllRecords($cliniclogArg);
                    $clinicupd =  '';
                    foreach($allclinic_log as $ackey => $acvalue)
                    {
                        if (in_array($acvalue['clinic_id'], $allclinicdata))
                        {
                            $clinicupd = '';
                        }else{
                            $clinicupd .= $acvalue['clinic_name'].",";
                        }
                    }

                    $clinic_name = rtrim($clinicupd,',');
                }else{
                    $clinic_name = '';
                }
                
                if($chages_data == true)
                { 
                    $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,rtrim($proddetails," and"));
                }
                
                header('Location:productlist.php');
                exit;
            }
        }
        
    }else{
        
        if(isset($_POST['clinics']))
        {
            $data['subscription_product_clinic_id'] = implode(',', $_POST['clinics']);
            $clinic_data = implode(',', $_POST['clinics']);
            $data['subscription_product_status'] = '0';
        }else{
            $data['subscription_product_status'] = '0';
            
        }
        
        $data['subscription_product_mode'] = trim($product_mode);
        $allProducts = $stripeObj->createProduct($data);
        //$allProducts = '1';
        if($allProducts->id)
        //if($allProducts == '1')
        {
            $data['subscription_product_stripe_id'] = $allProducts->id;
            //$data['subscription_product_stripe_id'] = $allProducts;
            $data['subscription_product_name'] = $_POST['product_name'];
            $data['subscription_product_stripe_response'] = json_encode($allProducts);
            $product_add  = $subscription_productObj->addRecords($data);
            
            if(!empty($clinic_data))
            {
                $clinicObj = new clinic();
                $cliniclogfields = array('clinic_name');
                $clinicObj->resultAs = 'array';
                $wherelogclinic = "clinic_id IN (".$clinic_data.") ";
                $cliniclogArg = array('fields'=>$cliniclogfields,'where' => $wherelogclinic);
                $allclinic_log = $clinicObj->getAllRecords($cliniclogArg);
                $clinicd =  '';
                foreach($allclinic_log as $ackey => $acvalue)
                {
                    
                    $clinicd .= $acvalue['clinic_name'].",";
                }
                $clinic_name = rtrim($clinicd,',');
            }else{
                $clinic_name = '';
            }
            
            $clinic_product = "<b>Add Record</b> ";    
            if(isset($product_mode) && $product_mode != '')
            {
                $clinic_product.= " <b>Product Mode</b>: ".$product_mode." <b>and</b>";
            }
            if(isset($_POST['product_name']) && $_POST['product_name'] != '')
            {
                $clinic_product.=  " <b>Product Name</b>: ".$_POST['product_name']." <b>and</b>";
            }
            if(isset($clinic_name) && $clinic_name != '')
            {
                $clinic_product.=  " <b>Clinic</b>: ".$clinic_name;
            }
            
            $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,rtrim($clinic_product," and"));
            
            //$product_add = '21';
            if($product_add)
            {
                if($product_mode == 'allinone')
                {
                   $plan_price = trim($_POST['plan_price']);
                   if($plan_price != '' && $plan_price != '0')
                   {
                        
                        for($i=1;$i<=2;$i++)
                        {
                            
                            if($i == '1')
                            {
                                $nickname = 'Standard Plan Monthly';
                                $plan_amount = ($plan_price * 100);
                                $plan_interval = 'month';
                                $final_ammount = $plan_price;
                             }else if($i == '2')
                            {
                                $nickname = 'Standard Plan Yearly';
                                $planyear = ($plan_price * 100);
                                $plan_amount = ($planyear * 12);
                                $final_ammount = ($plan_price * 12);
                                $plan_interval = 'year';
                            }
                            $planadddata=array(
                                'nickname' => $nickname,
                                'amount' => $plan_amount,
                                'currency' => 'cad',
                                'interval' => $plan_interval,
                                'product' => $allProducts->id,
                                //'product' => 'prod_KN1DsAtDOMGJwn',
                            );

                            $createmonthplan= $stripeObj->createPlans($planadddata);
                            
                            if($createmonthplan->id)
                            {
                                $plandata['plan_stripe_id'] = $createmonthplan->id;
                                $plandata['plan_product_id'] = $allProducts->id;
                                //$plandata['plan_product_id'] = 'prod_KN1DsAtDOMGJwn';

                                $plandata['plan_master_plan_id'] = '1';
                                $plandata['plan_amount'] = $final_ammount;

                                $plandata['plan_name'] = $nickname;
                                $plandata['plan_type'] = 'recurring';

                                $plandata['plan_system_type'] = 'standard';
                                $plandata['plan_interval'] = $plan_interval;
                                $plandata['plan_priority'] = '5';
                                $plandata['plan_master_product_id'] = $product_add;

                                $plandata['plan_title'] = 'Front plan';

                                $plandata['plan_stripe_response'] = json_encode($createmonthplan);
                                //print_r($plandata);exit;
                                $planmonthadd  = $subscription_planObj->addRecords($plandata);
                                
                                if($planmonthadd)
                                {
                                    $clinicplandata = "<b>Add Record Plan</b>: ".json_encode($plandata);
                                    $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$clinicplandata);
                                }
                            }
                            
                        }
                        
                        $where = "master_plan_status = 'active' AND master_plan_id !='1'  ";
                        $masterplanArg = array('where' => $where);
                        $allmasterplan = $subscription_master_planObj->getAllRecords($masterplanArg);
                        
                        foreach($allmasterplan as $key => $masterplan)
                        {
                            $fields = array('plan_id','plan_title','plan_img_name','plan_short_desc','plan_breif');
                            $where = "plan_status = 'active' AND plan_master_plan_id ='".$masterplan->master_plan_id."'  ";
                            $planArg = array('fields' => $fields,'where' => $where);
                            $allplandetail = $subscription_planObj->fromFields($planArg);
                            
                            if($masterplan->master_plan_id == '2')
                            {
                                $plan_priority = '2';
                            }else if($masterplan->master_plan_id == '3')
                            {
                                $plan_priority = '3';
                            }else if($masterplan->master_plan_id == '4')
                            {
                                $plan_priority = '4';
                            }
                            else if($masterplan->master_plan_id == '5')
                            {
                                $plan_priority = '1';
                            }
                            else if($masterplan->master_plan_id == '6')
                            {
                                $plan_priority = '6';
                            }
                            
                            for($j=1;$j<=2;$j++)
                            {
                                if($j == '1')
                                {
                                    $planname = $masterplan->master_plan_name.' Monthly';
                                    $plan_amount = '0';
                                    $plan_interval = 'month';
                                    $final_ammount = '0';
                                 }else if($j == '2')
                                {
                                    $planname = $masterplan->master_plan_name.' Yearly';
                                    $final_ammount = '0';
                                    $plan_interval = 'year';
                                }
                                
                                //$masterplandata['plan_stripe_id'] = $product_add."_dummy";
                                $masterplandata['plan_stripe_id'] = "price_dummy";
                                $masterplandata['plan_product_id'] = $allProducts->id;
                                //$masterplandata['plan_product_id'] = 'prod_KN1DsAtDOMGJwn';

                                $masterplandata['plan_master_plan_id'] = $masterplan->master_plan_id;
                                $masterplandata['plan_amount'] = $final_ammount;

                                $masterplandata['plan_name'] = $planname;
                                $masterplandata['plan_type'] = 'recurring';

                                $masterplandata['plan_system_type'] = 'custom';
                                $masterplandata['plan_interval'] = $plan_interval;
                                $masterplandata['plan_priority'] = $plan_priority;
                                $masterplandata['plan_master_product_id'] = $product_add;

                                $masterplandata['plan_title'] = $allplandetail->plan_title;
                                $masterplandata['plan_img_name'] = $allplandetail->plan_img_name;
                                $masterplandata['plan_short_desc'] = $allplandetail->plan_short_desc;
                                $masterplandata['plan_breif'] = $allplandetail->plan_breif;

                                //print_r($masterplandata);
                                $otherplanaddplanadd  = $subscription_planObj->addRecords($masterplandata);
                                if($otherplanaddplanadd)
                                {
                                    $clinicohterplandata = "<b>Add Record Other Plan</b>: ".json_encode($masterplandata);
                                    $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$clinicohterplandata);
                                }

                            }
                            //exit;
                            
                        }
                        
                        
                   }


                }
            }
        }
        if($product_add){
            header('Location:productlist.php');
            exit;
        }
    }
}


// Include Template 
include_once('../libs/routs.php')

?>