<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$buyerSystem = new BuyerSystem($database, $currentUserId);

if (!$buyerSystem->hasPermission('contract_farming')) {
    $_SESSION['flash_message'] = 'Contract farming is only available for Processors and Exporters';
    $_SESSION['flash_type'] = 'warning';
    header('Location: ' . APP_URL . '/buyer/dashboard.php');
    exit();
}

// Get contracts
$sql = "SELECT fc.*, u.full_name as farmer_name, u.phone_number as farmer_phone,
               d.district_name as farmer_district,
               (SELECT COUNT(*) FROM contract_deliveries WHERE contract_id = fc.id) as delivery_count,
               (SELECT SUM(quantity_delivered) FROM contract_deliveries WHERE contract_id = fc.id) as total_delivered
        FROM farming_contracts fc
        INNER JOIN users u ON fc.farmer_id = u.id
        LEFT JOIN districts d ON u.district_id = d.id
        WHERE fc.buyer_id = ?
        ORDER BY fc.created_at DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$contracts = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Farming Contracts';
$breadcrumbs = [['title' => 'Contracts', 'url' => '']];

require_once __DIR__ . '/includes/base.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<div class="row mb-4">
    <div class="col">
        <a href="<?php echo APP_URL; ?>/buyer/create-contract.php" class="btn btn-primary">
            <i class="bi bi-plus-circle me-2"></i>New Contract
        </a>
    </div>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Total Contracts</h6>
                <h3 class="mb-0"><?php echo count($contracts); ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Active</h6>
                <h3 class="mb-0 text-success">
                    <?php echo count(array_filter($contracts, fn($c) => $c['status'] === 'active')); ?>
                </h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Pending</h6>
                <h3 class="mb-0 text-warning">
                    <?php echo count(array_filter($contracts, fn($c) => $c['status'] === 'pending_approval')); ?>
                </h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Total Value</h6>
                <h3 class="mb-0 text-primary">
                    <?php echo formatCurrency(array_sum(array_column($contracts, 'total_contract_value'))); ?>
                </h3>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0"><i class="bi bi-file-earmark-text me-2"></i>Contracts (<?php echo count($contracts); ?>)</h5>
    </div>
    <div class="card-body">
        <?php if (empty($contracts)): ?>
            <div class="text-center py-5">
                <i class="bi bi-file-earmark-text" style="font-size: 4rem; color: #d1d5db;"></i>
                <h5 class="mt-3 text-muted">No contracts yet</h5>
                <p class="text-muted">Create your first farming contract</p>
                <a href="<?php echo APP_URL; ?>/buyer/create-contract.php" class="btn btn-primary mt-2">
                    <i class="bi bi-plus-circle me-2"></i>Create Contract
                </a>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover" id="contractsTable">
                    <thead class="table-light">
                        <tr>
                            <th>Farmer</th>
                            <th>Product</th>
                            <th>Quantity</th>
                            <th>Price/Unit</th>
                            <th>Total Value</th>
                            <th>Duration</th>
                            <th>Status</th>
                            <th>Progress</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($contracts as $contract): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($contract['farmer_name']); ?></strong><br>
                                <small class="text-muted"><?php echo htmlspecialchars($contract['farmer_district'] ?? 'N/A'); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($contract['product_type']); ?></td>
                            <td><?php echo number_format($contract['quantity_contracted'], 2); ?> <?php echo htmlspecialchars($contract['unit']); ?></td>
                            <td><?php echo formatCurrency($contract['price_per_unit']); ?></td>
                            <td><strong class="text-success"><?php echo formatCurrency($contract['total_contract_value']); ?></strong></td>
                            <td>
                                <small>
                                    <?php echo date('M j', strtotime($contract['start_date'])); ?> - 
                                    <?php echo date('M j, Y', strtotime($contract['end_date'])); ?>
                                </small>
                            </td>
                            <td>
                                <?php
                                $statusBadges = [
                                    'draft' => '<span class="badge bg-secondary">Draft</span>',
                                    'pending_approval' => '<span class="badge bg-warning">Pending</span>',
                                    'active' => '<span class="badge bg-success">Active</span>',
                                    'completed' => '<span class="badge bg-info">Completed</span>',
                                    'terminated' => '<span class="badge bg-danger">Terminated</span>'
                                ];
                                echo $statusBadges[$contract['status']] ?? $statusBadges['draft'];
                                ?>
                            </td>
                            <td>
                                <?php 
                                $progress = $contract['quantity_contracted'] > 0 
                                    ? ($contract['total_delivered'] / $contract['quantity_contracted']) * 100 
                                    : 0;
                                ?>
                                <div class="progress" style="height: 20px;">
                                    <div class="progress-bar" role="progressbar" 
                                         style="width: <?php echo min(100, $progress); ?>%">
                                        <?php echo number_format($progress, 0); ?>%
                                    </div>
                                </div>
                            </td>
                            <td>
                                <a href="<?php echo APP_URL; ?>/buyer/contract-details.php?id=<?php echo $contract['id']; ?>" 
                                   class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-eye"></i> View
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#contractsTable').DataTable({
        order: [[6, 'desc']],
        pageLength: 25
    });
});
</script>

<?php renderBuyerFooter(); ?>