<?php
/**
 * ============================================================================
 * classes/Farm.php - Farm Management Class
 * ============================================================================
 */

namespace App;

use PDO;
use PDOException;

class Farm {
    private $db;
    private $table = 'farms';
    
    public function __construct($db) {
        $this->db = $db;
    }
    
    /**
     * Create new farm
     */
    public function create($userId, $data) {
        try {
            $sql = "INSERT INTO {$this->table} 
                    (user_id, farm_name, total_acres, location_lat, location_lng, soil_type, water_source)
                    VALUES (?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute([
                $userId,
                sanitize($data['farm_name'] ?? 'My Farm'),
                $data['total_acres'] ?? 0,
                $data['location_lat'] ?? null,
                $data['location_lng'] ?? null,
                sanitize($data['soil_type'] ?? ''),
                sanitize($data['water_source'] ?? '')
            ]);
            
            if ($result) {
                $farmId = $this->db->lastInsertId();
                logActivity($userId, 'create_farm', "Created farm: {$data['farm_name']}");
                
                return [
                    'success' => true,
                    'message' => 'Farm created successfully',
                    'farm_id' => $farmId
                ];
            }
            
            return ['success' => false, 'message' => 'Failed to create farm'];
            
        } catch (PDOException $e) {
            error_log("Farm creation error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Database error occurred'];
        }
    }
    
    /**
     * Get user's farms
     */
    public function getUserFarms($userId) {
        $sql = "SELECT f.*, 
                COUNT(DISTINCT e.id) as enterprise_count,
                (SELECT SUM(size_acres) FROM enterprises WHERE farm_id = f.id) as used_acres
                FROM {$this->table} f
                LEFT JOIN enterprises e ON f.id = e.farm_id
                WHERE f.user_id = ?
                GROUP BY f.id
                ORDER BY f.created_at DESC";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$userId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * Get farm by ID
     */
    public function getById($farmId, $userId = null) {
        $sql = "SELECT f.*, 
                COUNT(DISTINCT e.id) as enterprise_count,
                (SELECT SUM(size_acres) FROM enterprises WHERE farm_id = f.id) as used_acres
                FROM {$this->table} f
                LEFT JOIN enterprises e ON f.id = e.farm_id
                WHERE f.id = ?";
        
        if ($userId) {
            $sql .= " AND f.user_id = ?";
        }
        
        $sql .= " GROUP BY f.id";
        
        $stmt = $this->db->prepare($sql);
        $userId ? $stmt->execute([$farmId, $userId]) : $stmt->execute([$farmId]);
        
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * Update farm
     */
    public function update($farmId, $userId, $data) {
        try {
            $sql = "UPDATE {$this->table} SET 
                    farm_name = ?,
                    total_acres = ?,
                    location_lat = ?,
                    location_lng = ?,
                    soil_type = ?,
                    water_source = ?,
                    updated_at = CURRENT_TIMESTAMP
                    WHERE id = ? AND user_id = ?";
            
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute([
                sanitize($data['farm_name']),
                $data['total_acres'],
                $data['location_lat'] ?? null,
                $data['location_lng'] ?? null,
                sanitize($data['soil_type'] ?? ''),
                sanitize($data['water_source'] ?? ''),
                $farmId,
                $userId
            ]);
            
            if ($result) {
                logActivity($userId, 'update_farm', "Updated farm ID: {$farmId}");
                return ['success' => true, 'message' => 'Farm updated successfully'];
            }
            
            return ['success' => false, 'message' => 'Failed to update farm'];
            
        } catch (PDOException $e) {
            error_log("Farm update error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Database error occurred'];
        }
    }
    
    /**
     * Delete farm
     */
    public function delete($farmId, $userId) {
        try {
            // Check if farm has enterprises
            $checkSql = "SELECT COUNT(*) as count FROM enterprises WHERE farm_id = ?";
            $checkStmt = $this->db->prepare($checkSql);
            $checkStmt->execute([$farmId]);
            $result = $checkStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($result['count'] > 0) {
                return [
                    'success' => false,
                    'message' => 'Cannot delete farm with active enterprises. Please delete enterprises first.'
                ];
            }
            
            $sql = "DELETE FROM {$this->table} WHERE id = ? AND user_id = ?";
            $stmt = $this->db->prepare($sql);
            
            if ($stmt->execute([$farmId, $userId])) {
                logActivity($userId, 'delete_farm', "Deleted farm ID: {$farmId}");
                return ['success' => true, 'message' => 'Farm deleted successfully'];
            }
            
            return ['success' => false, 'message' => 'Failed to delete farm'];
            
        } catch (PDOException $e) {
            error_log("Farm deletion error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Database error occurred'];
        }
    }
    
    /**
     * Get farm statistics
     */
    public function getStatistics($farmId) {
        $stats = [];
        
        // Enterprise summary
        $sql = "SELECT 
                enterprise_type,
                COUNT(*) as count,
                SUM(size_acres) as total_acres,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed
                FROM enterprises
                WHERE farm_id = ?
                GROUP BY enterprise_type";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$farmId]);
        $stats['enterprises'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Financial summary
        $sql = "SELECT 
                SUM(CASE WHEN transaction_type = 'income' THEN amount ELSE 0 END) as total_income,
                SUM(CASE WHEN transaction_type = 'expense' THEN amount ELSE 0 END) as total_expenses,
                SUM(CASE WHEN transaction_type = 'income' THEN amount ELSE -amount END) as net_profit
                FROM transactions t
                JOIN enterprises e ON t.enterprise_id = e.id
                WHERE e.farm_id = ?";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$farmId]);
        $stats['financial'] = $stmt->fetch(PDO::FETCH_ASSOC);
        
        return $stats;
    }
}
?>
