<?php
/**
 * Contact Card Widget for BoostBot
 *
 * A creatable widget that displays contact information from assigned contact lists.
 * The contact data is resolved from the widget's configured contact_list_ids.
 *
 * @package BoostBot
 * @since 1.0.0
 * @updated 1.7.0 - Made creatable as a standalone widget with contact list selection
 */

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

/**
 * Class BoostBot_Contact_Card_Widget
 */
class BoostBot_Contact_Card_Widget extends BoostBot_Widget_Base {

    /**
     * Widget ID.
     *
     * @var string
     */
    protected $id = 'contact_card';

    /**
     * Available in free version.
     *
     * @var bool
     */
    protected $is_free = true;

    public function get_name(): string {
        return __( 'כרטיס איש קשר', 'boostbot' );
    }

    public function get_description(): string {
        return __( 'מציג פרטי איש קשר בכרטיס מעוצב', 'boostbot' );
    }

    public function get_icon(): string {
        return 'user';
    }

    /**
     * Widget configuration schema.
     *
     * @return array
     */
    public function get_schema(): array {
        return array(
            'name'        => $this->get_name(),
            'description' => $this->get_description(),
            
            'settings' => array(
                // Which contact lists to pull contacts from
                // All contacts from these lists are sent to Gemini, which picks the best one
                // based on conversation context and role (תפקיד)
                'contact_list_ids' => array(),
                
                // Show call/message action buttons
                // Call button uses phone, Message button uses whatsapp
                'show_call_button'    => true,
                'show_message_button' => true,
            ),
            
            // Frontend rendering schema
            'contact' => array(
                'name'     => '',
                'title'    => '',
                'phone'    => '',
                'email'    => '',
                'location' => '',
                'whatsapp' => '',
                'avatar'   => '',
            ),
            'is_rtl' => true,
        );
    }

    /**
     * Get contacts based on widget settings.
     *
     * @param array $settings Widget settings.
     * @return array Array of contacts.
     */
    public function get_contacts( array $settings = array() ): array {
        $contact_list_ids = $settings['contact_list_ids'] ?? array();
        
        if ( empty( $contact_list_ids ) ) {
            return array();
        }
        
        // Get contacts from the selected lists
        $contacts = array();
        $contact_model = new BoostBot_Contact_Model();
        
        foreach ( $contact_list_ids as $list_id ) {
            $list_contacts = $contact_model->get_by_list( (int) $list_id );
            if ( ! empty( $list_contacts ) ) {
                $contacts = array_merge( $contacts, $list_contacts );
            }
        }
        
        // Remove duplicates by contact ID
        $unique_contacts = array();
        $seen_ids        = array();
        foreach ( $contacts as $contact ) {
            if ( ! in_array( $contact->id, $seen_ids, true ) ) {
                $unique_contacts[] = $contact;
                $seen_ids[]        = $contact->id;
            }
        }
        
        return $unique_contacts;
    }

    /**
     * Get all contacts from the configured contact lists.
     * Gemini will decide which contact to display based on context and role.
     *
     * @param array $settings Widget settings.
     * @return array All contacts from the configured lists.
     */
    public function get_display_contacts( array $settings = array() ): array {
        return $this->get_contacts( $settings );
    }

    /**
     * Format contact for frontend.
     *
     * Contact list columns: שם (name), תפקיד (title), טלפון (phone), מייל (email), וואטסאפ (whatsapp)
     *
     * @param object $contact Contact object from database.
     * @return array Formatted contact.
     */
    public function format_contact( $contact ): array {
        $formatted = array(
            'id'   => $contact->id ?? 0,
            // Name is ALWAYS included — the frontend requires it for identification
            // and the ContactCard component won't render without it.
            'name' => $contact->name ?? '',
        );
        
        $formatted['title']    = $contact->title ?? '';
        $formatted['phone']    = $contact->phone ?? '';
        $formatted['email']    = $contact->email ?? '';
        $formatted['whatsapp'] = $contact->whatsapp ?? '';
        
        // Structured meeting availability for AI/context consumers.
        $formatted['meeting_availability'] = $contact->meeting_availability ?? null;
        
        return $formatted;
    }

    /**
     * Get widget configuration for chat.
     *
     * @param int $widget_id Widget ID.
     * @return array Widget config for frontend.
     */
    public function get_chat_config( int $widget_id ): array {
        $widget_model = new BoostBot_Widget_Model();
        $widget       = $widget_model->get_with_fields( $widget_id );
        
        if ( ! $widget ) {
            return array();
        }
        
        $config   = is_array( $widget->config ) ? $widget->config : array();
        $settings = $config['settings'] ?? $config;
        
        $contacts    = $this->get_display_contacts( $settings );
        if ( empty( $contacts ) ) {
            return array();
        }
        
        // For single contact display
        if ( count( $contacts ) === 1 ) {
            return array(
                'contact'             => $this->format_contact( $contacts[0] ),
                'show_call_button'    => $settings['show_call_button'] ?? true,
                'show_message_button' => $settings['show_message_button'] ?? true,
                'is_rtl'              => true,
            );
        }
        
        // For multiple contacts
        return array(
            'contacts'            => array_map(
                function( $c ) {
                    return $this->format_contact( $c );
                },
                $contacts
            ),
            'show_call_button'    => $settings['show_call_button'] ?? true,
            'show_message_button' => $settings['show_message_button'] ?? true,
            'is_rtl'              => true,
        );
    }

    /**
     * Validate widget settings.
     *
     * @param array $data Widget data.
     * @return array Validation result.
     */
    public function validate( array $data ): array {
        $errors = array();
        
        // Validate contact_list_ids if provided
        if ( isset( $data['contact_list_ids'] ) ) {
            if ( ! is_array( $data['contact_list_ids'] ) ) {
                $errors['contact_list_ids'] = __( 'רשימות אנשי קשר חייבות להיות מערך', 'boostbot' );
            }
        }
        
        // Validate display_mode
        if ( isset( $data['display_mode'] ) ) {
            $valid_modes = array( 'first', 'random', 'all' );
            if ( ! in_array( $data['display_mode'], $valid_modes, true ) ) {
                $errors['display_mode'] = __( 'אופן תצוגה לא תקין', 'boostbot' );
            }
        }
        
        return array(
            'valid'  => empty( $errors ),
            'errors' => $errors,
        );
    }

    /**
     * Process widget action (display only, no submission).
     *
     * @param array $data    Action data.
     * @param array $context Context.
     * @return array Result.
     */
    public function process( array $data, array $context = array() ): array {
        return array(
            'ok' => true,
        );
    }
}

