<?php 
// Include main file
include_once('../libs/main.php');
// Check admin Login
include_once('checkLogin.php');
// Logical section of page
$subscription_planObj =  new  subscriptions_subscribed();

$stripeObj   = new stripePay();
$adminlogObj = new admin_log();
$modulepagesObj = new module_pages();

$filename=basename($_SERVER['SCRIPT_FILENAME']);
if($filename == 'planadd.php')
{
    $module_id = $adminlogObj->getModuleId($filename);
    $page_id = $adminlogObj->getPageId($filename);
    $allpages = $modulepagesObj->fromId($page_id);
    $pagename = $allpages->page;
}


if(isset($_REQUEST['act']) && $_REQUEST['act']=='edit' && isset($_REQUEST['subs_id'])){
    
    $subDetail           = $subscription_planObj->fromId($_REQUEST['subs_id']);
    $clinicId            = $subDetail->subscribed_clinic_id;
    $subscribedId        = $subDetail->subscribed_subscription_id;
    $subs_id             = $_REQUEST['subs_id'];
    $clinicObj           = new clinic();
    $clinicObj->resultAs = 'array';
    $clinicfields        = array('user_stripedata');
    $tables              = array('tbl_user u');
    $jfields             = array('u.user_id = c.clinic_user_id');
    $jtype               = array("INNER"); 
    $clinicwhere         = array(
        'clinic_id=' => $clinicId
    );
    $clinicArg    = array('fields'=>$clinicfields,'where' => $clinicwhere,'joinTables' =>$tables, 'joinFields' =>$jfields, 'joinTypes' => $jtype);
    $stripeCustomerdata = $clinicObj->fromFields($clinicArg);
    if($stripeCustomerdata['user_stripedata']!="" && is_array(json_decode($stripeCustomerdata['user_stripedata'],1))){
        if(array_key_exists("customerId", json_decode($stripeCustomerdata['user_stripedata'],1))){
            $customerData = json_decode($stripeCustomerdata['user_stripedata'],1);
            $stripeCustomerId = $customerData['customerId'];
            if(isset($stripeCustomerId) && $stripeCustomerId != '')
            {
                $creditbalancedata = $stripeObj->creditBalance($stripeCustomerId);
                //print_r($creditbalancedata);exit;
                if(!empty($creditbalancedata->data))
                {    
                    $creditbalance = ltrim($creditbalancedata->data[0]->ending_balance/100,"-");    
                }else{
                    $creditbalance = '0';
                }
                
            }
        }
        
    }else{
        $creditbalance = '0';
    }

    /*Subscriptions details*/
    $subscriptiondata = $stripeObj->getSubscription($subscribedId);
    if(isset($subscriptiondata['discount'])){
        $appliedCoupon = $subscriptiondata['discount']['coupon']['id'];
    }else{
        $appliedCoupon = '';
    }
}

/*add credit blanace*/
if(isset($_REQUEST['act']) && $_REQUEST['act']=='adddebitcredit'){
    $data['add_debit_amount'] = -($_REQUEST['add_debit_amount'] * 100) ;
    $data['customer']         = $_REQUEST['customer'];
    $data['subs_id']          = $_REQUEST['subs_id'];

    $addcreditbalancedata = $stripeObj->addCreditBalance($data);
    if(isset($addcreditbalancedata) && isset($addcreditbalancedata->id))
        echo "Credit Added";
    else
        echo "Something Went Wrong";
    exit;
}   
/*add credit blanace end*/

/*Debit credit blanace*/
if(isset($_REQUEST['act']) && $_REQUEST['act']=='debitcredit'){
    $data['add_debit_amount'] = $_REQUEST['add_debit_amount'] * 100 ;
    $data['customer']         = $_REQUEST['customer'];
    $data['subs_id']          = $_REQUEST['subs_id'];

    $addcreditbalancedata = $stripeObj->addCreditBalance($data);
    if(isset($addcreditbalancedata) && isset($addcreditbalancedata->id))
        echo "Debited Successfully";
    else
        echo "Something Went Wrong";
    exit;
}   
/*debit credit blanace end*/



/*Retrieve subscription data start*/
if(isset($_REQUEST['act']) && $_REQUEST['act']=='retrievesubs'){
    $subscribedID          = $_REQUEST['subscribedID'];

    $subscriptiondata = $stripeObj->getSubscription($subscribedID);

    //echo "<pre>";print_r($subscriptiondata);echo "</pre>";
    
    exit();
}   
/*Retrieve subscription data start end*/

/*Add coupon to subscription start*/
if(isset($_REQUEST['act']) && $_REQUEST['act']=='addcoupon'){
    $subscribedID = $_REQUEST['subsID'];
    $couponname   = $_REQUEST['couponname'];
    $subs_id      = $_REQUEST['subs_id'];//primary key

    $subscriptioncoupondata = $stripeObj->updateSubscriptionCouponData($subscribedID,$couponname);
    if($subscriptioncoupondata){

        $upgradsubData['subscribed_tstart_date'] = date('Y-m-d');
        $upgradsubData['subscribed_tend_date']   = $_REQUEST['trialenddate'];
        $upgradsubData['subscribed_tperiod']     = dateDiff($upgradsubData['subscribed_tstart_date'],$upgradsubData['subscribed_tend_date']);
        $updateoldsubscription                   = $subscription_planObj->updateRecords($upgradsubData,$subs_id);

        echo "Coupon Added Successfully";
    }
    else
        echo "Something Went Wrong";
    
    exit();
}   
/*Add coupon to subscription end*/

/*Add Trial start*/
if(isset($_REQUEST['act']) && $_REQUEST['act']=='addtrial'){
    $subscribedID = $_REQUEST['subsID'];
    $subs_id      = $_REQUEST['subs_id'];//primary key
    $trialend     = strtotime($_REQUEST['trialenddate']);

    $subscriptiontrialenddata = $stripeObj->updateSubscriptiontrialendData($subscribedID,$trialend);
    if($subscriptiontrialenddata){
        //$upgradsubId                           = $subscriptioDatachk['subscribed_id'];
        $upgradsubData['subscribed_tstart_date'] = date('Y-m-d');
        $upgradsubData['subscribed_tend_date']   = $_REQUEST['trialenddate'];
        $upgradsubData['subscribed_tperiod']     = dateDiff($upgradsubData['subscribed_tstart_date'],$upgradsubData['subscribed_tend_date']);
        //echo "<pre>";print_r($upgradsubData['subscribed_tperiod']);echo "</pre>";
        $updateoldsubscription                   = $subscription_planObj->updateRecords($upgradsubData,$subs_id);
        echo "Trial Added Successfully";
    }
    else
        echo "Something Went Wrong";
    exit;
} 
/*Add trial end*/

/*Cancel Subscription*/
if(isset($_REQUEST['act']) && $_REQUEST['act']=='cancel_subscription'){
    $subs_id = $_REQUEST['subs_id'];
    $stripe_sub_id = isset($_REQUEST['stripe_sub_id']) ? $_REQUEST['stripe_sub_id'] : '';
    
    // 1. Cancel in Stripe
    if($stripe_sub_id != '' && $stripe_sub_id != '0'){
         try {
            $stripeObj->cancelSubscription($stripe_sub_id);
         } catch (Exception $e) {
             // Log error but continue
         }
    }
    
    // 2. Find Basic Plan ID
    $planObj = new subscription_plans();
    $basicPlans = $planObj->getAllRecords(array('where' => "plan_name LIKE '%Basic%' AND plan_status='active'", 'limit'=>array('start'=>0,'record'=>1)));
    
    $basicPlanId = 0;
    if($basicPlans && count($basicPlans) > 0){
        $basicPlanId = $basicPlans[0]->plan_id;
    } else {
        // Fallback to ID 1 if Basic plan not found by name
        $basicPlanId = 1; 
    }
   
    $data = array(
        'subscribed_plan_id' => $basicPlanId,
        'subscribed_status' => 'active'
    );
    
    $rs = $subscription_planObj->updateRecords($data, $subs_id);
    if($rs){
        echo "Success: Subscription cancelled and reverted to Basic Plan.";
    } else {
        echo "Error: Database update failed.";
    }
    exit;
}

function dateDiff($date1, $date2)
{
    $date1_ts = strtotime($date1);
    $date2_ts = strtotime($date2);
    $diff = $date2_ts - $date1_ts;
    return round($diff / 86400);
}

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

?>