/**
 * DescomplicarÂ® Crescimento Digital
 * https://descomplicar.pt
 */

<?php

defined('BASEPATH') or exit('No direct script access allowed');

/**
 * General Synchronization Service
 * 
 * Coordinates synchronization between Perfex CRM and Moloni
 * Provides high-level sync orchestration and management
 * 
 * @package    DeskMoloni
 * @subpackage Libraries
 * @version    3.0.0
 * @author     Descomplicar®
 */
class SyncService
{
    private $CI;
    private $client_sync_service;
    private $invoice_sync_service;
    private $sync_log_model;
    private $sync_queue_model;
    
    public function __construct()
    {
        $this->CI = &get_instance();
        
        // Load required services and models
        $this->CI->load->library('desk_moloni/client_sync_service');
        $this->CI->load->library('desk_moloni/invoice_sync_service');
        $this->CI->load->model('desk_moloni/desk_moloni_sync_log_model', 'sync_log_model');
        $this->CI->load->model('desk_moloni/desk_moloni_sync_queue_model', 'sync_queue_model');
        
        $this->client_sync_service = $this->CI->client_sync_service;
        $this->invoice_sync_service = $this->CI->invoice_sync_service;
        $this->sync_log_model = $this->CI->sync_log_model;
        $this->sync_queue_model = $this->CI->sync_queue_model;
    }
    
    /**
     * Perform full synchronization
     */
    public function full_sync($options = [])
    {
        $start_time = microtime(true);
        
        try {
            $results = [
                'clients' => $this->client_sync_service->sync_bidirectional('bidirectional', $options),
                'invoices' => $this->invoice_sync_service->sync_bidirectional('bidirectional', $options)
            ];
            
            $execution_time = microtime(true) - $start_time;
            
            // Log sync completion
            $this->sync_log_model->log_event([
                'event_type' => 'full_sync_completed',
                'entity_type' => 'system',
                'entity_id' => null,
                'message' => 'Full synchronization completed',
                'log_level' => 'info',
                'execution_time' => $execution_time,
                'sync_data' => json_encode($results)
            ]);
            
            return [
                'success' => true,
                'results' => $results,
                'execution_time' => $execution_time,
                'timestamp' => date('Y-m-d H:i:s')
            ];
            
        } catch (Exception $e) {
            $execution_time = microtime(true) - $start_time;
            
            $this->sync_log_model->log_event([
                'event_type' => 'full_sync_error',
                'entity_type' => 'system',
                'entity_id' => null,
                'message' => 'Full sync failed: ' . $e->getMessage(),
                'log_level' => 'error',
                'execution_time' => $execution_time
            ]);
            
            return [
                'success' => false,
                'error' => $e->getMessage(),
                'execution_time' => $execution_time,
                'timestamp' => date('Y-m-d H:i:s')
            ];
        }
    }
    
    /**
     * Get sync status overview
     */
    public function get_sync_status()
    {
        return [
            'clients' => $this->client_sync_service->get_sync_statistics(),
            'invoices' => $this->invoice_sync_service->get_sync_statistics(),
            'queue' => $this->sync_queue_model->get_queue_statistics(),
            'last_sync' => $this->get_last_sync_info()
        ];
    }
    
    /**
     * Get last sync information
     */
    private function get_last_sync_info()
    {
        // Get most recent sync log entry
        $this->CI->db->select('*');
        $this->CI->db->from('tbldeskmoloni_sync_log');
        $this->CI->db->where('event_type', 'full_sync_completed');
        $this->CI->db->order_by('created_at', 'DESC');
        $this->CI->db->limit(1);
        
        $query = $this->CI->db->get();
        
        if ($query->num_rows() > 0) {
            return $query->row_array();
        }
        
        return null;
    }
}