<?php
/**
 * Service Synchronization Controller
 * Syncs services from MrGoViral with 80% markup pricing
 */

namespace App\Controller;

use App\Classes\Api\MrGoViralAPI;

class SyncController {
    protected $db;
    protected $api;
    
    const PROFIT_MARKUP = 0.80;
    
    public function __construct($db) {
        $this->db = $db;
        $this->api = new MrGoViralAPI();
    }
    
    /**
     * Sync services from MrGoViral
     */
    public function syncServices() {
        try {
            $this->db->beginTransaction();
            
            // Log sync start
            $logStmt = $this->db->prepare('
                INSERT INTO service_sync_logs (sync_start, status)
                VALUES (NOW(), "in_progress")
            ');
            $logStmt->execute();
            $syncLogId = $this->db->lastInsertId();
            
            // Fetch services from MrGoViral
            $servicesData = $this->api->getServices();
            
            if (!MrGoViralAPI::isSuccess($servicesData)) {
                throw new \Exception('Failed to fetch services: ' . MrGoViralAPI::getError($servicesData));
            }
            
            $servicesList = $servicesData['services'] ?? [];
            $added = 0;
            $updated = 0;
            $removed = 0;
            
            // Process each service
            foreach ($servicesList as $apiService) {
                $serviceId = $apiService['service'] ?? $apiService['id'];
                $basePrice = $apiService['rate'] ?? $apiService['price'] ?? 0;
                
                // Check if service already exists
                $existStmt = $this->db->prepare('SELECT id FROM services WHERE service_id = ?');
                $existStmt->execute([$serviceId]);
                $existingService = $existStmt->fetch(\PDO::FETCH_ASSOC);
                
                if ($existingService) {
                    // Update existing service
                    $updateStmt = $this->db->prepare('
                        UPDATE services
                        SET name = ?, description = ?, base_price = ?, 
                            min_quantity = ?, max_quantity = ?, is_refillable = ?,
                            last_synced = NOW()
                        WHERE service_id = ?
                    ');
                    
                    $updateStmt->execute([
                        $apiService['name'] ?? '',
                        $apiService['description'] ?? '',
                        $basePrice,
                        $apiService['min'] ?? 1,
                        $apiService['max'] ?? 10000,
                        isset($apiService['refill']) && $apiService['refill'] == 1 ? 1 : 0,
                        $serviceId
                    ]);
                    
                    $updated++;
                } else {
                    // Insert new service
                    $insertStmt = $this->db->prepare('
                        INSERT INTO services 
                        (service_id, name, description, category, base_price, currency, 
                         min_quantity, max_quantity, is_refillable, status, provider, last_synced)
                        VALUES (?, ?, ?, ?, ?, "UGX", ?, ?, ?, "active", "mrgoviral", NOW())
                    ');
                    
                    $insertStmt->execute([
                        $serviceId,
                        $apiService['name'] ?? '',
                        $apiService['description'] ?? '',
                        $apiService['category'] ?? 'General',
                        $basePrice,
                        $apiService['min'] ?? 1,
                        $apiService['max'] ?? 10000,
                        isset($apiService['refill']) && $apiService['refill'] == 1 ? 1 : 0
                    ]);
                    
                    $added++;
                }
            }
            
            // Mark old services as inactive (if not synced recently)
            $deactivateStmt = $this->db->prepare('
                UPDATE services
                SET status = "inactive"
                WHERE last_synced IS NULL OR last_synced < DATE_SUB(NOW(), INTERVAL 7 DAY)
            ');
            $deactivateStmt->execute();
            $removed = $this->db->query('SELECT ROW_COUNT()')->fetch(\PDO::FETCH_ASSOC)['ROW_COUNT()'] ?? 0;
            
            // Update sync log
            $updateLogStmt = $this->db->prepare('
                UPDATE service_sync_logs
                SET sync_end = NOW(), services_added = ?, services_updated = ?, 
                    services_removed = ?, status = "completed"
                WHERE id = ?
            ');
            $updateLogStmt->execute([$added, $updated, $removed, $syncLogId]);
            
            $this->db->commit();
            
            // Notify admin via Telegram
            $this->notifyAdminSync($added, $updated, $removed);
            
            return [
                'success' => true,
                'message' => 'Services synced successfully',
                'added' => $added,
                'updated' => $updated,
                'removed' => $removed,
                'total' => count($servicesList)
            ];
            
        } catch (\Exception $e) {
            $this->db->rollBack();
            error_log('Service Sync Error: ' . $e->getMessage());
            
            // Update sync log with error
            try {
                $errorStmt = $this->db->prepare('
                    UPDATE service_sync_logs
                    SET sync_end = NOW(), status = "failed", error_message = ?
                    WHERE id = ?
                ');
                $errorStmt->execute([$e->getMessage(), $syncLogId ?? 0]);
            } catch (\Exception $logError) {
                error_log('Failed to log sync error: ' . $logError->getMessage());
            }
            
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Get sync status/logs
     */
    public function getSyncLogs($limit = 50) {
        try {
            $stmt = $this->db->prepare('
                SELECT * FROM service_sync_logs
                ORDER BY created_at DESC
                LIMIT ?
            ');
            $stmt->execute([$limit]);
            $logs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            
            return ['success' => true, 'logs' => $logs];
            
        } catch (\Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Get service statistics
     */
    public function getServiceStats() {
        try {
            $stats = [];
            
            // Total active services
            $stmt = $this->db->query('SELECT COUNT(*) as count FROM services WHERE status = "active"');
            $stats['active_services'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'];
            
            // Total inactive services
            $stmt = $this->db->query('SELECT COUNT(*) as count FROM services WHERE status = "inactive"');
            $stats['inactive_services'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'];
            
            // Services by category
            $stmt = $this->db->query('SELECT category, COUNT(*) as count FROM services WHERE status = "active" GROUP BY category');
            $stats['by_category'] = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            
            // Last sync time
            $stmt = $this->db->query('SELECT MAX(sync_end) as last_sync FROM service_sync_logs WHERE status = "completed"');
            $stats['last_sync'] = $stmt->fetch(\PDO::FETCH_ASSOC)['last_sync'];
            
            return ['success' => true, 'stats' => $stats];
            
        } catch (\Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Notify admin of sync via Telegram
     */
    private function notifyAdminSync($added, $updated, $removed) {
        try {
            $message = "✅ Service Sync Complete\n";
            $message .= "✨ Added: $added\n";
            $message .= "🔄 Updated: $updated\n";
            $message .= "🗑️ Removed: $removed\n";
            $message .= "Time: " . date('Y-m-d H:i:s');
            
            // Will be implemented with Telegram bot
            error_log("Sync Notification: $message");
        } catch (\Exception $e) {
            error_log('Admin Sync Notification Error: ' . $e->getMessage());
        }
    }
}
?>
