<?php
/**
 * Annual Tax Deduction Model
 * Handles yearly estimated deductions for tax calculations
 *
 * @package Freelance_Studio
 */

class FS_Annual_Deduction {
    
    /**
     * Get all annual deductions for a year
     *
     * @param int $year Year
     * @return array
     */
    public static function get_all($year = null) {
        global $wpdb;
        
        if (!$year) {
            $year = gmdate('Y');
        }
        
        $table = $wpdb->prefix . 'fs_annual_deductions';
        $user_id = get_current_user_id();
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$table} 
             WHERE user_id = %d AND year = %d 
             ORDER BY category ASC, name ASC",
            $user_id,
            $year
        ));
    }

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

    /**
     * Create a new annual deduction
     *
     * @param array $data Deduction data
     * @return int|false Insert ID or false on failure
     */
    public static function create($data) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_annual_deductions';
        $user_id = get_current_user_id();
        
        $result = $wpdb->insert(
            $table,
            array(
                'user_id' => $user_id,
                'year' => intval($data['year']),
                'name' => sanitize_text_field($data['name']),
                'category' => sanitize_text_field($data['category']),
                'annual_amount' => floatval($data['annual_amount']),
                'deduction_percentage' => isset($data['deduction_percentage']) ? floatval($data['deduction_percentage']) : 100,
                'notes' => isset($data['notes']) ? sanitize_textarea_field($data['notes']) : '',
                'is_active' => isset($data['is_active']) ? intval($data['is_active']) : 1,
            ),
            array('%d', '%d', '%s', '%s', '%f', '%f', '%s', '%d')
        );
        
        return $result ? $wpdb->insert_id : false;
    }

    /**
     * Update an annual deduction
     *
     * @param int   $id   Deduction ID
     * @param array $data Deduction data
     * @return int|false
     */
    public static function update($id, $data) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_annual_deductions';
        
        $update_data = array(
            'name' => sanitize_text_field($data['name']),
            'category' => sanitize_text_field($data['category']),
            'annual_amount' => floatval($data['annual_amount']),
            'deduction_percentage' => isset($data['deduction_percentage']) ? floatval($data['deduction_percentage']) : 100,
            'notes' => isset($data['notes']) ? sanitize_textarea_field($data['notes']) : '',
            'is_active' => isset($data['is_active']) ? intval($data['is_active']) : 1,
        );
        
        return $wpdb->update(
            $table,
            $update_data,
            array('id' => $id),
            array('%s', '%s', '%f', '%f', '%s', '%d'),
            array('%d')
        );
    }

    /**
     * Delete an annual deduction
     *
     * @param int $id Deduction ID
     * @return int|false
     */
    public static function delete($id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_annual_deductions';
        
        return $wpdb->delete($table, array('id' => $id), array('%d'));
    }

    /**
     * Get total annual deductions for a year
     *
     * @param int  $year        Year
     * @param bool $active_only Only include active deductions
     * @return float
     */
    public static function get_total($year = null, $active_only = true) {
        global $wpdb;
        
        if (!$year) {
            $year = gmdate('Y');
        }
        
        $table = $wpdb->prefix . 'fs_annual_deductions';
        $user_id = get_current_user_id();
        
        $where = array(
            $wpdb->prepare('user_id = %d', $user_id),
            $wpdb->prepare('year = %d', $year)
        );
        
        if ($active_only) {
            $where[] = 'is_active = 1';
        }
        
        $where_clause = implode(' AND ', $where);
        
        // Calculate: annual_amount * (deduction_percentage / 100)
        $total = $wpdb->get_var(
            "SELECT SUM(annual_amount * (deduction_percentage / 100)) 
             FROM {$table} 
             WHERE {$where_clause}"
        );
        
        return (float) $total;
    }

    /**
     * Get deductions by category for a year
     *
     * @param int  $year        Year
     * @param bool $active_only Only include active deductions
     * @return array
     */
    public static function get_by_category($year = null, $active_only = true) {
        global $wpdb;
        
        if (!$year) {
            $year = gmdate('Y');
        }
        
        $table = $wpdb->prefix . 'fs_annual_deductions';
        $user_id = get_current_user_id();
        
        $where = array(
            $wpdb->prepare('user_id = %d', $user_id),
            $wpdb->prepare('year = %d', $year)
        );
        
        if ($active_only) {
            $where[] = 'is_active = 1';
        }
        
        $where_clause = implode(' AND ', $where);
        
        return $wpdb->get_results(
            "SELECT category, 
                    SUM(annual_amount * (deduction_percentage / 100)) as total, 
                    COUNT(*) as count 
             FROM {$table} 
             WHERE {$where_clause} 
             GROUP BY category 
             ORDER BY total DESC"
        );
    }

    /**
     * Get common deduction categories
     *
     * @return array
     */
    public static function get_categories() {
        return array(
            'Home Office' => __('Home Office', 'freelance-studio'),
            'Internet & Phone' => __('Internet & Phone', 'freelance-studio'),
            'Utilities' => __('Utilities', 'freelance-studio'),
            'Health Insurance' => __('Health Insurance', 'freelance-studio'),
            'Retirement Contributions' => __('Retirement Contributions', 'freelance-studio'),
            'Professional Development' => __('Professional Development', 'freelance-studio'),
            'Software Subscriptions' => __('Software Subscriptions', 'freelance-studio'),
            'Equipment Depreciation' => __('Equipment Depreciation', 'freelance-studio'),
            'Professional Memberships' => __('Professional Memberships', 'freelance-studio'),
            'Business Insurance' => __('Business Insurance', 'freelance-studio'),
            'Vehicle Expenses' => __('Vehicle Expenses', 'freelance-studio'),
            'Marketing & Advertising' => __('Marketing & Advertising', 'freelance-studio'),
            'Other' => __('Other', 'freelance-studio'),
        );
    }

    /**
     * Get common deduction presets with typical amounts
     * These are suggestions only - actual amounts vary
     *
     * @return array
     */
    public static function get_presets() {
        return array(
            array(
                'name' => __('Home Office Deduction', 'freelance-studio'),
                'category' => 'Home Office',
                'description' => __('Simplified method: $5/sq ft up to 300 sq ft', 'freelance-studio'),
                'typical_amount' => 1500,
                'typical_percentage' => 100,
            ),
            array(
                'name' => __('Internet Service', 'freelance-studio'),
                'category' => 'Internet & Phone',
                'description' => __('Monthly internet bill for business use', 'freelance-studio'),
                'typical_amount' => 1200,
                'typical_percentage' => 50,
            ),
            array(
                'name' => __('Cell Phone', 'freelance-studio'),
                'category' => 'Internet & Phone',
                'description' => __('Mobile phone used for business', 'freelance-studio'),
                'typical_amount' => 1200,
                'typical_percentage' => 50,
            ),
            array(
                'name' => __('Adobe Creative Cloud', 'freelance-studio'),
                'category' => 'Software Subscriptions',
                'description' => __('Creative Cloud subscription', 'freelance-studio'),
                'typical_amount' => 660,
                'typical_percentage' => 100,
            ),
            array(
                'name' => __('Health Insurance Premiums', 'freelance-studio'),
                'category' => 'Health Insurance',
                'description' => __('Self-employed health insurance', 'freelance-studio'),
                'typical_amount' => 6000,
                'typical_percentage' => 100,
            ),
            array(
                'name' => __('SEP-IRA / Solo 401k', 'freelance-studio'),
                'category' => 'Retirement Contributions',
                'description' => __('Retirement savings contributions', 'freelance-studio'),
                'typical_amount' => 5000,
                'typical_percentage' => 100,
            ),
            array(
                'name' => __('Professional Liability Insurance', 'freelance-studio'),
                'category' => 'Business Insurance',
                'description' => __('E&O or professional liability coverage', 'freelance-studio'),
                'typical_amount' => 500,
                'typical_percentage' => 100,
            ),
            array(
                'name' => __('Electricity', 'freelance-studio'),
                'category' => 'Utilities',
                'description' => __('Home office portion of electricity', 'freelance-studio'),
                'typical_amount' => 1800,
                'typical_percentage' => 15,
            ),
            array(
                'name' => __('Online Courses & Training', 'freelance-studio'),
                'category' => 'Professional Development',
                'description' => __('Skillshare, Udemy, conferences, etc.', 'freelance-studio'),
                'typical_amount' => 500,
                'typical_percentage' => 100,
            ),
            array(
                'name' => __('Professional Association Dues', 'freelance-studio'),
                'category' => 'Professional Memberships',
                'description' => __('AIGA, Dribbble Pro, etc.', 'freelance-studio'),
                'typical_amount' => 300,
                'typical_percentage' => 100,
            ),
        );
    }

    /**
     * Copy deductions from one year to another
     *
     * @param int $from_year Source year
     * @param int $to_year   Destination year
     * @return int Number of deductions copied
     */
    public static function copy_to_year($from_year, $to_year) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_annual_deductions';
        $user_id = get_current_user_id();
        
        // Get deductions from source year
        $deductions = self::get_all($from_year);
        
        $count = 0;
        foreach ($deductions as $deduction) {
            // Check if already exists in destination year
            $exists = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$table} 
                 WHERE user_id = %d AND year = %d AND name = %s",
                $user_id,
                $to_year,
                $deduction->name
            ));
            
            if (!$exists) {
                $result = self::create(array(
                    'year' => $to_year,
                    'name' => $deduction->name,
                    'category' => $deduction->category,
                    'annual_amount' => $deduction->annual_amount,
                    'deduction_percentage' => $deduction->deduction_percentage,
                    'notes' => $deduction->notes,
                    'is_active' => $deduction->is_active,
                ));
                
                if ($result) {
                    $count++;
                }
            }
        }
        
        return $count;
    }

    /**
     * Count deductions for a year
     *
     * @param int $year Year
     * @return int
     */
    public static function count($year = null) {
        global $wpdb;
        
        if (!$year) {
            $year = gmdate('Y');
        }
        
        $table = $wpdb->prefix . 'fs_annual_deductions';
        $user_id = get_current_user_id();
        
        return (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE user_id = %d AND year = %d",
            $user_id,
            $year
        ));
    }
}
