# CUSTOMER ORDER BALANCE DEDUCTION ANALYSIS

## Overview
This document analyzes which price list is deducted from the store owner's account when a regular customer places an order from the store page.

---

## Key Finding

**When a customer buys from the store, the ADMIN PRICE (from `agent_pricing_rules` table) is deducted from the store owner's account, NOT the customer price.**

---

## Order Flow Analysis

### Step 1: Customer Places Order (`process_store_order.php`)

**File**: `process_store_order.php` (Lines 65-76)

```php
// Calculate price using CUSTOMER pricing (not agent pricing)
$customerPricingManager = new StoreCustomerPricingManager($conn);
$priceInfo = $customerPricingManager->getPriceForPackage($storeId, $package, $network);

$amount = $priceInfo['price']; // Customer price from store_customer_pricing table
```

**What happens:**
- Uses **CUSTOMER PRICING** from `store_customer_pricing` table
- Customer price is stored in `orders.amount` field
- Order status: `'pending'`
- **NO balance deduction at this stage**

**Price Source**: `store_customer_pricing` table (package-specific pricing)

---

### Step 2: Order Payment Confirmation

When the order is paid (via Paystack or manual confirmation), one of these files processes it:

#### A. Manual Payment Confirmation (`process_pending_order.php`)

**File**: `process_pending_order.php` (Lines 74-119)

```php
// Customer paid store owner's price (stored in order amount)
$customerPaidAmount = floatval($order['amount']); // Store owner's price (what customer paid)

// Calculate admin price (what store owner actually pays)
$externalPricingManager = new ExternalAPIPricingManager($conn);
$adminPrice = $externalPricingManager->getAdminPrice($order['package_size'], $order['network_type']);

// Use admin price for balance debit (fallback to customer paid amount if admin price not available)
$amount = ($adminPrice !== null && $adminPrice > 0) ? $adminPrice : $customerPaidAmount;
```

**What happens:**
1. Gets customer paid amount from `orders.amount` (customer price)
2. Calculates **ADMIN PRICE** using `ExternalAPIPricingManager::getAdminPrice()`
3. **Deducts ADMIN PRICE from store owner's balance** (Line 161)

**Price Source for Deduction**: `agent_pricing_rules` table (admin's base pricing)

#### B. Paystack Payment Callback (`store_paystack_callback.php`)

**File**: `store_paystack_callback.php` (Lines 127-156)

```php
// Calculate admin cost (what store owner needs to pay)
$externalPricingManager = new ExternalAPIPricingManager($conn);
$adminPrice = $externalPricingManager->getAdminPrice($order['package_size'], $order['network_type']);

$amount = floatval($adminPrice);

// Deduct balance
$newBalance = round($currentBalance - $amount, 2);
```

**What happens:**
1. Calculates **ADMIN PRICE** using `ExternalAPIPricingManager::getAdminPrice()`
2. **Deducts ADMIN PRICE from store owner's balance** (Line 167)

**Price Source for Deduction**: `agent_pricing_rules` table (admin's base pricing)

---

## Price Calculation Details

### Admin Price Calculation

**Method**: `ExternalAPIPricingManager::getAdminPrice()`

**Source**: `agent_pricing_rules` table
- Filters: `network_type = ? AND role = 'agent' AND is_active = 1`
- Finds matching range: `min_size_gb <= package_size_gb AND max_size_gb >= package_size_gb`
- Calculates: `price_per_gb × package_size_gb`

**Example:**
- Package: 1GB
- Admin rule: 0.5-2.99GB at GH₵3.50/GB
- Admin price: 1.0 × 3.50 = **GH₵3.50**

---

## Complete Flow Diagram

```
┌─────────────────────────────────────────────────────────────┐
│           CUSTOMER PLACES ORDER (store.php)                 │
│  ┌──────────────────────────────────────────────────────┐  │
│  │ 1. Uses CUSTOMER PRICING                             │  │
│  │    Source: store_customer_pricing table              │  │
│  │    Example: 1GB = GH₵5.00 (customer price)          │  │
│  │ 2. Stores in orders.amount = GH₵5.00                │  │
│  │ 3. Order status = 'pending'                          │  │
│  │ 4. NO balance deduction yet                          │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│         CUSTOMER PAYS (Paystack or Manual)                 │
│  ┌──────────────────────────────────────────────────────┐  │
│  │ 1. Payment confirmed                                 │  │
│  │ 2. Order status changes to 'processing'              │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│      BALANCE DEDUCTION (process_pending_order.php)         │
│  ┌──────────────────────────────────────────────────────┐  │
│  │ 1. Calculates ADMIN PRICE                             │  │
│  │    Source: agent_pricing_rules table                 │  │
│  │    Example: 1GB = GH₵3.50 (admin price)             │  │
│  │ 2. Deducts ADMIN PRICE from store owner balance      │  │
│  │    Balance -= GH₵3.50 (NOT GH₵5.00)                  │  │
│  │ 3. Logs balance history                               │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

---

## Price Comparison Example

### Scenario: Customer buys 1GB package

| Stage | Price Type | Amount | Source Table | Purpose |
|-------|-----------|--------|--------------|---------|
| **Order Creation** | Customer Price | GH₵5.00 | `store_customer_pricing` | What customer pays |
| **Balance Deduction** | Admin Price | GH₵3.50 | `agent_pricing_rules` | What store owner pays |
| **Store Owner Profit** | Difference | GH₵1.50 | Calculated | Profit margin |

---

## Code References

### Customer Price (What Customer Pays)
- **File**: `process_store_order.php` (Line 68)
- **Method**: `StoreCustomerPricingManager::getPriceForPackage()`
- **Table**: `store_customer_pricing`
- **Stored in**: `orders.amount`

### Admin Price (What Store Owner Pays)
- **File**: `process_pending_order.php` (Line 79)
- **File**: `store_paystack_callback.php` (Line 146)
- **Method**: `ExternalAPIPricingManager::getAdminPrice()`
- **Table**: `agent_pricing_rules`
- **Used for**: Balance deduction

---

## Important Notes

1. **Customer pays customer price** (from `store_customer_pricing`)
2. **Store owner's balance is debited with admin price** (from `agent_pricing_rules`)
3. **Profit margin** = Customer Price - Admin Price
4. **If admin price not found**, system falls back to customer paid amount (Line 119 in `process_pending_order.php`)

---

## Fallback Behavior

If admin price cannot be calculated:

```php
// Use admin price for balance debit (fallback to customer paid amount if admin price not available)
$amount = ($adminPrice !== null && $adminPrice > 0) ? $adminPrice : $customerPaidAmount;
```

**Fallback**: Uses customer paid amount (from `orders.amount`) if admin price is not available.

---

## Summary

**Question**: Which price list is subtracted from store owner's account when customer buys from store?

**Answer**: **ADMIN PRICE** from `agent_pricing_rules` table (admin's base pricing), NOT the customer price.

**Flow**:
1. Customer pays → Customer price (from `store_customer_pricing`)
2. Store owner balance deducted → Admin price (from `agent_pricing_rules`)
3. Store owner profit → Customer price - Admin price

This ensures store owners always pay the admin's base price, regardless of what they charge customers.

