false, 'message' => 'Please Log In']); exit(); } $Request['SESSION']['PHPSESSID'] = $_POST['DUMMYSESSID']; $Request['SESSION']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; include_once './Home_include.php'; PAWebAdminSessionInfo($Request, $Response); if ($Response['SESSION']['Active'] == 0) { echo json_encode(['status' => false, 'message' => 'Session expired']); exit(); } $data = []; require_once __DIR__ . '/PA_SHOP_SUBSCRIPTION_HEALTH.php'; require_once __DIR__ . '/PA_SHOP_FULFILLMENT.php'; if (($_POST['action'] ?? '') === 'billing_control_history') { $id=$_POST['subscription_id']??''; if(!is_string($id)||!preg_match('/^[1-9][0-9]{0,17}$/D',$id)){ echo json_encode(['status'=>false,'message'=>'Invalid subscription reference.']);exit(); } try{ $s=$PAAPP_CONFIG_DB_LINK->prepare('SELECT Action AS action,ServiceMode AS service_mode,AlertAcknowledged AS alert_acknowledged,State AS state,AdminID AS admin_id,Reason AS reason,LastErrorCode AS error_code,InsertDateTimeUTC AS started_utc,UpdateDateTimeUTC AS updated_utc FROM PA_ShopBillingControl WHERE SubscriptionID=? ORDER BY InsertDateTimeUTC DESC,RequestID DESC LIMIT 20'); if(!$s||!$s->execute([$id]))throw new RuntimeException('History unavailable'); echo json_encode(['status'=>true,'data'=>['rows'=>$s->fetchAll(PDO::FETCH_ASSOC),'limit'=>20]]); }catch(Throwable $e){echo json_encode(['status'=>false,'message'=>'Billing history is unavailable.']);} exit(); } if (($_POST['action'] ?? '') === 'activation_history') { try { $history = PAShopActivationHistory($PAAPP_CONFIG_DB_LINK, $_POST['transaction_id'] ?? ''); $history['recovery_allowed']=false; if(($PASYSCONF['SHOP']['ACTIVATION']['Enabled']??false)===true && ($history['recovery']['code']??'')==='billing_confirmation'){ require_once '/opt/SA/DEV/WEB/SHOP/wp-content/plugins/pa-device-transaction/PA_SHOP_ACTIVATION_RECOVERY.php'; $gate=PAShopActivationRecovery::effectiveGate($PASYSCONF['SHOP']??[]); $preflight=new PAShopActivationRecovery($PAAPP_CONFIG_DB_LINK,function(){return false;},function(){return false;},$gate); try{$preflight->inspect((int)$Response['SESSION']['AdminID'],(int)$_POST['transaction_id']);$history['recovery_allowed']=true;}catch(Throwable $denied){} } echo json_encode(['status' => true, 'data' => $history]); } catch (Throwable $historyError) { echo json_encode(['status' => false, 'message' => 'Activation history is unavailable. Refresh the report and try again.']); } exit(); } $data['activation_health'] = PAShopActivationHealth($PAAPP_CONFIG_DB_LINK); $data['service_action_health'] = PAShopServiceActionHealth($PAAPP_CONFIG_DB_LINK); try { require_once __DIR__ . '/PA_SHOP_RENEWAL_REVIEW_QUEUE.php'; $data['renewal_review'] = PAShopRenewalReviewQueue($PAAPP_CONFIG_DB_LINK); $replacementGate=$PASYSCONF['SHOP']['REPLACEMENT_REFUND_DECISION']??[]; $replacementAllowed=($replacementGate['Enabled']??false)===true &&($replacementGate['Policy']??'')==='manual_replacement_refund_v1' &&is_array($replacementGate['AllowedAdminIDs']??null) &&is_array($replacementGate['AllowedClientIDs']??null) &&in_array((int)$Response['SESSION']['AdminID'],$replacementGate['AllowedAdminIDs'],true); $data['renewal_review']['actions_enabled']=$replacementAllowed; $data['renewal_review']['suspension_enabled']=$replacementAllowed &&($replacementGate['AllowServiceSuspension']??false)===true; foreach ($data['renewal_review']['rows'] as &$reviewRow) { $reviewRow['decision_available']=$replacementAllowed &&in_array((int)($reviewRow['client_id']??0),$replacementGate['AllowedClientIDs']??[],true) &&($reviewRow['kind']??'')==='replacement' &&($reviewRow['state']??'')==='succeeded' &&(int)($reviewRow['review_required']??0)===1 &&(int)($reviewRow['refund_count']??0)>0 &&empty($reviewRow['replacement_decision_state']); } unset($reviewRow); } catch (Throwable $reviewError) { $data['renewal_review'] = ['available'=>false,'pending_count'=>null,'rows'=>[], 'limit'=>25,'actions_enabled'=>false]; } $paidRecoveryGate=$PASYSCONF['SHOP']['REPLACEMENT_PAYMENT_RECOVERY']??[]; $restorationGate=$PASYSCONF['SHOP']['RENEWAL_RESTORATION']??[]; $data['paid_replacement_recovery_available']=($paidRecoveryGate['Enabled']??false)===true &&($paidRecoveryGate['Policy']??'')==='manual_paid_replacement_v1' &&is_array($paidRecoveryGate['AllowedAdminIDs']??null) &&is_array($paidRecoveryGate['AllowedClientIDs']??null) &&in_array((int)$Response['SESSION']['AdminID'],$paidRecoveryGate['AllowedAdminIDs'],true) &&($restorationGate['Enabled']??false)===true &&($restorationGate['Policy']??'')==='verified_replacement_restoration_v1' &&($PASYSCONF['SHOP']['RENEWAL']['Enabled']??false)===true &&($PASYSCONF['SHOP']['ACTIVATION']['Enabled']??false)===true; $reconciliationGate=$PASYSCONF['SHOP']['RENEWAL_RECONCILIATION']??[]; $data['renewal_reconciliation_available']=($reconciliationGate['Enabled']??false)===true &&($reconciliationGate['Policy']??'')==='carrier_confirmed_backend_v1' &&is_array($reconciliationGate['AllowedAdminIDs']??null) &&is_array($reconciliationGate['AllowedClientIDs']??null) &&in_array((int)$Response['SESSION']['AdminID'],$reconciliationGate['AllowedAdminIDs'],true) &&($restorationGate['Enabled']??false)===true &&($restorationGate['Policy']??'')==='verified_replacement_restoration_v1' &&($PASYSCONF['SHOP']['RENEWAL']['Enabled']??false)===true &&($PASYSCONF['SHOP']['ACTIVATION']['Enabled']??false)===true; $billingGate=$PASYSCONF['SHOP']['BILLING_CONTROL']??[]; try{require_once __DIR__.'/PA_SHOP_ADMIN_GATE.php';$billingGate=PAShopAdminGate::resolve($PAAPP_CONFIG_DB_LINK,$PASYSCONF,'BILLING_CONTROL',(int)$Response['SESSION']['AdminID']);}catch(Throwable $e){$billingGate=[];} $data['billing_control_available']=($billingGate['Enabled']??false)===true &&($billingGate['PausePolicy']??'')==='billing_only_keep_paid_dates' &&is_array($billingGate['AllowedAdminIDs']??null) &&in_array((int)$Response['SESSION']['AdminID'],$billingGate['AllowedAdminIDs'],true); $data['service_suspension_available']=$data['billing_control_available'] &&($billingGate['AllowServiceSuspension']??false)===true; $unitHealthSQL = PAShopSubscriptionUnitHealthSQL(); $unitCount = []; PACommonDBSelectRecord('SELECT COUNT(*) AS cnt FROM (' . $unitHealthSQL . ') unit_health', $unitCount, $c, $e, $s); $unitHealthError = !empty($e); $unitRows = []; if (!$unitHealthError) { PACommonDBSelectMultipleRecords($unitHealthSQL . ' ORDER BY o.id, i.order_item_id LIMIT 100', $unitRows, $c, $e, $s); $unitHealthError = !empty($e); } if (is_array($unitRows) && isset($unitRows['subscription_id'])) $unitRows = [$unitRows]; $data['subscription_unit_health'] = [ 'available' => !$unitHealthError, 'mismatch_count' => $unitHealthError ? null : intval($unitCount['cnt'] ?? 0), 'rows' => $unitHealthError ? [] : ($unitRows ?? []), 'limit' => 100 ]; // ── Executive summary metrics ─────────────────────────────────────────────── $q = "SELECT COALESCE(SUM(total_amount),0) AS v FROM wp_wc_orders WHERE type='shop_order' AND status IN ('wc-completed','wc-processing')"; PACommonDBSelectRecord($q, $d, $c, $e, $s); $data['total_revenue'] = round((float)($d['v'] ?? 0), 2); $q = "SELECT COALESCE(SUM(total_amount),0) AS v FROM wp_wc_orders WHERE type='shop_order' AND status IN ('wc-completed','wc-processing') AND date_created_gmt >= DATE_FORMAT(NOW(),'%Y-%m-01')"; PACommonDBSelectRecord($q, $d, $c, $e, $s); $data['revenue_this_month'] = round((float)($d['v'] ?? 0), 2); $q = "SELECT COUNT(*) AS v FROM wp_wc_orders WHERE type='shop_order' AND status IN ('wc-completed','wc-processing') AND date_created_gmt >= DATE_FORMAT(NOW(),'%Y-%m-01')"; PACommonDBSelectRecord($q, $d, $c, $e, $s); $data['orders_this_month'] = intval($d['v'] ?? 0); $q = "SELECT COUNT(*) AS v FROM wp_wc_orders o WHERE type='shop_order' AND status='wc-processing' AND ".PAShopFulfillment::physicalOrderSQL(); PACommonDBSelectRecord($q, $d, $c, $e, $s); $data['pending_orders'] = intval($d['v'] ?? 0); $q = "SELECT COUNT(*) AS v FROM Client WHERE RecordStatus = 1 AND InsertDateTime >= DATE_FORMAT(NOW(),'%Y-%m-01')"; PACommonDBSelectRecord($q, $d, $c, $e, $s); $data['new_clients_this_month'] = intval($d['v'] ?? 0); // ── 1. Monthly Revenue — last 12 months ────────────────────────────────── $q = "SELECT DATE_FORMAT(date_created_gmt,'%Y-%m') AS month, ROUND(SUM(total_amount),2) AS revenue, COUNT(*) AS orders FROM wp_wc_orders WHERE type='shop_order' AND status IN ('wc-completed','wc-processing') AND date_created_gmt >= DATE_SUB(NOW(), INTERVAL 12 MONTH) GROUP BY DATE_FORMAT(date_created_gmt,'%Y-%m') ORDER BY month ASC"; $revMonth = null; PACommonDBSelectMultipleRecords($q, $revMonth, $c, $e, $s); $data['revenue_monthly'] = $revMonth ?? []; // ── 2. Orders by Status ─────────────────────────────────────────────────── $q = "SELECT status, COUNT(*) AS cnt FROM wp_wc_orders WHERE type='shop_order' GROUP BY status ORDER BY cnt DESC"; $ordStatus = null; PACommonDBSelectMultipleRecords($q, $ordStatus, $c, $e, $s); $data['orders_by_status'] = $ordStatus ?? []; // ── 3. Product Performance ──────────────────────────────────────────────── $q = "SELECT oi.order_item_name AS product, COUNT(*) AS units, ROUND(SUM(CAST(m.meta_value AS DECIMAL(10,2))),2) AS revenue FROM wp_woocommerce_order_items oi JOIN wp_woocommerce_order_itemmeta m ON m.order_item_id = oi.order_item_id AND m.meta_key = '_line_total' JOIN wp_wc_orders o ON o.id = oi.order_id WHERE oi.order_item_type='line_item' AND o.type='shop_order' AND o.status IN ('wc-completed','wc-processing') GROUP BY oi.order_item_name ORDER BY revenue DESC"; $prodPerf = null; PACommonDBSelectMultipleRecords($q, $prodPerf, $c, $e, $s); $data['product_performance'] = $prodPerf ?? []; // ── 4. New Clients per Month — last 12 months ───────────────────────────── $q = "SELECT DATE_FORMAT(STR_TO_DATE(InsertDateTime,'%Y-%m-%d'),'%Y-%m') AS month, COUNT(*) AS new_clients FROM Client WHERE RecordStatus = 1 AND InsertDateTime >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 12 MONTH),'%Y-%m-01') GROUP BY DATE_FORMAT(STR_TO_DATE(InsertDateTime,'%Y-%m-%d'),'%Y-%m') ORDER BY month ASC"; $newClients = null; PACommonDBSelectMultipleRecords($q, $newClients, $c, $e, $s); $data['new_clients_monthly'] = $newClients ?? []; // ── 5. Subscription Health ──────────────────────────────────────────────── $q = "SELECT IFNULL(SubscriptionStatus,'pending') AS status, COUNT(*) AS cnt FROM ClientDeviceTransaction WHERE TransactionType='subscription' GROUP BY SubscriptionStatus"; $subHealth = null; PACommonDBSelectMultipleRecords($q, $subHealth, $c, $e, $s); $data['subscription_health'] = $subHealth ?? []; $q = "SELECT COUNT(*) AS v FROM ClientDeviceTransaction WHERE TransactionType='subscription' AND SubscriptionStatus='active' AND EndDateTime BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)"; PACommonDBSelectRecord($q, $d, $c, $e, $s); $data['expiring_30'] = intval($d['v'] ?? 0); $q = "SELECT COUNT(*) AS v FROM ClientDeviceTransaction WHERE TransactionType='subscription' AND SubscriptionStatus='active' AND EndDateTime BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 60 DAY)"; PACommonDBSelectRecord($q, $d, $c, $e, $s); $data['expiring_60'] = intval($d['v'] ?? 0); $q = "SELECT COUNT(*) AS v FROM ClientDeviceTransaction WHERE TransactionType='subscription' AND SubscriptionStatus='active' AND EndDateTime BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 90 DAY)"; PACommonDBSelectRecord($q, $d, $c, $e, $s); $data['expiring_90'] = intval($d['v'] ?? 0); // ── 6. Top 10 Customers by spend ───────────────────────────────────────── $q = "SELECT c.ClientID, o.billing_email, CONCAT(IFNULL(a.first_name,''),' ',IFNULL(a.last_name,'')) AS customer_name, COUNT(DISTINCT o.id) AS order_count, ROUND(SUM(o.total_amount),2) AS total_spent FROM wp_wc_orders o LEFT JOIN wp_wc_order_addresses a ON a.order_id = o.id AND a.address_type = 'billing' LEFT JOIN Client c ON c.UserName = o.billing_email COLLATE utf8mb4_unicode_520_ci WHERE o.type='shop_order' AND o.status IN ('wc-completed','wc-processing') GROUP BY o.billing_email, c.ClientID, a.first_name, a.last_name ORDER BY total_spent DESC LIMIT 10"; $topCust = null; PACommonDBSelectMultipleRecords($q, $topCust, $c, $e, $s); $data['top_customers'] = $topCust ?? []; // ── 7. Cancelled & Not-Renewed Subscriptions ───────────────────────────── $q = "SELECT cdt.ClientID, c.UserName AS email, cdt.TransactionDate, cdt.EndDateTime, cdt.SubscriptionStatus FROM ClientDeviceTransaction cdt LEFT JOIN Client c ON c.ClientID = cdt.ClientID WHERE cdt.TransactionType='subscription' AND cdt.SubscriptionStatus IN ('cancelled','not_renewed') ORDER BY cdt.UpdateDateTime DESC LIMIT 20"; $lostSubs = null; PACommonDBSelectMultipleRecords($q, $lostSubs, $c, $e, $s); $data['lost_subscriptions'] = $lostSubs ?? []; $data['lost_subscription_count'] = is_array($lostSubs) ? intval($c) : 0; echo json_encode(['status' => true, 'data' => $data]); ?>