<?php
/**
 * ============================================================================
 * farm/index.php - Enhanced Farm Management Overview
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

// Only farmers can access
if (getUserType() !== 'farmer') {
    redirect('/dashboard/', 'Only farmers can access farm management', 'error');
}

$pageTitle = 'My Farm';
$userId = getUserId();

// Initialize database
$database = new Database();
$db = $database->getConnection();

// Get or create farm
$farmClass = new \App\Farm($db);
$farms = $farmClass->getUserFarms($userId);

// If no farm exists, create one
if (empty($farms)) {
    $result = $farmClass->create($userId, ['farm_name' => 'My Farm']);
    if ($result['success']) {
        $farms = $farmClass->getUserFarms($userId);
    }
}

$farm = $farms[0] ?? null;

// Get enterprises if farm exists
$enterprises = [];
if ($farm) {
    $enterpriseClass = new \App\Enterprise($db);
    $enterprises = $enterpriseClass->getFarmEnterprises($farm['id']);
}

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-house-heart text-success"></i> <?php echo $farm ? htmlspecialchars($farm['farm_name']) : 'My Farm'; ?>
                    </h2>
                    <p class="text-muted mb-0">Manage your farm and enterprises</p>
                </div>
                <div class="d-flex gap-2">
                    <a href="<?php echo APP_URL; ?>/farm/profile.php" class="btn btn-outline-primary">
                        <i class="bi bi-gear"></i> <span class="d-none d-md-inline">Settings</span>
                    </a>
                    <a href="<?php echo APP_URL; ?>/farm/add-enterprise.php" class="btn btn-success">
                        <i class="bi bi-plus-circle"></i> <span class="d-none d-md-inline">Add Enterprise</span>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <?php if ($farm): ?>
        <!-- Farm Summary Cards -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <p class="text-muted mb-1">Total Land</p>
                                <h3 class="mb-0"><?php echo number_format($farm['total_acres'], 1); ?></h3>
                                <small class="text-muted">
                                    <?php echo number_format($farm['used_acres'] ?? 0, 1); ?> used
                                </small>
                            </div>
                            <div class="bg-success bg-opacity-10 p-3 rounded">
                                <i class="bi bi-map text-success fs-4"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <p class="text-muted mb-1">Enterprises</p>
                                <h3 class="mb-0"><?php echo count($enterprises); ?></h3>
                                <small class="text-success">
                                    <?php 
                                    $active = count(array_filter($enterprises, fn($e) => in_array($e['status'], ['planted', 'growing'])));
                                    echo $active; ?> active
                                </small>
                            </div>
                            <div class="bg-primary bg-opacity-10 p-3 rounded">
                                <i class="bi bi-flower3 text-primary fs-4"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <p class="text-muted mb-1">Products Listed</p>
                                <?php
                                $sql = "SELECT COUNT(*) as count FROM products WHERE seller_id = ? AND status = 'available'";
                                $stmt = $db->prepare($sql);
                                $stmt->execute([$userId]);
                                $productCount = $stmt->fetch()['count'];
                                ?>
                                <h3 class="mb-0"><?php echo $productCount; ?></h3>
                                <a href="<?php echo APP_URL; ?>/marketplace/my-products.php" class="small text-decoration-none">
                                    View all <i class="bi bi-arrow-right"></i>
                                </a>
                            </div>
                            <div class="bg-warning bg-opacity-10 p-3 rounded">
                                <i class="bi bi-box-seam text-warning fs-4"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <p class="text-muted mb-1">This Month</p>
                                <?php
                                $sql = "SELECT SUM(CASE WHEN transaction_type = 'income' THEN amount ELSE -amount END) as profit
                                        FROM transactions 
                                        WHERE user_id = ? 
                                        AND MONTH(transaction_date) = MONTH(CURDATE())
                                        AND YEAR(transaction_date) = YEAR(CURDATE())";
                                $stmt = $db->prepare($sql);
                                $stmt->execute([$userId]);
                                $profit = $stmt->fetch()['profit'] ?? 0;
                                ?>
                                <h3 class="mb-0 <?php echo $profit >= 0 ? 'text-success' : 'text-danger'; ?>">
                                    <?php echo formatCurrency(abs($profit)); ?>
                                </h3>
                                <small class="<?php echo $profit >= 0 ? 'text-success' : 'text-danger'; ?>">
                                    <?php echo $profit >= 0 ? 'Profit' : 'Loss'; ?>
                                </small>
                            </div>
                            <div class="bg-info bg-opacity-10 p-3 rounded">
                                <i class="bi bi-graph-up text-info fs-4"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Navigation Cards -->
        <div class="row mb-4">
            <div class="col-12">
                <h5 class="mb-3">
                    <i class="bi bi-grid-3x3-gap"></i> Farm Management
                </h5>
            </div>

            <div class="col-lg-3 col-md-6 mb-3">
                <a href="<?php echo APP_URL; ?>/farm/analytics.php" class="card border-0 shadow-sm text-decoration-none h-100 hover-lift">
                    <div class="card-body text-center p-4">
                        <div class="bg-primary bg-opacity-10 p-3 rounded-circle d-inline-block mb-3">
                            <i class="bi bi-graph-up-arrow text-primary" style="font-size: 2rem;"></i>
                        </div>
                        <h6 class="mb-2">Analytics</h6>
                        <p class="text-muted small mb-0">View farm performance</p>
                    </div>
                </a>
            </div>

            <div class="col-lg-3 col-md-6 mb-3">
                <a href="<?php echo APP_URL; ?>/farm/transactions.php" class="card border-0 shadow-sm text-decoration-none h-100 hover-lift">
                    <div class="card-body text-center p-4">
                        <div class="bg-info bg-opacity-10 p-3 rounded-circle d-inline-block mb-3">
                            <i class="bi bi-wallet2 text-info" style="font-size: 2rem;"></i>
                        </div>
                        <h6 class="mb-2">Transactions</h6>
                        <p class="text-muted small mb-0">Track income & expenses</p>
                    </div>
                </a>
            </div>

            <div class="col-lg-3 col-md-6 mb-3">
                <a href="<?php echo APP_URL; ?>/farm/reports.php" class="card border-0 shadow-sm text-decoration-none h-100 hover-lift">
                    <div class="card-body text-center p-4">
                        <div class="bg-warning bg-opacity-10 p-3 rounded-circle d-inline-block mb-3">
                            <i class="bi bi-bar-chart text-warning" style="font-size: 2rem;"></i>
                        </div>
                        <h6 class="mb-2">Financial Reports</h6>
                        <p class="text-muted small mb-0">Detailed analysis</p>
                    </div>
                </a>
            </div>

            <div class="col-lg-3 col-md-6 mb-3">
                <a href="<?php echo APP_URL; ?>/farm/profile.php" class="card border-0 shadow-sm text-decoration-none h-100 hover-lift">
                    <div class="card-body text-center p-4">
                        <div class="bg-success bg-opacity-10 p-3 rounded-circle d-inline-block mb-3">
                            <i class="bi bi-gear text-success" style="font-size: 2rem;"></i>
                        </div>
                        <h6 class="mb-2">Farm Profile</h6>
                        <p class="text-muted small mb-0">Manage settings</p>
                    </div>
                </a>
            </div>
        </div>

        <!-- Enterprises List -->
        <div class="row">
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white border-bottom">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="bi bi-flower2"></i> My Enterprises
                            </h5>
                            <a href="<?php echo APP_URL; ?>/farm/add-enterprise.php" class="btn btn-sm btn-success">
                                <i class="bi bi-plus-circle"></i> Add New
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($enterprises)): ?>
                            <div class="table-responsive">
                                <table class="table table-hover align-middle">
                                    <thead>
                                        <tr>
                                            <th>Enterprise</th>
                                            <th>Type</th>
                                            <th>Size</th>
                                            <th>Status</th>
                                            <th>Planting Date</th>
                                            <th>Expected Harvest</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($enterprises as $enterprise): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($enterprise['enterprise_name'] ?: ucfirst(str_replace('_', ' ', $enterprise['enterprise_type']))); ?></strong>
                                                </td>
                                                <td>
                                                    <span class="badge bg-primary">
                                                        <?php echo ucfirst(str_replace('_', ' ', $enterprise['enterprise_type'])); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo number_format($enterprise['size_acres'], 1); ?> acres</td>
                                                <td>
                                                    <span class="badge bg-<?php echo getStatusBadgeClass($enterprise['status']); ?>">
                                                        <?php echo ucfirst($enterprise['status']); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo $enterprise['planting_date'] ? formatDate($enterprise['planting_date']) : 'N/A'; ?></td>
                                                <td><?php echo $enterprise['expected_harvest_date'] ? formatDate($enterprise['expected_harvest_date']) : 'N/A'; ?></td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="<?php echo APP_URL; ?>/farm/edit-enterprise.php?id=<?php echo $enterprise['id']; ?>" 
                                                           class="btn btn-outline-primary" title="Edit">
                                                            <i class="bi bi-pencil"></i>
                                                        </a>
                                                        <button class="btn btn-outline-danger" 
                                                                onclick="deleteEnterprise(<?php echo $enterprise['id']; ?>)" title="Delete">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="bi bi-flower3 text-muted" style="font-size: 4rem;"></i>
                                <h5 class="mt-3">No Enterprises Yet</h5>
                                <p class="text-muted">Start by adding your first enterprise</p>
                                <a href="<?php echo APP_URL; ?>/farm/add-enterprise.php" class="btn btn-success">
                                    <i class="bi bi-plus-circle"></i> Add Enterprise
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

    <?php else: ?>
        <div class="row">
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-5">
                        <i class="bi bi-house-heart text-muted" style="font-size: 5rem;"></i>
                        <h4 class="mt-3">Setup Your Farm</h4>
                        <p class="text-muted">Get started by creating your farm profile</p>
                        <button class="btn btn-success btn-lg" onclick="location.reload()">
                            <i class="bi bi-plus-circle"></i> Create Farm
                        </button>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<style>
.hover-lift {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hover-lift:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.15) !important;
}
</style>

<script>
function deleteEnterprise(enterpriseId) {
    confirmAction(
        'Delete Enterprise',
        'Are you sure? This will also delete linked products.',
        function() {
            showToast('Feature coming soon', 'info');
        }
    );
}
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>