<?php
/**
 * ============================================================================
 * farm/analytics.php - Farm Analytics Dashboard
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

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

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

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

// Get farm data
$farmClass = new \App\Farm($db);
$farms = $farmClass->getUserFarms($userId);
$farm = $farms[0] ?? null;

if (!$farm) {
    redirect('/farm/', 'Please create a farm first', 'error');
}

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

// Get transaction summary
$transactionClass = new \App\Transaction($db);
$monthSummary = $transactionClass->getSummary($userId, date('Y-m-01'), date('Y-m-t'));
$yearSummary = $transactionClass->getSummary($userId, date('Y-01-01'), date('Y-12-31'));

// Get upcoming harvests
$upcomingHarvests = $enterpriseClass->getUpcomingHarvests($userId, 30);

// Get products count
$sql = "SELECT COUNT(*) as count FROM products WHERE seller_id = ? AND status = 'available'";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$productsCount = $stmt->fetch()['count'];

// Get enterprise breakdown by type
$sql = "SELECT enterprise_type, 
        COUNT(*) as count,
        SUM(size_acres) as total_acres
        FROM enterprises 
        WHERE farm_id = ?
        GROUP BY enterprise_type
        ORDER BY count DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$farm['id']]);
$enterpriseBreakdown = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get enterprise by status
$sql = "SELECT status, COUNT(*) as count
        FROM enterprises 
        WHERE farm_id = ?
        GROUP BY status";
$stmt = $db->prepare($sql);
$stmt->execute([$farm['id']]);
$statusBreakdown = $stmt->fetchAll(PDO::FETCH_ASSOC);

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">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-graph-up-arrow text-primary"></i> Farm Analytics
                    </h2>
                    <p class="text-muted mb-0">Comprehensive overview of your farm performance</p>
                </div>
                <div>
                    <a href="<?php echo APP_URL; ?>/farm/" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left"></i> Back
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Key Metrics -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div>
                            <p class="text-muted mb-1 small">Total Land</p>
                            <h3 class="mb-0"><?php echo number_format($farm['total_acres'], 1); ?></h3>
                            <small class="text-muted">acres</small>
                        </div>
                        <div class="bg-primary bg-opacity-10 p-3 rounded">
                            <i class="bi bi-map text-primary fs-4"></i>
                        </div>
                    </div>
                    <div class="progress mt-3" style="height: 6px;">
                        <?php
                        $utilization = $farm['total_acres'] > 0 
                            ? (($farm['used_acres'] ?? 0) / $farm['total_acres'] * 100) 
                            : 0;
                        ?>
                        <div class="progress-bar bg-primary" style="width: <?php echo $utilization; ?>%"></div>
                    </div>
                    <small class="text-muted"><?php echo number_format($utilization, 1); ?>% utilized</small>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div>
                            <p class="text-muted mb-1 small">Active 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-success bg-opacity-10 p-3 rounded">
                            <i class="bi bi-flower3 text-success fs-4"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div>
                            <p class="text-muted mb-1 small">This Month Profit</p>
                            <h3 class="mb-0 <?php echo ($monthSummary['net_profit'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?>">
                                <?php echo formatCurrency(abs($monthSummary['net_profit'] ?? 0)); ?>
                            </h3>
                            <small class="<?php echo ($monthSummary['net_profit'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?>">
                                <?php echo ($monthSummary['net_profit'] ?? 0) >= 0 ? '↑ Profit' : '↓ Loss'; ?>
                            </small>
                        </div>
                        <div class="bg-warning bg-opacity-10 p-3 rounded">
                            <i class="bi bi-cash-stack text-warning fs-4"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div>
                            <p class="text-muted mb-1 small">Products Listed</p>
                            <h3 class="mb-0"><?php echo $productsCount; ?></h3>
                            <small class="text-info">in marketplace</small>
                        </div>
                        <div class="bg-info bg-opacity-10 p-3 rounded">
                            <i class="bi bi-box-seam text-info fs-4"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <!-- Enterprise Breakdown -->
        <div class="col-lg-4 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom">
                    <h6 class="mb-0">
                        <i class="bi bi-pie-chart"></i> Enterprise Distribution
                    </h6>
                </div>
                <div class="card-body">
                    <?php if (!empty($enterpriseBreakdown)): ?>
                        <?php foreach ($enterpriseBreakdown as $type): ?>
                            <div class="mb-3">
                                <div class="d-flex justify-content-between mb-1">
                                    <span class="small"><?php echo ucwords(str_replace('_', ' ', $type['enterprise_type'])); ?></span>
                                    <span class="small fw-semibold"><?php echo $type['count']; ?> (<?php echo number_format($type['total_acres'], 1); ?> acres)</span>
                                </div>
                                <div class="progress" style="height: 8px;">
                                    <?php
                                    $percentage = $farm['total_acres'] > 0 
                                        ? ($type['total_acres'] / $farm['total_acres'] * 100) 
                                        : 0;
                                    ?>
                                    <div class="progress-bar bg-primary" style="width: <?php echo $percentage; ?>%"></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="text-muted text-center py-4">No enterprises yet</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Enterprise Status -->
        <div class="col-lg-4 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom">
                    <h6 class="mb-0">
                        <i class="bi bi-list-check"></i> Enterprise Status
                    </h6>
                </div>
                <div class="card-body">
                    <?php if (!empty($statusBreakdown)): ?>
                        <?php 
                        $statusColors = [
                            'planning' => 'secondary',
                            'planted' => 'info',
                            'growing' => 'success',
                            'harvesting' => 'warning',
                            'completed' => 'primary'
                        ];
                        $statusIcons = [
                            'planning' => 'clipboard',
                            'planted' => 'seedling',
                            'growing' => 'tree',
                            'harvesting' => 'scissors',
                            'completed' => 'check-circle'
                        ];
                        $totalCount = array_sum(array_column($statusBreakdown, 'count'));
                        ?>
                        <?php foreach ($statusBreakdown as $status): ?>
                            <?php 
                            $percentage = $totalCount > 0 ? ($status['count'] / $totalCount * 100) : 0;
                            $color = $statusColors[$status['status']] ?? 'secondary';
                            $icon = $statusIcons[$status['status']] ?? 'circle';
                            ?>
                            <div class="d-flex align-items-center justify-content-between mb-3">
                                <div class="d-flex align-items-center">
                                    <div class="bg-<?php echo $color; ?> bg-opacity-10 p-2 rounded me-3">
                                        <i class="bi bi-<?php echo $icon; ?> text-<?php echo $color; ?>"></i>
                                    </div>
                                    <div>
                                        <div class="fw-semibold"><?php echo ucfirst($status['status']); ?></div>
                                        <small class="text-muted"><?php echo number_format($percentage, 0); ?>%</small>
                                    </div>
                                </div>
                                <span class="badge bg-<?php echo $color; ?> rounded-pill"><?php echo $status['count']; ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="text-muted text-center py-4">No data available</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Financial Summary -->
        <div class="col-lg-4 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom">
                    <h6 class="mb-0">
                        <i class="bi bi-wallet2"></i> Financial Summary (Year)
                    </h6>
                </div>
                <div class="card-body">
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <span class="text-muted">Total Income</span>
                            <span class="fs-5 fw-semibold text-success">
                                <?php echo formatCurrency($yearSummary['total_income'] ?? 0); ?>
                            </span>
                        </div>
                        <div class="progress" style="height: 10px;">
                            <div class="progress-bar bg-success" style="width: 100%"></div>
                        </div>
                        <small class="text-muted"><?php echo $yearSummary['income_count'] ?? 0; ?> transactions</small>
                    </div>

                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <span class="text-muted">Total Expenses</span>
                            <span class="fs-5 fw-semibold text-danger">
                                <?php echo formatCurrency($yearSummary['total_expenses'] ?? 0); ?>
                            </span>
                        </div>
                        <div class="progress" style="height: 10px;">
                            <?php
                            $expenseRatio = ($yearSummary['total_income'] ?? 0) > 0 
                                ? (($yearSummary['total_expenses'] ?? 0) / ($yearSummary['total_income'] ?? 1) * 100)
                                : 0;
                            ?>
                            <div class="progress-bar bg-danger" style="width: <?php echo min($expenseRatio, 100); ?>%"></div>
                        </div>
                        <small class="text-muted"><?php echo $yearSummary['expense_count'] ?? 0; ?> transactions</small>
                    </div>

                    <hr>

                    <div class="text-center p-3 rounded" style="background: <?php echo ($yearSummary['net_profit'] ?? 0) >= 0 ? '#d1fae5' : '#fee2e2'; ?>">
                        <small class="text-muted d-block mb-1">Net Position</small>
                        <h4 class="mb-0 <?php echo ($yearSummary['net_profit'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?>">
                            <?php echo formatCurrency(abs($yearSummary['net_profit'] ?? 0)); ?>
                        </h4>
                        <small class="<?php echo ($yearSummary['net_profit'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?>">
                            <?php echo ($yearSummary['net_profit'] ?? 0) >= 0 ? '✓ Profit' : '✗ Loss'; ?>
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Upcoming Harvests -->
    <?php if (!empty($upcomingHarvests)): ?>
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h6 class="mb-0">
                        <i class="bi bi-calendar-event text-warning"></i> Upcoming Harvests (Next 30 Days)
                    </h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Enterprise</th>
                                    <th>Type</th>
                                    <th>Size</th>
                                    <th>Expected Date</th>
                                    <th>Days Remaining</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($upcomingHarvests as $harvest): ?>
                                    <?php
                                    $daysRemaining = (strtotime($harvest['expected_harvest_date']) - time()) / 86400;
                                    $urgency = $daysRemaining <= 7 ? 'danger' : ($daysRemaining <= 14 ? 'warning' : 'success');
                                    ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($harvest['enterprise_name'] ?: 'Unnamed'); ?></strong>
                                            <br><small class="text-muted"><?php echo htmlspecialchars($harvest['farm_name']); ?></small>
                                        </td>
                                        <td>
                                            <span class="badge bg-primary">
                                                <?php echo ucwords(str_replace('_', ' ', $harvest['enterprise_type'])); ?>
                                            </span>
                                        </td>
                                        <td><?php echo number_format($harvest['size_acres'], 1); ?> acres</td>
                                        <td><?php echo formatDate($harvest['expected_harvest_date']); ?></td>
                                        <td>
                                            <span class="badge bg-<?php echo $urgency; ?>">
                                                <?php echo ceil($daysRemaining); ?> days
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php echo getStatusBadgeClass($harvest['status']); ?>">
                                                <?php echo ucfirst($harvest['status']); ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Quick Actions -->
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h6 class="mb-3">
                        <i class="bi bi-lightning"></i> Quick Actions
                    </h6>
                    <div class="row g-3">
                        <div class="col-md-3 col-sm-6">
                            <a href="<?php echo APP_URL; ?>/farm/add-enterprise.php" class="btn btn-outline-success w-100">
                                <i class="bi bi-plus-circle"></i> Add Enterprise
                            </a>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <a href="<?php echo APP_URL; ?>/farm/add-transaction.php" class="btn btn-outline-primary w-100">
                                <i class="bi bi-cash-stack"></i> Record Transaction
                            </a>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <a href="<?php echo APP_URL; ?>/marketplace/add-product.php" class="btn btn-outline-warning w-100">
                                <i class="bi bi-box-seam"></i> List Product
                            </a>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <a href="<?php echo APP_URL; ?>/farm/reports.php" class="btn btn-outline-info w-100">
                                <i class="bi bi-graph-up"></i> View Reports
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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