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

namespace App;

use PDO;
use PDOException;

class Enterprise {
    private $db;
    private $table = 'enterprises';
    
    public function __construct($db) {
        $this->db = $db;
    }
    
    /**
     * Create new enterprise
     */
    public function create($farmId, $data) {
        try {
            $sql = "INSERT INTO {$this->table} 
                    (farm_id, enterprise_type, enterprise_name, size_acres, quantity, 
                     planting_date, expected_harvest_date, status, notes)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute([
                $farmId,
                $data['enterprise_type'],
                sanitize($data['enterprise_name'] ?? ''),
                $data['size_acres'] ?? 0,
                $data['quantity'] ?? 0,
                $data['planting_date'] ?? null,
                $data['expected_harvest_date'] ?? null,
                $data['status'] ?? 'planning',
                sanitize($data['notes'] ?? '')
            ]);
            
            if ($result) {
                $enterpriseId = $this->db->lastInsertId();
                
                // Get user ID from farm
                $farmSql = "SELECT user_id FROM farms WHERE id = ?";
                $farmStmt = $this->db->prepare($farmSql);
                $farmStmt->execute([$farmId]);
                $farm = $farmStmt->fetch(PDO::FETCH_ASSOC);
                
                if ($farm) {
                    logActivity($farm['user_id'], 'create_enterprise', 
                        "Created enterprise: {$data['enterprise_type']}");
                }
                
                return [
                    'success' => true,
                    'message' => 'Enterprise created successfully',
                    'enterprise_id' => $enterpriseId
                ];
            }
            
            return ['success' => false, 'message' => 'Failed to create enterprise'];
            
        } catch (PDOException $e) {
            error_log("Enterprise creation error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Database error occurred'];
        }
    }
    
    /**
     * Get farm enterprises
     */
    public function getFarmEnterprises($farmId) {
        $sql = "SELECT e.*,
                (SELECT COUNT(*) FROM products WHERE enterprise_id = e.id) as product_count,
                (SELECT SUM(amount) FROM transactions WHERE enterprise_id = e.id AND transaction_type = 'income') as total_income,
                (SELECT SUM(amount) FROM transactions WHERE enterprise_id = e.id AND transaction_type = 'expense') as total_expenses
                FROM {$this->table} e
                WHERE e.farm_id = ?
                ORDER BY e.created_at DESC";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$farmId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * Get enterprise by ID
     */
    public function getById($enterpriseId) {
        $sql = "SELECT e.*, f.user_id, f.farm_name,
                (SELECT COUNT(*) FROM products WHERE enterprise_id = e.id) as product_count,
                (SELECT SUM(amount) FROM transactions WHERE enterprise_id = e.id AND transaction_type = 'income') as total_income,
                (SELECT SUM(amount) FROM transactions WHERE enterprise_id = e.id AND transaction_type = 'expense') as total_expenses
                FROM {$this->table} e
                JOIN farms f ON e.farm_id = f.id
                WHERE e.id = ?";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$enterpriseId]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * Update enterprise
     */
    public function update($enterpriseId, $data) {
        try {
            $sql = "UPDATE {$this->table} SET 
                    enterprise_type = ?,
                    enterprise_name = ?,
                    size_acres = ?,
                    quantity = ?,
                    planting_date = ?,
                    expected_harvest_date = ?,
                    status = ?,
                    notes = ?,
                    updated_at = CURRENT_TIMESTAMP
                    WHERE id = ?";
            
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute([
                $data['enterprise_type'],
                sanitize($data['enterprise_name']),
                $data['size_acres'],
                $data['quantity'],
                $data['planting_date'],
                $data['expected_harvest_date'],
                $data['status'],
                sanitize($data['notes'] ?? ''),
                $enterpriseId
            ]);
            
            if ($result) {
                return ['success' => true, 'message' => 'Enterprise updated successfully'];
            }
            
            return ['success' => false, 'message' => 'Failed to update enterprise'];
            
        } catch (PDOException $e) {
            error_log("Enterprise update error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Database error occurred'];
        }
    }
    
    /**
     * Delete enterprise
     */
    public function delete($enterpriseId) {
        try {
            // Check for linked products
            $checkSql = "SELECT COUNT(*) as count FROM products WHERE enterprise_id = ?";
            $checkStmt = $this->db->prepare($checkSql);
            $checkStmt->execute([$enterpriseId]);
            $result = $checkStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($result['count'] > 0) {
                return [
                    'success' => false,
                    'message' => 'Cannot delete enterprise with linked products'
                ];
            }
            
            $sql = "DELETE FROM {$this->table} WHERE id = ?";
            $stmt = $this->db->prepare($sql);
            
            if ($stmt->execute([$enterpriseId])) {
                return ['success' => true, 'message' => 'Enterprise deleted successfully'];
            }
            
            return ['success' => false, 'message' => 'Failed to delete enterprise'];
            
        } catch (PDOException $e) {
            error_log("Enterprise deletion error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Database error occurred'];
        }
    }
    
    /**
     * Get enterprise summary
     */
    public function getSummary($enterpriseId) {
        $summary = [];
        
        // Get basic info
        $summary['enterprise'] = $this->getById($enterpriseId);
        
        // Get transactions
        $sql = "SELECT * FROM transactions 
                WHERE enterprise_id = ? 
                ORDER BY transaction_date DESC 
                LIMIT 10";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$enterpriseId]);
        $summary['recent_transactions'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get products
        $sql = "SELECT * FROM products 
                WHERE enterprise_id = ? 
                ORDER BY created_at DESC 
                LIMIT 5";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$enterpriseId]);
        $summary['products'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return $summary;
    }
    
    /**
     * Get upcoming harvests
     */
    public function getUpcomingHarvests($userId, $days = 30) {
        $sql = "SELECT e.*, f.farm_name
                FROM {$this->table} e
                JOIN farms f ON e.farm_id = f.id
                WHERE f.user_id = ?
                AND e.expected_harvest_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL ? DAY)
                AND e.status IN ('planted', 'growing')
                ORDER BY e.expected_harvest_date ASC";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$userId, $days]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>
