<?php
/**
 * ============================================================================
 * api/extension.php
 * Extension Worker API Endpoints
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

// Check authentication
if (!isLoggedIn()) {
    jsonError('Authentication required', 401);
}

// Check authorization
if (!in_array(getUserType(), ['extension_officer', 'admin'])) {
    jsonError('Access denied. Extension workers only.', 403);
}

$userId = getUserId();
$database = \App\Database::getInstance();
$db = $database->getConnection();

$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    switch($action) {
        case 'schedule_service':
            scheduleService($db, $userId);
            break;
            
        case 'update_service':
            updateService($db, $userId);
            break;
            
        case 'cancel_service':
            cancelService($db, $userId);
            break;
            
        case 'complete_service':
            completeService($db, $userId);
            break;
            
        case 'mark_attendance':
            markAttendance($db, $userId);
            break;
            
        case 'get_service_details':
            getServiceDetails($db, $userId);
            break;
            
        case 'get_participants':
            getParticipants($db, $userId);
            break;
            
        case 'send_reminder':
            sendServiceReminder($db, $userId);
            break;
            
        default:
            jsonError('Invalid action', 400);
    }
} catch (Exception $e) {
    logError('Extension API Error: ' . $e->getMessage());
    jsonError('An error occurred: ' . $e->getMessage(), 500);
}

/**
 * Schedule a new service
 */
function scheduleService($db, $userId) {
    // Validate required fields
    $required = ['service_type', 'title', 'location', 'scheduled_date'];
    foreach ($required as $field) {
        if (empty($_POST[$field])) {
            jsonError(ucfirst(str_replace('_', ' ', $field)) . ' is required');
        }
    }
    
    // Validate date is not in the past
    if (strtotime($_POST['scheduled_date']) < strtotime('today')) {
        jsonError('Service date cannot be in the past');
    }
    
    try {
        $db->beginTransaction();
        
        // Insert service
        $sql = "INSERT INTO extension_services 
                (officer_id, service_type, title, description, location, 
                 scheduled_date, scheduled_time, duration_hours, max_participants, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'scheduled')";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $userId,
            sanitize($_POST['service_type']),
            sanitize($_POST['title']),
            sanitize($_POST['description'] ?? ''),
            sanitize($_POST['location']),
            $_POST['scheduled_date'],
            !empty($_POST['scheduled_time']) ? $_POST['scheduled_time'] : null,
            !empty($_POST['duration_hours']) ? (int)$_POST['duration_hours'] : 2,
            !empty($_POST['max_participants']) ? (int)$_POST['max_participants'] : null
        ]);
        
        $serviceId = $db->lastInsertId();
        
        // Log activity
        logActivity($userId, 'schedule_service', "Scheduled service: " . $_POST['title']);
        
        // Get officer's area farmers for notification
        $sql = "SELECT eo.*, u.district_id, u.subcounty_id, u.parish_id, u.village_id
                FROM extension_officer_profiles eo
                JOIN users u ON eo.user_id = u.id
                WHERE eo.user_id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$userId]);
        $profile = $stmt->fetch();
        
        // Determine notification scope based on officer level
        $whereClause = "user_type = 'farmer' AND is_active = 1";
        $params = [];
        
        if (!empty($profile['village_id'])) {
            $whereClause .= " AND village_id = ?";
            $params[] = $profile['village_id'];
        } elseif (!empty($profile['parish_id'])) {
            $whereClause .= " AND parish_id = ?";
            $params[] = $profile['parish_id'];
        } elseif (!empty($profile['subcounty_id'])) {
            $whereClause .= " AND subcounty_id = ?";
            $params[] = $profile['subcounty_id'];
        } elseif (!empty($profile['district_id'])) {
            $whereClause .= " AND district_id = ?";
            $params[] = $profile['district_id'];
        }
        
        // Send notification to farmers in area
        $sql = "INSERT INTO notifications (user_id, title, message, type, icon, link)
                SELECT id, ?, ?, 'info', 'calendar-event', ?
                FROM users
                WHERE $whereClause
                LIMIT 100"; // Limit to prevent overwhelming system
        
        $stmt = $db->prepare($sql);
        $notifParams = array_merge([
            'New Extension Service Available',
            sanitize($_POST['title']) . ' on ' . date('M j, Y', strtotime($_POST['scheduled_date'])),
            '/extension/service-details.php?id=' . $serviceId
        ], $params);
        $stmt->execute($notifParams);
        
        $db->commit();
        
        jsonSuccess('Service scheduled successfully', [
            'service_id' => $serviceId
        ]);
        
    } catch (Exception $e) {
        $db->rollback();
        logError('Schedule service error: ' . $e->getMessage());
        jsonError('Failed to schedule service');
    }
}

/**
 * Update existing service
 */
function updateService($db, $userId) {
    if (empty($_POST['service_id'])) {
        jsonError('Service ID is required');
    }
    
    $serviceId = (int)$_POST['service_id'];
    
    // Verify ownership
    $sql = "SELECT id FROM extension_services WHERE id = ? AND officer_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$serviceId, $userId]);
    if (!$stmt->fetch()) {
        jsonError('Service not found or access denied');
    }
    
    try {
        $updates = [];
        $params = [];
        
        if (!empty($_POST['title'])) {
            $updates[] = "title = ?";
            $params[] = sanitize($_POST['title']);
        }
        if (isset($_POST['description'])) {
            $updates[] = "description = ?";
            $params[] = sanitize($_POST['description']);
        }
        if (!empty($_POST['location'])) {
            $updates[] = "location = ?";
            $params[] = sanitize($_POST['location']);
        }
        if (!empty($_POST['scheduled_date'])) {
            $updates[] = "scheduled_date = ?";
            $params[] = $_POST['scheduled_date'];
        }
        if (isset($_POST['scheduled_time'])) {
            $updates[] = "scheduled_time = ?";
            $params[] = !empty($_POST['scheduled_time']) ? $_POST['scheduled_time'] : null;
        }
        if (isset($_POST['duration_hours'])) {
            $updates[] = "duration_hours = ?";
            $params[] = (int)$_POST['duration_hours'];
        }
        if (isset($_POST['max_participants'])) {
            $updates[] = "max_participants = ?";
            $params[] = !empty($_POST['max_participants']) ? (int)$_POST['max_participants'] : null;
        }
        
        if (empty($updates)) {
            jsonError('No fields to update');
        }
        
        $params[] = $serviceId;
        
        $sql = "UPDATE extension_services SET " . implode(', ', $updates) . " WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        
        logActivity($userId, 'update_service', "Updated service ID: $serviceId");
        
        jsonSuccess('Service updated successfully');
        
    } catch (Exception $e) {
        logError('Update service error: ' . $e->getMessage());
        jsonError('Failed to update service');
    }
}

/**
 * Cancel service
 */
function cancelService($db, $userId) {
    if (empty($_POST['service_id'])) {
        jsonError('Service ID is required');
    }
    
    $serviceId = (int)$_POST['service_id'];
    
    // Verify ownership
    $sql = "SELECT id, title FROM extension_services WHERE id = ? AND officer_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$serviceId, $userId]);
    $service = $stmt->fetch();
    
    if (!$service) {
        jsonError('Service not found or access denied');
    }
    
    try {
        $db->beginTransaction();
        
        // Update service status
        $sql = "UPDATE extension_services SET status = 'cancelled' WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$serviceId]);
        
        // Notify registered participants
        $sql = "INSERT INTO notifications (user_id, title, message, type, icon, link)
                SELECT user_id, 'Service Cancelled', 
                       CONCAT('The service \"', ?, '\" has been cancelled.'),
                       'warning', 'calendar-x', '/extension/my-services.php'
                FROM service_participants
                WHERE service_id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$service['title'], $serviceId]);
        
        logActivity($userId, 'cancel_service', "Cancelled service ID: $serviceId");
        
        $db->commit();
        
        jsonSuccess('Service cancelled successfully');
        
    } catch (Exception $e) {
        $db->rollback();
        logError('Cancel service error: ' . $e->getMessage());
        jsonError('Failed to cancel service');
    }
}

/**
 * Mark service as completed
 */
function completeService($db, $userId) {
    if (empty($_POST['service_id'])) {
        jsonError('Service ID is required');
    }
    
    $serviceId = (int)$_POST['service_id'];
    
    // Verify ownership
    $sql = "SELECT id FROM extension_services WHERE id = ? AND officer_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$serviceId, $userId]);
    if (!$stmt->fetch()) {
        jsonError('Service not found or access denied');
    }
    
    try {
        $sql = "UPDATE extension_services SET status = 'completed' WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$serviceId]);
        
        logActivity($userId, 'complete_service', "Completed service ID: $serviceId");
        
        jsonSuccess('Service marked as completed');
        
    } catch (Exception $e) {
        logError('Complete service error: ' . $e->getMessage());
        jsonError('Failed to complete service');
    }
}

/**
 * Mark attendance for participants
 */
function markAttendance($db, $userId) {
    if (empty($_POST['service_id']) || empty($_POST['participant_id'])) {
        jsonError('Service ID and Participant ID are required');
    }
    
    $serviceId = (int)$_POST['service_id'];
    $participantId = (int)$_POST['participant_id'];
    $status = sanitize($_POST['status'] ?? 'attended');
    
    // Verify ownership
    $sql = "SELECT id FROM extension_services WHERE id = ? AND officer_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$serviceId, $userId]);
    if (!$stmt->fetch()) {
        jsonError('Service not found or access denied');
    }
    
    try {
        $sql = "UPDATE service_participants 
                SET attendance_status = ? 
                WHERE service_id = ? AND id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$status, $serviceId, $participantId]);
        
        jsonSuccess('Attendance marked successfully');
        
    } catch (Exception $e) {
        logError('Mark attendance error: ' . $e->getMessage());
        jsonError('Failed to mark attendance');
    }
}

/**
 * Get service details
 */
function getServiceDetails($db, $userId) {
    if (empty($_GET['service_id'])) {
        jsonError('Service ID is required');
    }
    
    $serviceId = (int)$_GET['service_id'];
    
    try {
        $sql = "SELECT es.*, u.full_name as officer_name, u.phone_number as officer_phone,
                COUNT(sp.id) as total_participants,
                SUM(CASE WHEN sp.attendance_status = 'attended' THEN 1 ELSE 0 END) as attended_count
                FROM extension_services es
                JOIN users u ON es.officer_id = u.id
                LEFT JOIN service_participants sp ON es.id = sp.service_id
                WHERE es.id = ?
                GROUP BY es.id";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$serviceId]);
        $service = $stmt->fetch();
        
        if (!$service) {
            jsonError('Service not found');
        }
        
        jsonSuccess('Service details retrieved', [
            'service' => $service
        ]);
        
    } catch (Exception $e) {
        logError('Get service details error: ' . $e->getMessage());
        jsonError('Failed to get service details');
    }
}

/**
 * Get service participants
 */
function getParticipants($db, $userId) {
    if (empty($_GET['service_id'])) {
        jsonError('Service ID is required');
    }
    
    $serviceId = (int)$_GET['service_id'];
    
    // Verify ownership
    $sql = "SELECT id FROM extension_services WHERE id = ? AND officer_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$serviceId, $userId]);
    if (!$stmt->fetch()) {
        jsonError('Service not found or access denied');
    }
    
    try {
        $sql = "SELECT sp.*, u.full_name, u.phone_number, u.email,
                d.district_name, s.subcounty_name, p.parish_name, v.village_name
                FROM service_participants sp
                JOIN users u ON sp.user_id = u.id
                LEFT JOIN districts d ON u.district_id = d.id
                LEFT JOIN subcounties s ON u.subcounty_id = s.id
                LEFT JOIN parishes p ON u.parish_id = p.id
                LEFT JOIN villages v ON u.village_id = v.id
                WHERE sp.service_id = ?
                ORDER BY sp.registered_at DESC";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$serviceId]);
        $participants = $stmt->fetchAll();
        
        jsonSuccess('Participants retrieved', [
            'participants' => $participants
        ]);
        
    } catch (Exception $e) {
        logError('Get participants error: ' . $e->getMessage());
        jsonError('Failed to get participants');
    }
}

/**
 * Send reminder to participants
 */
function sendServiceReminder($db, $userId) {
    if (empty($_POST['service_id'])) {
        jsonError('Service ID is required');
    }
    
    $serviceId = (int)$_POST['service_id'];
    
    // Verify ownership
    $sql = "SELECT es.*, u.full_name as officer_name
            FROM extension_services es
            JOIN users u ON es.officer_id = u.id
            WHERE es.id = ? AND es.officer_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$serviceId, $userId]);
    $service = $stmt->fetch();
    
    if (!$service) {
        jsonError('Service not found or access denied');
    }
    
    try {
        // Send notification to registered participants
        $sql = "INSERT INTO notifications (user_id, title, message, type, icon, link)
                SELECT sp.user_id, 'Service Reminder', 
                       CONCAT('Reminder: \"', ?, '\" on ', ?, ' at ', ?),
                       'info', 'bell', ?
                FROM service_participants sp
                WHERE sp.service_id = ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $service['title'],
            date('M j, Y', strtotime($service['scheduled_date'])),
            $service['scheduled_time'] ? date('g:i A', strtotime($service['scheduled_time'])) : 'TBA',
            '/extension/service-details.php?id=' . $serviceId,
            $serviceId
        ]);
        
        $sentCount = $stmt->rowCount();
        
        logActivity($userId, 'send_reminder', "Sent reminder for service ID: $serviceId to $sentCount participants");
        
        jsonSuccess("Reminder sent to $sentCount participants");
        
    } catch (Exception $e) {
        logError('Send reminder error: ' . $e->getMessage());
        jsonError('Failed to send reminder');
    }
}
?>