<?php
/**
 * CLAWS Zapier Integration Class
 * Handles webhook triggers for Zapier automation
 */

if (!defined('ABSPATH')) {
    exit;
}

class CLAWS_Zapier {
    
    private static $instance = null;
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        // Hook into CLAWS events to trigger webhooks
        add_action('claws_intake_saved', array($this, 'trigger_intake_webhook'), 10, 2);
        add_action('claws_discharge_saved', array($this, 'trigger_discharge_webhook'), 10, 2);
        add_action('claws_colony_saved', array($this, 'trigger_colony_webhook'), 10, 2);
    }
    
    /**
     * Check if Zapier integration is enabled
     */
    private function is_enabled() {
        return get_option('claws_zapier_enabled', 0) == 1;
    }
    
    /**
     * Get the webhook URL
     */
    private function get_webhook_url() {
        return get_option('claws_zapier_webhook_url', '');
    }
    
    /**
     * Get enabled events
     */
    private function get_enabled_events() {
        return get_option('claws_zapier_events', array());
    }
    
    /**
     * Send webhook data to Zapier
     */
    private function send_webhook($event_type, $data) {
        if (!$this->is_enabled()) {
            return false;
        }
        
        $webhook_url = $this->get_webhook_url();
        if (empty($webhook_url)) {
            return false;
        }
        
        $enabled_events = $this->get_enabled_events();
        if (!in_array($event_type, $enabled_events)) {
            return false;
        }
        
        $payload = array(
            'event' => $event_type,
            'timestamp' => current_time('c'), // ISO 8601 format
            'site_url' => site_url(),
            'site_name' => get_bloginfo('name'),
            'data' => $data
        );
        
        // Send async webhook to avoid blocking the main request
        wp_remote_post($webhook_url, array(
            'method' => 'POST',
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
                'User-Agent' => 'CLAWS-Webhook/1.0 WordPress/' . get_bloginfo('version')
            ),
            'body' => wp_json_encode($payload),
            'blocking' => false // Non-blocking request
        ));
        
        // Log the webhook send (for debugging)
        error_log('CLAWS Zapier webhook sent: ' . $event_type . ' to ' . $webhook_url);
        
        return true;
    }
    
    /**
     * Trigger webhook for new intake
     */
    public function trigger_intake_webhook($intake_id, $intake_data) {
        $webhook_data = array(
            'intake_id' => $intake_id,
            'date' => $intake_data['intake_date'] ?? '',
            'cat' => array(
                'name' => $intake_data['cat_name'] ?? '',
                'age' => $intake_data['age'] ?? '',
                'gender' => $intake_data['gender'] ?? '',
                'coat' => $intake_data['coat'] ?? '',
                'color' => $intake_data['color'] ?? '',
                'type' => $intake_data['type'] ?? ''
            ),
            'contact' => array(
                'name' => $intake_data['contact_name'] ?? '',
                'address' => $intake_data['address'] ?? '',
                'phone' => $intake_data['phone'] ?? '',
                'email' => $intake_data['email'] ?? '',
                'anonymous' => $intake_data['anonymous'] ?? false,
                'dropoff' => $intake_data['dropoff'] ?? false,
                'phone_unknown' => $intake_data['phone_unknown'] ?? false,
                'email_unknown' => $intake_data['email_unknown'] ?? false
            ),
            'notes' => $intake_data['notes'] ?? '',
            'added_by' => array(
                'user_id' => get_current_user_id(),
                'username' => wp_get_current_user()->user_login ?? 'unknown'
            )
        );
        
        $this->send_webhook('intake', $webhook_data);
    }
    
    /**
     * Trigger webhook for discharge
     */
    public function trigger_discharge_webhook($discharge_id, $discharge_data) {
        $webhook_data = array(
            'discharge_id' => $discharge_id,
            'intake_id' => $discharge_data['intake_id'] ?? '',
            'date' => $discharge_data['discharge_date'] ?? '',
            'outcome' => $discharge_data['outcome'] ?? '',
            'location' => $discharge_data['location'] ?? '',
            'adopter' => array(
                'name' => $discharge_data['adopter_name'] ?? '',
                'email' => $discharge_data['adopter_email'] ?? '',
                'phone' => $discharge_data['adopter_phone'] ?? ''
            ),
            'notes' => $discharge_data['notes'] ?? '',
            'added_by' => array(
                'user_id' => get_current_user_id(),
                'username' => wp_get_current_user()->user_login ?? 'unknown'
            )
        );
        
        $this->send_webhook('discharge', $webhook_data);
    }
    
    /**
     * Trigger webhook for new colony
     */
    public function trigger_colony_webhook($colony_id, $colony_data) {
        $webhook_data = array(
            'colony_id' => $colony_id,
            'name' => $colony_data['name'] ?? '',
            'address' => array(
                'full' => $colony_data['address'] ?? '',
                'street' => $colony_data['street'] ?? '',
                'city' => $colony_data['city'] ?? '',
                'state' => $colony_data['state'] ?? '',
                'zip' => $colony_data['zip'] ?? ''
            ),
            'coordinates' => array(
                'latitude' => $colony_data['lat'] ?? '',
                'longitude' => $colony_data['lng'] ?? ''
            ),
            'population' => array(
                'babies' => $colony_data['babies'] ?? 0,
                'kittens' => $colony_data['kittens'] ?? 0,
                'adults' => $colony_data['adults'] ?? 0,
                'seniors' => $colony_data['seniors'] ?? 0,
                'total' => $colony_data['cats'] ?? 0
            ),
            'health_metrics' => array(
                'tipped_ears' => $colony_data['tippedEars'] ?? 0,
                'winter_shelters' => $colony_data['winterShelters'] ?? 0,
                'food_security' => $colony_data['foodSecurity'] ?? '',
                'water_security' => $colony_data['waterSecurity'] ?? '',
                'safe_location' => $colony_data['safeLocation'] ?? ''
            ),
            'caregivers' => $colony_data['caregivers'] ?? array(),
            'added_by' => array(
                'user_id' => get_current_user_id(),
                'username' => wp_get_current_user()->user_login ?? 'unknown'
            )
        );
        
        $this->send_webhook('colony', $webhook_data);
    }
    
    /**
     * Manual webhook test (called from admin)
     */
    public function send_test_webhook() {
        $test_data = array(
            'test_message' => 'This is a test webhook from CLAWS',
            'timestamp' => current_time('c'),
            'site_info' => array(
                'url' => site_url(),
                'name' => get_bloginfo('name'),
                'admin_email' => get_option('admin_email')
            )
        );
        
        return $this->send_webhook('test', $test_data);
    }
}