<?php
/**
 * Meeting Type Model
 *
 * @package Freelance_Studio
 */

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

class FS_Meeting_Type {

    /**
     * Get table name
     */
    private static function get_table_name() {
        global $wpdb;
        return $wpdb->prefix . 'fs_meeting_types';
    }

    /**
     * Get a single meeting type by ID
     */
    public static function get($id) {
        global $wpdb;
        $table = self::get_table_name();
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table WHERE id = %d",
            $id
        ));
    }

    /**
     * Get meeting type by slug
     */
    public static function get_by_slug($slug) {
        global $wpdb;
        $table = self::get_table_name();
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table WHERE slug = %s",
            $slug
        ));
    }

    /**
     * Get all meeting types
     */
    public static function get_all($active_only = false, $public_only = false) {
        global $wpdb;
        $table = self::get_table_name();
        
        $where = array('1=1');
        
        if ($active_only) {
            $where[] = 'is_active = 1';
        }
        
        if ($public_only) {
            $where[] = 'is_public = 1';
        }
        
        $where_sql = implode(' AND ', $where);
        
        return $wpdb->get_results(
            "SELECT * FROM $table WHERE $where_sql ORDER BY sort_order ASC, name ASC"
        );
    }

    /**
     * Get active public meeting types (for booking page)
     */
    public static function get_bookable() {
        return self::get_all(true, true);
    }

    /**
     * Create a new meeting type
     */
    public static function create($data) {
        global $wpdb;
        $table = self::get_table_name();
        
        // Generate slug if not provided
        if (empty($data['slug'])) {
            $data['slug'] = self::generate_slug($data['name']);
        }
        
        $defaults = array(
            'duration' => 30,
            'color' => '#4173B0',
            'location_type' => 'video',
            'buffer_before' => 0,
            'buffer_after' => 0,
            'min_notice_hours' => 24,
            'max_days_advance' => 60,
            'is_active' => 1,
            'is_public' => 1,
            'sort_order' => 0,
        );
        
        $data = wp_parse_args($data, $defaults);
        
        $wpdb->insert($table, $data);
        
        return $wpdb->insert_id;
    }

    /**
     * Update a meeting type
     */
    public static function update($id, $data) {
        global $wpdb;
        $table = self::get_table_name();
        
        // Regenerate slug if name changed and slug not explicitly set
        if (isset($data['name']) && !isset($data['slug'])) {
            $existing = self::get($id);
            if ($existing && self::slugify($existing->name) !== self::slugify($data['name'])) {
                $data['slug'] = self::generate_slug($data['name'], $id);
            }
        }
        
        return $wpdb->update($table, $data, array('id' => $id));
    }

    /**
     * Delete a meeting type
     */
    public static function delete($id) {
        global $wpdb;
        $table = self::get_table_name();
        
        return $wpdb->delete($table, array('id' => $id));
    }

    /**
     * Generate a unique slug
     */
    private static function generate_slug($name, $exclude_id = null) {
        global $wpdb;
        $table = self::get_table_name();
        
        $base_slug = self::slugify($name);
        $slug = $base_slug;
        $counter = 1;
        
        while (true) {
            $query = "SELECT id FROM $table WHERE slug = %s";
            $params = array($slug);
            
            if ($exclude_id) {
                $query .= " AND id != %d";
                $params[] = $exclude_id;
            }
            
            $existing = $wpdb->get_var($wpdb->prepare($query, $params)); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared
            
            if (!$existing) {
                break;
            }
            
            $slug = $base_slug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }

    /**
     * Convert string to slug
     */
    private static function slugify($text) {
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9]+/', '-', $text);
        $text = trim($text, '-');
        return $text;
    }

    /**
     * Get duration display string
     */
    public static function get_duration_display($minutes) {
        if ($minutes < 60) {
            return $minutes . ' min';
        }
        
        $hours = floor($minutes / 60);
        $mins = $minutes % 60;
        
        if ($mins === 0) {
            return $hours . ' hour' . ($hours > 1 ? 's' : '');
        }
        
        return $hours . 'h ' . $mins . 'm';
    }

    /**
     * Get location type display string
     */
    public static function get_location_display($type, $details = '') {
        $types = array(
            'video' => __('Video Call', 'freelance-studio'),
            'phone' => __('Phone Call', 'freelance-studio'),
            'in_person' => __('In Person', 'freelance-studio'),
            'custom' => $details ?: __('TBD', 'freelance-studio'),
        );
        
        return isset($types[$type]) ? $types[$type] : $type;
    }
}
