<?php
/**
 * Quarterly Tax Model
 * Handles quarterly tax tracking for freelance income
 *
 * @package Freelance_Studio
 */

class FS_Quarterly_Tax {
    
    /**
     * Get or create quarterly tax record
     * 
     * @param int $user_id User ID
     * @param int $year Year
     * @param int $quarter Quarter (1-4)
     * @return object|null Quarterly tax record
     */
    public static function get_or_create($user_id, $year, $quarter) {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_quarterly_tax_payments';
        
        // Convert quarter number to string format used in table
        $quarter_str = 'Q' . $quarter;
        
        // Try to get existing record
        $record = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table WHERE user_id = %d AND year = %d AND quarter = %s",
            $user_id, $year, $quarter_str
        ));
        
        if ($record) {
            return $record;
        }
        
        // Create new record
        $wpdb->insert(
            $table,
            array(
                'user_id' => $user_id,
                'year' => $year,
                'quarter' => $quarter_str,
                'estimated_amount' => 0.00,
                'actual_payment' => 0.00,
                'payment_date' => null,
                'notes' => ''
            ),
            array('%d', '%d', '%s', '%f', '%f', '%s', '%s')
        );
        
        return self::get_or_create($user_id, $year, $quarter);
    }
    
    /**
     * Update quarterly tax payment
     * 
     * @param int $id Record ID
     * @param array $data Data to update
     * @return bool Success
     */
    public static function update($id, $data) {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_quarterly_tax_payments';
        
        $result = $wpdb->update(
            $table,
            $data,
            array('id' => $id),
            null,
            array('%d')
        );
        
        return $result !== false;
    }
    
    /**
     * Get record by ID
     * 
     * @param int $id Record ID
     * @return object|null
     */
    public static function get($id) {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_quarterly_tax_payments';
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table WHERE id = %d",
            $id
        ));
    }
    
    /**
     * Calculate quarterly income and taxes
     * Calculates on all freelance income (invoices + manual income)
     * 
     * @param int $year Year
     * @param int $quarter Quarter (1-4)
     * @return array Income and tax calculations
     */
    public static function calculate_quarter($year, $quarter) {
        global $wpdb;
        
        // Define quarter date ranges
        $quarters = array(
            1 => array('start' => "$year-01-01", 'end' => "$year-03-31"),
            2 => array('start' => "$year-04-01", 'end' => "$year-06-30"),
            3 => array('start' => "$year-07-01", 'end' => "$year-09-30"),
            4 => array('start' => "$year-10-01", 'end' => "$year-12-31")
        );
        
        if (!isset($quarters[$quarter])) {
            return array('income' => 0, 'federal' => 0, 'state' => 0, 'total' => 0);
        }
        
        $start_date = $quarters[$quarter]['start'];
        $end_date = $quarters[$quarter]['end'] . ' 23:59:59';
        
        // Get paid invoice income for this quarter
        $invoices_table = $wpdb->prefix . 'fs_invoices';
        
        $invoice_income = $wpdb->get_var($wpdb->prepare(
            "SELECT SUM(total) as total
            FROM $invoices_table
            WHERE status = 'paid'
            AND paid_at >= %s AND paid_at <= %s",
            $start_date, $end_date
        ));
        
        $invoice_income = $invoice_income ? floatval($invoice_income) : 0;
        
        // Get manual income for this quarter
        $manual_income = FS_Manual_Income::get_total($start_date, $quarters[$quarter]['end']);
        
        // Total income = invoices + manual income
        $income = $invoice_income + $manual_income;
        
        // Get expenses for this quarter
        $expenses_table = $wpdb->prefix . 'fs_expenses';
        $expenses = $wpdb->get_var($wpdb->prepare(
            "SELECT SUM(amount) as total
            FROM $expenses_table
            WHERE expense_date BETWEEN %s AND %s",
            $start_date, $quarters[$quarter]['end']
        ));
        $expenses = $expenses ? floatval($expenses) : 0;
        
        // Net income after expenses
        $net_income = max(0, $income - $expenses);
        
        // Get user's state and federal bracket for tax calculation
        $state = get_option('fs_tax_state', '');
        $state_rate = FS_Tax_Rates::get_state_rate($state);
        $federal_bracket = floatval(get_option('fs_federal_tax_bracket', 22));
        
        // Self-Employment Tax Rate (15.3% - Social Security 12.4% + Medicare 2.9%)
        $se_tax_rate = 15.3;
        
        // === GROSS TAX CALCULATION (before expenses/deductions) ===
        $gross_se_tax = $income * ($se_tax_rate / 100);
        $gross_se_deduction = $gross_se_tax * 0.5;
        $gross_taxable = $income - $gross_se_deduction;
        $gross_federal_income_tax = $gross_taxable * ($federal_bracket / 100);
        $gross_state_tax = $gross_taxable * ($state_rate / 100);
        $gross_total_federal = $gross_se_tax + $gross_federal_income_tax;
        $gross_total_tax = $gross_total_federal + $gross_state_tax;
        
        // === NET TAX CALCULATION (after expenses/deductions) ===
        $se_tax = $net_income * ($se_tax_rate / 100);
        $se_tax_deduction = $se_tax * 0.5;
        $taxable_income = $net_income - $se_tax_deduction;
        $federal_income_tax = $taxable_income * ($federal_bracket / 100);
        $state_tax = $taxable_income * ($state_rate / 100);
        $total_federal = $se_tax + $federal_income_tax;
        $total_tax = $total_federal + $state_tax;
        
        // Tax savings from expenses/deductions
        $tax_savings = $gross_total_tax - $total_tax;
        
        return array(
            'income' => $income,
            'expenses' => $expenses,
            'net_income' => $net_income,
            // Gross calculations (before expenses)
            'gross_se_tax' => $gross_se_tax,
            'gross_federal' => $gross_total_federal,
            'gross_state' => $gross_state_tax,
            'gross_total' => $gross_total_tax,
            // Net calculations (after expenses)
            'se_tax' => $se_tax,
            'se_tax_deduction' => $se_tax_deduction,
            'taxable_income' => $taxable_income,
            'federal_income_tax' => $federal_income_tax,
            'federal' => $total_federal,
            'state' => $state_tax,
            'total' => $total_tax,
            'se_tax_rate' => $se_tax_rate,
            'federal_bracket' => $federal_bracket,
            'state_rate' => $state_rate
        );
    }
    
    /**
     * Get all quarterly tax records for a year with calculations
     * 
     * @param int $user_id User ID
     * @param int $year Year
     * @return array Array of quarterly tax records
     */
    public static function get_year_records($user_id, $year) {
        $records = array();
        
        for ($quarter = 1; $quarter <= 4; $quarter++) {
            $record = self::get_or_create($user_id, $year, $quarter);
            $calculations = self::calculate_quarter($year, $quarter);
            
            // Update record with latest calculations
            if ($record) {
                self::update($record->id, array(
                    'estimated_amount' => $calculations['total']
                ));
                
                // Refresh record
                $record = self::get_or_create($user_id, $year, $quarter);
                
                // Add calculation details to record object
                $record->income = $calculations['income'];
                $record->expenses = $calculations['expenses'];
                $record->net_income = $calculations['net_income'];
                $record->estimated_federal = $calculations['federal'];
                $record->estimated_state = $calculations['state'];
                $record->estimated_total = $calculations['total'];
                $record->paid = floatval($record->actual_payment) > 0 ? 1 : 0;
            }
            
            $records[$quarter] = $record;
        }
        
        return $records;
    }
    
    /**
     * Update actual payment amount
     * 
     * @param int $record_id Record ID
     * @param float $amount Payment amount
     * @return bool Success
     */
    public static function update_payment($record_id, $amount) {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_quarterly_tax_payments';
        
        $result = $wpdb->update(
            $table,
            array(
                'actual_payment' => floatval($amount),
                'payment_date' => $amount > 0 ? current_time('Y-m-d') : null
            ),
            array('id' => $record_id),
            array('%f', '%s'),
            array('%d')
        );
        
        return $result !== false;
    }
    
    /**
     * Update paid status
     * 
     * @param int $record_id Record ID
     * @param int $paid Paid status (0 or 1)
     * @return bool Success
     */
    public static function update_paid_status($record_id, $paid) {
        // In our implementation, paid status is derived from actual_payment > 0
        // But we can add a dedicated column if needed
        // For now, we just return true as the status is calculated
        return true;
    }
}
