<?php
/**
 * AUTO TESTER - Pricing Management API
 * Handles all pricing operations including CRUD, rules, and analytics
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../database/functions/Database.php';

class PricingSystem {
    private $db;
    private $currentUser;
    
    public function __construct() {
        $this->db = Database::getInstance();
        $this->currentUser = $this->getCurrentUser();
    }
    
    /**
     * Get current authenticated user
     */
    private function getCurrentUser() {
        $headers = getallheaders();
        $token = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (empty($token)) {
            return null;
        }
        
        $token = str_replace('Bearer ', '', $token);
        
        try {
            $stmt = $this->db->prepare("
                SELECT id, role, permissions, full_name, email, status 
                FROM users 
                WHERE api_token = ? AND status = 'active'
            ");
            $stmt->execute([$token]);
            return $stmt->fetch();
        } catch (Exception $e) {
            return null;
        }
    }
    
    /**
     * Check if user has permission for pricing action
     */
    private function hasPermission($permission) {
        if (!$this->currentUser) {
            return false;
        }
        
        $role = $this->currentUser['role'];
        
        switch ($permission) {
            case 'view_pricing':
                return in_array($role, ['admin', 'supervisor']);
            case 'manage_pricing':
                return $role === 'admin';
            case 'view_analytics':
                return in_array($role, ['admin', 'supervisor']);
            case 'manage_rules':
                return $role === 'admin';
            default:
                return false;
        }
    }
    
    /**
     * Get all services with current pricing
     */
    public function getServices($includeInactive = false) {
        if (!$this->hasPermission('view_pricing')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $activeCondition = $includeInactive ? '' : 'AND s.is_active = 1';
            
            $stmt = $this->db->prepare("
                SELECT 
                    s.*,
                    sp.price_amount,
                    sp.currency,
                    sp.pricing_unit,
                    sp.valid_from,
                    sp.valid_until,
                    sp.is_active as price_active,
                    CASE 
                        WHEN sp.valid_until IS NULL OR sp.valid_until >= CURRENT_DATE THEN 'current'
                        ELSE 'expired'
                    END as price_status
                FROM services s
                LEFT JOIN service_pricing sp ON s.id = sp.service_id 
                    AND sp.pricing_type = 'base_price' 
                    AND sp.is_active = 1
                    AND (sp.valid_until IS NULL OR sp.valid_until >= CURRENT_DATE)
                WHERE 1=1 $activeCondition
                ORDER BY s.sort_order, s.service_name_ar
            ");
            $stmt->execute();
            $services = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $services];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get service pricing details
     */
    public function getServicePricing($serviceId) {
        if (!$this->hasPermission('view_pricing')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Get base pricing
            $stmt = $this->db->prepare("
                SELECT sp.*, s.service_name_ar, s.service_name_en
                FROM service_pricing sp
                JOIN services s ON sp.service_id = s.id
                WHERE sp.service_id = ? 
                AND sp.pricing_type = 'base_price'
                AND sp.is_active = 1
                ORDER BY sp.valid_from DESC
            ");
            $stmt->execute([$serviceId]);
            $basePricing = $stmt->fetchAll();
            
            // Get vehicle type pricing
            $stmt = $this->db->prepare("
                SELECT sp.*
                FROM service_pricing sp
                WHERE sp.service_id = ? 
                AND sp.pricing_type = 'vehicle_type'
                AND sp.is_active = 1
                ORDER BY sp.vehicle_type
            ");
            $stmt->execute([$serviceId]);
            $vehiclePricing = $stmt->fetchAll();
            
            // Get additional services pricing
            $stmt = $this->db->prepare("
                SELECT sp.*
                FROM service_pricing sp
                WHERE sp.service_id = ? 
                AND sp.pricing_type = 'additional_service'
                AND sp.is_active = 1
                ORDER BY sp.price_amount
            ");
            $stmt->execute([$serviceId]);
            $additionalPricing = $stmt->fetchAll();
            
            return [
                'success' => true,
                'data' => [
                    'base_pricing' => $basePricing,
                    'vehicle_pricing' => $vehiclePricing,
                    'additional_pricing' => $additionalPricing
                ]
            ];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Create new service
     */
    public function createService($data) {
        if (!$this->hasPermission('manage_pricing')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Validate required fields
            $required = ['service_code', 'service_name_ar', 'service_name_en', 'service_category'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Check if service code already exists
            $stmt = $this->db->prepare("SELECT id FROM services WHERE service_code = ?");
            $stmt->execute([$data['service_code']]);
            if ($stmt->fetch()) {
                return ['success' => false, 'message' => 'Service code already exists'];
            }
            
            // Insert service
            $stmt = $this->db->prepare("
                INSERT INTO services 
                (service_code, service_name_ar, service_name_en, service_description_ar, 
                 service_description_en, service_category, service_type, duration_minutes,
                 inspection_points, requires_appointment, icon_class, image_url,
                 tags, sort_order, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $result = $stmt->execute([
                $data['service_code'],
                $data['service_name_ar'],
                $data['service_name_en'],
                $data['service_description_ar'] ?? '',
                $data['service_description_en'] ?? '',
                $data['service_category'],
                $data['service_type'] ?? 'standard',
                $data['duration_minutes'] ?? 60,
                $data['inspection_points'] ?? 0,
                $data['requires_appointment'] ?? true,
                $data['icon_class'] ?? 'fas fa-car',
                $data['image_url'] ?? '',
                json_encode($data['tags'] ?? []),
                $data['sort_order'] ?? 0,
                $this->currentUser['id']
            ]);
            
            if ($result) {
                $serviceId = $this->db->lastInsertId();
                
                // Create base pricing if provided
                if (isset($data['base_price'])) {
                    $this->createServicePricing($serviceId, [
                        'pricing_type' => 'base_price',
                        'price_amount' => $data['base_price'],
                        'currency' => $data['currency'] ?? 'EGP',
                        'pricing_unit' => $data['pricing_unit'] ?? 'per_service'
                    ]);
                }
                
                return [
                    'success' => true, 
                    'message' => 'Service created successfully',
                    'service_id' => $serviceId
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to create service'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Update service
     */
    public function updateService($serviceId, $data) {
        if (!$this->hasPermission('manage_pricing')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Build update query dynamically
            $updateFields = [];
            $updateValues = [];
            
            $allowedFields = [
                'service_name_ar', 'service_name_en', 'service_description_ar', 
                'service_description_en', 'service_category', 'service_type', 
                'duration_minutes', 'inspection_points', 'requires_appointment',
                'icon_class', 'image_url', 'is_active', 'is_featured', 'sort_order'
            ];
            
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updateFields[] = "$field = ?";
                    $updateValues[] = $data[$field];
                }
            }
            
            if (isset($data['tags'])) {
                $updateFields[] = "tags = ?";
                $updateValues[] = json_encode($data['tags']);
            }
            
            if (empty($updateFields)) {
                return ['success' => false, 'message' => 'No valid fields to update'];
            }
            
            $updateFields[] = "updated_by = ?";
            $updateValues[] = $this->currentUser['id'];
            $updateValues[] = $serviceId;
            
            $sql = "UPDATE services SET " . implode(', ', $updateFields) . " WHERE id = ?";
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute($updateValues);
            
            if ($result) {
                return ['success' => true, 'message' => 'Service updated successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to update service'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Create or update service pricing
     */
    public function createServicePricing($serviceId, $data) {
        if (!$this->hasPermission('manage_pricing')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Validate required fields
            $required = ['pricing_type', 'price_amount'];
            foreach ($required as $field) {
                if (!isset($data[$field])) {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Insert pricing
            $stmt = $this->db->prepare("
                INSERT INTO service_pricing 
                (service_id, pricing_type, price_amount, currency, pricing_unit,
                 vehicle_type, vehicle_age_min, vehicle_age_max, engine_size_min,
                 engine_size_max, location_type, customer_type, min_quantity,
                 max_quantity, valid_from, valid_until, is_active,
                 price_description_ar, price_description_en, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $result = $stmt->execute([
                $serviceId,
                $data['pricing_type'],
                $data['price_amount'],
                $data['currency'] ?? 'EGP',
                $data['pricing_unit'] ?? 'per_service',
                $data['vehicle_type'] ?? 'all',
                $data['vehicle_age_min'] ?? 0,
                $data['vehicle_age_max'] ?? 0,
                $data['engine_size_min'] ?? 0,
                $data['engine_size_max'] ?? 0,
                $data['location_type'] ?? 'center',
                $data['customer_type'] ?? 'all',
                $data['min_quantity'] ?? 1,
                $data['max_quantity'] ?? 1,
                $data['valid_from'] ?? date('Y-m-d'),
                $data['valid_until'] ?? null,
                $data['is_active'] ?? true,
                $data['price_description_ar'] ?? '',
                $data['price_description_en'] ?? '',
                $this->currentUser['id']
            ]);
            
            if ($result) {
                $pricingId = $this->db->lastInsertId();
                
                // Log pricing change
                $this->logPricingChange($serviceId, $pricingId, 'created', null, $data['price_amount']);
                
                return [
                    'success' => true, 
                    'message' => 'Pricing created successfully',
                    'pricing_id' => $pricingId
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to create pricing'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Update service pricing
     */
    public function updateServicePricing($pricingId, $data) {
        if (!$this->hasPermission('manage_pricing')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Get current pricing for history
            $stmt = $this->db->prepare("SELECT * FROM service_pricing WHERE id = ?");
            $stmt->execute([$pricingId]);
            $currentPricing = $stmt->fetch();
            
            if (!$currentPricing) {
                return ['success' => false, 'message' => 'Pricing not found'];
            }
            
            // Build update query
            $updateFields = [];
            $updateValues = [];
            
            $allowedFields = [
                'price_amount', 'currency', 'pricing_unit', 'vehicle_type',
                'vehicle_age_min', 'vehicle_age_max', 'engine_size_min',
                'engine_size_max', 'location_type', 'customer_type',
                'min_quantity', 'max_quantity', 'valid_from', 'valid_until',
                'is_active', 'price_description_ar', 'price_description_en'
            ];
            
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updateFields[] = "$field = ?";
                    $updateValues[] = $data[$field];
                }
            }
            
            if (empty($updateFields)) {
                return ['success' => false, 'message' => 'No valid fields to update'];
            }
            
            $updateFields[] = "updated_by = ?";
            $updateValues[] = $this->currentUser['id'];
            $updateValues[] = $pricingId;
            
            $sql = "UPDATE service_pricing SET " . implode(', ', $updateFields) . " WHERE id = ?";
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute($updateValues);
            
            if ($result) {
                // Log price change if amount changed
                if (isset($data['price_amount']) && $data['price_amount'] != $currentPricing['price_amount']) {
                    $this->logPricingChange(
                        $currentPricing['service_id'], 
                        $pricingId, 
                        'updated', 
                        $currentPricing['price_amount'], 
                        $data['price_amount']
                    );
                }
                
                return ['success' => true, 'message' => 'Pricing updated successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to update pricing'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Delete service pricing
     */
    public function deleteServicePricing($pricingId) {
        if (!$this->hasPermission('manage_pricing')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Get pricing info before deletion
            $stmt = $this->db->prepare("SELECT * FROM service_pricing WHERE id = ?");
            $stmt->execute([$pricingId]);
            $pricing = $stmt->fetch();
            
            if (!$pricing) {
                return ['success' => false, 'message' => 'Pricing not found'];
            }
            
            // Soft delete by setting is_active to false
            $stmt = $this->db->prepare("UPDATE service_pricing SET is_active = 0, updated_by = ? WHERE id = ?");
            $result = $stmt->execute([$this->currentUser['id'], $pricingId]);
            
            if ($result) {
                // Log deletion
                $this->logPricingChange($pricing['service_id'], $pricingId, 'deleted', $pricing['price_amount'], 0);
                
                return ['success' => true, 'message' => 'Pricing deleted successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to delete pricing'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get pricing rules
     */
    public function getPricingRules($includeInactive = false) {
        if (!$this->hasPermission('view_pricing')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $activeCondition = $includeInactive ? '' : 'AND is_active = 1';
            
            $stmt = $this->db->prepare("
                SELECT pr.*, u.full_name as created_by_name
                FROM pricing_rules pr
                LEFT JOIN users u ON pr.created_by = u.id
                WHERE 1=1 $activeCondition
                ORDER BY pr.priority DESC, pr.created_at DESC
            ");
            $stmt->execute();
            $rules = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $rules];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Create pricing rule
     */
    public function createPricingRule($data) {
        if (!$this->hasPermission('manage_rules')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Validate required fields
            $required = ['rule_name', 'rule_type', 'conditions', 'actions'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            $stmt = $this->db->prepare("
                INSERT INTO pricing_rules 
                (rule_name, rule_description, rule_type, conditions, actions,
                 applicable_services, applicable_customers, applicable_locations,
                 start_date, end_date, is_active, priority, usage_limit,
                 customer_usage_limit, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $result = $stmt->execute([
                $data['rule_name'],
                $data['rule_description'] ?? '',
                $data['rule_type'],
                json_encode($data['conditions']),
                json_encode($data['actions']),
                json_encode($data['applicable_services'] ?? []),
                json_encode($data['applicable_customers'] ?? []),
                json_encode($data['applicable_locations'] ?? []),
                $data['start_date'] ?? null,
                $data['end_date'] ?? null,
                $data['is_active'] ?? true,
                $data['priority'] ?? 0,
                $data['usage_limit'] ?? 0,
                $data['customer_usage_limit'] ?? 0,
                $this->currentUser['id']
            ]);
            
            if ($result) {
                $ruleId = $this->db->lastInsertId();
                return [
                    'success' => true, 
                    'message' => 'Pricing rule created successfully',
                    'rule_id' => $ruleId
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to create pricing rule'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get pricing history
     */
    public function getPricingHistory($serviceId = null, $limit = 50) {
        if (!$this->hasPermission('view_analytics')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $serviceCondition = $serviceId ? 'AND ph.service_id = ?' : '';
            $params = $serviceId ? [$serviceId] : [];
            
            $stmt = $this->db->prepare("
                SELECT 
                    ph.*,
                    s.service_name_ar,
                    s.service_name_en,
                    u.full_name as changed_by_name,
                    approver.full_name as approved_by_name
                FROM pricing_history ph
                JOIN services s ON ph.service_id = s.id
                LEFT JOIN users u ON ph.changed_by = u.id
                LEFT JOIN users approver ON ph.approved_by = approver.id
                WHERE 1=1 $serviceCondition
                ORDER BY ph.change_date DESC
                LIMIT ?
            ");
            
            $params[] = $limit;
            $stmt->execute($params);
            $history = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $history];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get pricing analytics
     */
    public function getPricingAnalytics($period = 'monthly', $limit = 12) {
        if (!$this->hasPermission('view_analytics')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $dateCondition = '';
            switch ($period) {
                case 'daily':
                    $dateCondition = "DATE(pa.date) >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)";
                    $dateFormat = '%Y-%m-%d';
                    break;
                case 'weekly':
                    $dateCondition = "pa.date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 WEEK)";
                    $dateFormat = '%Y-%u';
                    break;
                case 'monthly':
                    $dateCondition = "pa.date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH)";
                    $dateFormat = '%Y-%m';
                    break;
                case 'yearly':
                    $dateCondition = "pa.date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR)";
                    $dateFormat = '%Y';
                    break;
                default:
                    $dateCondition = "pa.date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH)";
                    $dateFormat = '%Y-%m';
            }
            
            $stmt = $this->db->prepare("
                SELECT 
                    DATE_FORMAT(pa.date, ?) as period,
                    COUNT(*) as total_services,
                    SUM(pa.times_used) as total_usage,
                    SUM(pa.total_revenue) as total_revenue,
                    AVG(pa.total_revenue) as avg_revenue_per_service,
                    SUM(pa.new_customers) as new_customers,
                    AVG(pa.customer_satisfaction_score) as avg_satisfaction,
                    AVG(pa.price_advantage) as avg_price_advantage
                FROM pricing_analytics pa
                WHERE $dateCondition
                GROUP BY DATE_FORMAT(pa.date, ?)
                ORDER BY period DESC
                LIMIT ?
            ");
            
            $stmt->execute([$dateFormat, $dateFormat, $limit]);
            $analytics = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $analytics];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Calculate price for service with rules
     */
    public function calculatePrice($serviceId, $vehicleType = 'all', $customerType = 'individual', $quantity = 1) {
        try {
            // Get base price
            $stmt = $this->db->prepare("
                SELECT price_amount 
                FROM service_pricing 
                WHERE service_id = ? 
                AND pricing_type = 'base_price'
                AND is_active = 1
                AND (valid_until IS NULL OR valid_until >= CURRENT_DATE)
                ORDER BY valid_from DESC
                LIMIT 1
            ");
            $stmt->execute([$serviceId]);
            $basePrice = $stmt->fetch();
            
            if (!$basePrice) {
                return ['success' => false, 'message' => 'No pricing found for service'];
            }
            
            $price = $basePrice['price_amount'];
            
            // Check vehicle type pricing
            if ($vehicleType !== 'all') {
                $stmt = $this->db->prepare("
                    SELECT price_amount 
                    FROM service_pricing 
                    WHERE service_id = ? 
                    AND pricing_type = 'vehicle_type'
                    AND vehicle_type = ?
                    AND is_active = 1
                    AND (valid_until IS NULL OR valid_until >= CURRENT_DATE)
                    LIMIT 1
                ");
                $stmt->execute([$serviceId, $vehicleType]);
                $vehiclePrice = $stmt->fetch();
                
                if ($vehiclePrice) {
                    $price = $vehiclePrice['price_amount'];
                }
            }
            
            // Apply pricing rules (simplified)
            $discount = $this->applyPricingRules($serviceId, $price, $customerType, $quantity);
            $finalPrice = $price - $discount;
            
            return [
                'success' => true,
                'data' => [
                    'base_price' => $price,
                    'discount_amount' => $discount,
                    'final_price' => $finalPrice,
                    'applied_rules' => []
                ]
            ];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Apply pricing rules (simplified implementation)
     */
    private function applyPricingRules($serviceId, $price, $customerType, $quantity) {
        $totalDiscount = 0;
        
        try {
            $stmt = $this->db->prepare("
                SELECT conditions, actions 
                FROM pricing_rules 
                WHERE is_active = 1
                AND (start_date IS NULL OR start_date <= CURRENT_DATE)
                AND (end_date IS NULL OR end_date >= CURRENT_DATE)
                AND (JSON_CONTAINS(applicable_services, ?) OR JSON_CONTAINS(applicable_services, 'null'))
                ORDER BY priority DESC
            ");
            $stmt->execute([json_encode($serviceId)]);
            $rules = $stmt->fetchAll();
            
            foreach ($rules as $rule) {
                $conditions = json_decode($rule['conditions'], true);
                $actions = json_decode($rule['actions'], true);
                
                // Check if conditions match (simplified)
                if ($this->evaluateConditions($conditions, $customerType, $quantity)) {
                    if ($actions['discount_type'] === 'percentage') {
                        $totalDiscount += ($price * $actions['discount_value']) / 100;
                    } elseif ($actions['discount_type'] === 'fixed') {
                        $totalDiscount += $actions['discount_value'];
                    }
                }
            }
            
        } catch (Exception $e) {
            error_log("Error applying pricing rules: " . $e->getMessage());
        }
        
        return min($totalDiscount, $price * 0.8); // Max 80% discount
    }
    
    /**
     * Evaluate rule conditions (simplified)
     */
    private function evaluateConditions($conditions, $customerType, $quantity) {
        if (isset($conditions['customer_type']) && $conditions['customer_type'] !== $customerType) {
            return false;
        }
        
        if (isset($conditions['min_quantity']) && $quantity < $conditions['min_quantity']) {
            return false;
        }
        
        return true;
    }
    
    /**
     * Log pricing changes
     */
    private function logPricingChange($serviceId, $pricingId, $changeType, $oldPrice, $newPrice) {
        try {
            $priceChange = $newPrice - $oldPrice;
            $priceChangePercent = $oldPrice > 0 ? ($priceChange / $oldPrice) * 100 : 0;
            
            $stmt = $this->db->prepare("
                INSERT INTO pricing_history 
                (service_id, pricing_id, change_type, old_price, new_price, 
                 price_change_amount, price_change_percentage, change_reason, changed_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $serviceId,
                $pricingId,
                $changeType,
                $oldPrice,
                $newPrice,
                $priceChange,
                $priceChangePercent,
                'Price changed by admin',
                $this->currentUser['id']
            ]);
            
        } catch (Exception $e) {
            error_log("Error logging pricing change: " . $e->getMessage());
        }
    }
}

// API Endpoint Handler
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$pricingSystem = new PricingSystem();
$endpoint = $_GET['endpoint'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($endpoint) {
        case 'services':
            if ($method === 'GET') {
                $includeInactive = $_GET['include_inactive'] === 'true';
                echo json_encode($pricingSystem->getServices($includeInactive));
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($pricingSystem->createService($data));
            }
            break;
            
        case 'service-pricing':
            if ($method === 'GET') {
                $serviceId = $_GET['service_id'];
                echo json_encode($pricingSystem->getServicePricing($serviceId));
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($pricingSystem->createServicePricing($data['service_id'], $data));
            } elseif ($method === 'PUT') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($pricingSystem->updateServicePricing($data['pricing_id'], $data));
            } elseif ($method === 'DELETE') {
                $pricingId = $_GET['pricing_id'];
                echo json_encode($pricingSystem->deleteServicePricing($pricingId));
            }
            break;
            
        case 'pricing-rules':
            if ($method === 'GET') {
                $includeInactive = $_GET['include_inactive'] === 'true';
                echo json_encode($pricingSystem->getPricingRules($includeInactive));
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($pricingSystem->createPricingRule($data));
            }
            break;
            
        case 'pricing-history':
            if ($method === 'GET') {
                $serviceId = $_GET['service_id'] ?? null;
                $limit = $_GET['limit'] ?? 50;
                echo json_encode($pricingSystem->getPricingHistory($serviceId, $limit));
            }
            break;
            
        case 'pricing-analytics':
            if ($method === 'GET') {
                $period = $_GET['period'] ?? 'monthly';
                $limit = $_GET['limit'] ?? 12;
                echo json_encode($pricingSystem->getPricingAnalytics($period, $limit));
            }
            break;
            
        case 'calculate-price':
            if ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($pricingSystem->calculatePrice(
                    $data['service_id'],
                    $data['vehicle_type'] ?? 'all',
                    $data['customer_type'] ?? 'individual',
                    $data['quantity'] ?? 1
                ));
            }
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}
?>
