<?php
/**
 * ============================================================================
 * farm/profile.php - Farm Profile & Settings
 * ============================================================================
 */
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 Profile';
$userId = getUserId();

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

// Get user's farm
$farmClass = new \App\Farm($db);
$farms = $farmClass->getUserFarms($userId);

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

$farm = $farms[0];

// Handle form submission
if (isPost()) {
    $data = [
        'farm_name' => $_POST['farm_name'],
        'total_acres' => $_POST['total_acres'],
        'location_lat' => $_POST['location_lat'] ?? null,
        'location_lng' => $_POST['location_lng'] ?? null,
        'soil_type' => $_POST['soil_type'],
        'water_source' => $_POST['water_source']
    ];
    
    $result = $farmClass->update($farm['id'], $userId, $data);
    
    if ($result['success']) {
        setFlashMessage($result['message'], 'success');
        redirect('/farm/profile.php');
    } else {
        setFlashMessage($result['message'], 'error');
    }
}

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

<div class="container-fluid py-4">
    <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-gear text-primary"></i> Farm Profile & Settings
                    </h2>
                    <p class="text-muted mb-0">Manage your farm information and configuration</p>
                </div>
                <a href="<?php echo APP_URL; ?>/farm/" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left"></i> Back to Dashboard
                </a>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Farm Information Form -->
        <div class="col-lg-8 mb-4">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0">
                        <i class="bi bi-info-circle"></i> Farm Information
                    </h5>
                </div>
                <div class="card-body p-4">
                    <form method="POST">
                        <!-- Farm Name -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Farm Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control form-control-lg" name="farm_name" 
                                   value="<?php echo htmlspecialchars($farm['farm_name']); ?>" required>
                            <small class="text-muted">Give your farm a unique name</small>
                        </div>

                        <!-- Total Land Size -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Total Land Size (Acres) <span class="text-danger">*</span></label>
                            <input type="number" class="form-control form-control-lg" name="total_acres" 
                                   value="<?php echo $farm['total_acres']; ?>" 
                                   step="0.01" min="0" required>
                            <small class="text-muted">
                                Currently used: <?php echo number_format($farm['used_acres'] ?? 0, 2); ?> acres 
                                | Available: <?php echo number_format($farm['total_acres'] - ($farm['used_acres'] ?? 0), 2); ?> acres
                            </small>
                        </div>

                        <!-- Soil Type -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Primary Soil Type</label>
                            <select class="form-select" name="soil_type">
                                <option value="">Select soil type...</option>
                                <option value="Clay" <?php echo $farm['soil_type'] == 'Clay' ? 'selected' : ''; ?>>Clay</option>
                                <option value="Sandy" <?php echo $farm['soil_type'] == 'Sandy' ? 'selected' : ''; ?>>Sandy</option>
                                <option value="Loam" <?php echo $farm['soil_type'] == 'Loam' ? 'selected' : ''; ?>>Loam</option>
                                <option value="Silt" <?php echo $farm['soil_type'] == 'Silt' ? 'selected' : ''; ?>>Silt</option>
                                <option value="Peat" <?php echo $farm['soil_type'] == 'Peat' ? 'selected' : ''; ?>>Peat</option>
                                <option value="Chalky" <?php echo $farm['soil_type'] == 'Chalky' ? 'selected' : ''; ?>>Chalky</option>
                                <option value="Mixed" <?php echo $farm['soil_type'] == 'Mixed' ? 'selected' : ''; ?>>Mixed</option>
                            </select>
                            <small class="text-muted">Understanding your soil helps with crop selection</small>
                        </div>

                        <!-- Water Source -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Primary Water Source</label>
                            <select class="form-select" name="water_source">
                                <option value="">Select water source...</option>
                                <option value="Borehole" <?php echo $farm['water_source'] == 'Borehole' ? 'selected' : ''; ?>>Borehole</option>
                                <option value="Well" <?php echo $farm['water_source'] == 'Well' ? 'selected' : ''; ?>>Well</option>
                                <option value="River/Stream" <?php echo $farm['water_source'] == 'River/Stream' ? 'selected' : ''; ?>>River/Stream</option>
                                <option value="Dam" <?php echo $farm['water_source'] == 'Dam' ? 'selected' : ''; ?>>Dam</option>
                                <option value="Rainwater Harvest" <?php echo $farm['water_source'] == 'Rainwater Harvest' ? 'selected' : ''; ?>>Rainwater Harvesting</option>
                                <option value="Piped Water" <?php echo $farm['water_source'] == 'Piped Water' ? 'selected' : ''; ?>>Piped Water</option>
                                <option value="Multiple Sources" <?php echo $farm['water_source'] == 'Multiple Sources' ? 'selected' : ''; ?>>Multiple Sources</option>
                            </select>
                        </div>

                        <!-- Location Coordinates -->
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Latitude (Optional)</label>
                                <input type="text" class="form-control" name="location_lat" 
                                       value="<?php echo $farm['location_lat'] ?? ''; ?>" 
                                       placeholder="e.g., 0.3476">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Longitude (Optional)</label>
                                <input type="text" class="form-control" name="location_lng" 
                                       value="<?php echo $farm['location_lng'] ?? ''; ?>" 
                                       placeholder="e.g., 33.2026">
                            </div>
                            <div class="col-12 mt-2">
                                <small class="text-muted">
                                    <i class="bi bi-info-circle"></i> Location helps with weather forecasts and market information
                                    <button type="button" class="btn btn-sm btn-outline-primary ms-2" onclick="getLocation()">
                                        <i class="bi bi-geo-alt"></i> Get My Location
                                    </button>
                                </small>
                            </div>
                        </div>

                        <!-- Save Button -->
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="bi bi-check-circle"></i> Save Changes
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Farm Statistics -->
        <div class="col-lg-4 mb-4">
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-header bg-white border-bottom">
                    <h6 class="mb-0">
                        <i class="bi bi-bar-chart"></i> Farm Statistics
                    </h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-1">
                            <small class="text-muted">Land Utilization</small>
                            <small class="fw-semibold">
                                <?php 
                                $utilization = $farm['total_acres'] > 0 
                                    ? (($farm['used_acres'] ?? 0) / $farm['total_acres'] * 100) 
                                    : 0;
                                echo number_format($utilization, 1); 
                                ?>%
                            </small>
                        </div>
                        <div class="progress" style="height: 8px;">
                            <div class="progress-bar bg-success" role="progressbar" 
                                 style="width: <?php echo $utilization; ?>%"></div>
                        </div>
                    </div>

                    <hr>

                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted">Total Enterprises</span>
                        <span class="badge bg-primary"><?php echo $farm['enterprise_count'] ?? 0; ?></span>
                    </div>

                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted">Total Land</span>
                        <span class="fw-semibold"><?php echo number_format($farm['total_acres'], 2); ?> acres</span>
                    </div>

                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted">Used Land</span>
                        <span class="fw-semibold"><?php echo number_format($farm['used_acres'] ?? 0, 2); ?> acres</span>
                    </div>

                    <div class="d-flex justify-content-between align-items-center">
                        <span class="text-muted">Available Land</span>
                        <span class="fw-semibold text-success">
                            <?php echo number_format($farm['total_acres'] - ($farm['used_acres'] ?? 0), 2); ?> acres
                        </span>
                    </div>
                </div>
            </div>

            <!-- Quick Info Card -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h6 class="mb-0">
                        <i class="bi bi-lightbulb"></i> Farm Details
                    </h6>
                </div>
                <div class="card-body">
                    <div class="mb-2">
                        <small class="text-muted d-block">Soil Type</small>
                        <span class="fw-semibold"><?php echo $farm['soil_type'] ?: 'Not specified'; ?></span>
                    </div>
                    <div class="mb-2">
                        <small class="text-muted d-block">Water Source</small>
                        <span class="fw-semibold"><?php echo $farm['water_source'] ?: 'Not specified'; ?></span>
                    </div>
                    <div class="mb-2">
                        <small class="text-muted d-block">Farm Created</small>
                        <span class="fw-semibold"><?php echo formatDate($farm['created_at']); ?></span>
                    </div>
                    <?php if ($farm['location_lat'] && $farm['location_lng']): ?>
                        <div>
                            <small class="text-muted d-block">Location</small>
                            <a href="https://www.google.com/maps?q=<?php echo $farm['location_lat']; ?>,<?php echo $farm['location_lng']; ?>" 
                               target="_blank" class="text-primary text-decoration-none">
                                <i class="bi bi-geo-alt"></i> View on Map
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function getLocation() {
    if (navigator.geolocation) {
        showToast('Getting your location...', 'info');
        
        navigator.geolocation.getCurrentPosition(
            function(position) {
                $('input[name="location_lat"]').val(position.coords.latitude.toFixed(6));
                $('input[name="location_lng"]').val(position.coords.longitude.toFixed(6));
                showToast('Location captured successfully!', 'success');
            },
            function(error) {
                let message = 'Unable to get location';
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        message = 'Location permission denied. Please enable location access.';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        message = 'Location information unavailable.';
                        break;
                    case error.TIMEOUT:
                        message = 'Location request timed out.';
                        break;
                }
                showToast(message, 'error');
            }
        );
    } else {
        showToast('Geolocation is not supported by your browser', 'error');
    }
}
</script>

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