<?php
/**
 * Client Contact Model
 *
 * @package Freelance_Studio
 */

class FS_Client_Contact {

    /**
     * Create a new contact
     *
     * @param array $data Contact data
     * @return int|false Insert ID or false on failure
     */
    public static function create($data) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_client_contacts';
        
        // If this is marked as primary, unset other primary contacts for this client
        if (!empty($data['is_primary'])) {
            self::unset_primary($data['client_id']);
        }
        
        $result = $wpdb->insert(
            $table,
            array(
                'client_id' => intval($data['client_id']),
                'name' => sanitize_text_field($data['name']),
                'email' => isset($data['email']) ? sanitize_email($data['email']) : '',
                'phone' => isset($data['phone']) ? sanitize_text_field($data['phone']) : '',
                'role' => isset($data['role']) ? sanitize_text_field($data['role']) : '',
                'is_primary' => isset($data['is_primary']) ? intval($data['is_primary']) : 0,
                'is_billing_contact' => isset($data['is_billing_contact']) ? intval($data['is_billing_contact']) : 0,
                'is_project_contact' => isset($data['is_project_contact']) ? intval($data['is_project_contact']) : 0,
                'notes' => isset($data['notes']) ? sanitize_textarea_field($data['notes']) : '',
            ),
            array('%d', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%s')
        );
        
        return $result ? $wpdb->insert_id : false;
    }

    /**
     * Get all contacts for a client
     *
     * @param int $client_id Client ID
     * @return array
     */
    public static function get_by_client($client_id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_client_contacts';
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$table} WHERE client_id = %d ORDER BY is_primary DESC, name ASC",
            $client_id
        ));
    }

    /**
     * Get a single contact
     *
     * @param int $id Contact ID
     * @return object|null
     */
    public static function get($id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_client_contacts';
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE id = %d",
            $id
        ));
    }

    /**
     * Get primary contact for a client
     *
     * @param int $client_id Client ID
     * @return object|null
     */
    public static function get_primary($client_id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_client_contacts';
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE client_id = %d AND is_primary = 1",
            $client_id
        ));
    }

    /**
     * Get billing contact for a client
     *
     * @param int $client_id Client ID
     * @return object|null
     */
    public static function get_billing_contact($client_id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_client_contacts';
        
        // Try to get billing contact first, fall back to primary
        $contact = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE client_id = %d AND is_billing_contact = 1",
            $client_id
        ));
        
        if (!$contact) {
            $contact = self::get_primary($client_id);
        }
        
        return $contact;
    }

    /**
     * Update a contact
     *
     * @param int   $id   Contact ID
     * @param array $data Contact data
     * @return int|false
     */
    public static function update($id, $data) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_client_contacts';
        
        // Get the contact to find the client_id
        $contact = self::get($id);
        if (!$contact) {
            return false;
        }
        
        // If this is marked as primary, unset other primary contacts
        if (!empty($data['is_primary'])) {
            self::unset_primary($contact->client_id, $id);
        }
        
        return $wpdb->update(
            $table,
            array(
                'name' => sanitize_text_field($data['name']),
                'email' => isset($data['email']) ? sanitize_email($data['email']) : '',
                'phone' => isset($data['phone']) ? sanitize_text_field($data['phone']) : '',
                'role' => isset($data['role']) ? sanitize_text_field($data['role']) : '',
                'is_primary' => isset($data['is_primary']) ? intval($data['is_primary']) : 0,
                'is_billing_contact' => isset($data['is_billing_contact']) ? intval($data['is_billing_contact']) : 0,
                'is_project_contact' => isset($data['is_project_contact']) ? intval($data['is_project_contact']) : 0,
                'notes' => isset($data['notes']) ? sanitize_textarea_field($data['notes']) : '',
            ),
            array('id' => $id),
            array('%s', '%s', '%s', '%s', '%d', '%d', '%d', '%s'),
            array('%d')
        );
    }

    /**
     * Delete a contact
     *
     * @param int $id Contact ID
     * @return int|false
     */
    public static function delete($id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_client_contacts';
        
        return $wpdb->delete($table, array('id' => $id), array('%d'));
    }

    /**
     * Unset primary flag for all contacts of a client
     *
     * @param int $client_id Client ID
     * @param int $except_id Optional contact ID to exclude
     */
    private static function unset_primary($client_id, $except_id = null) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_client_contacts';
        
        $sql = $wpdb->prepare(
            "UPDATE {$table} SET is_primary = 0 WHERE client_id = %d",
            $client_id
        );
        
        if ($except_id) {
            $sql .= $wpdb->prepare(" AND id != %d", $except_id);
        }
        
        $wpdb->query($sql); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared
    }

    /**
     * Count contacts for a client
     *
     * @param int $client_id Client ID
     * @return int
     */
    public static function count_by_client($client_id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_client_contacts';
        
        return (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE client_id = %d",
            $client_id
        ));
    }
}
