<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

try {

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

    // Get and verify token
    $token = Helpers::getBearerToken();
    $userData = Helpers::verifyJWT($token);

    if (!$userData) {
        Helpers::sendResponse(false, 'Unauthorized access.', null, 403);
    }

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

    // Verify admin access
    $query = "SELECT ur.role_level, ur.can_manage_services 
              FROM users u 
              JOIN user_roles ur ON u.role_id = ur.id 
              WHERE u.id = :user_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $userData['user_id']);
    $stmt->execute();
    $userRole = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$userRole || !$userRole['can_manage_services']) {
        Helpers::sendResponse(false, 'Unauthorized. Service management access required.', null, 403);
    }

    $method = $_SERVER['REQUEST_METHOD'];

    // GET: Retrieve services
    if ($method === 'GET') {
        $includeInactive = isset($_GET['include_inactive']) ? filter_var($_GET['include_inactive'], FILTER_VALIDATE_BOOLEAN) : false;
        $serviceTypeFilter = isset($_GET['service_type']) ? intval($_GET['service_type']) : 0;
        $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
        $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

        $whereConditions = [];
        $params = [];

        if (!$includeInactive) {
            $whereConditions[] = "s.is_active = TRUE";
        }

        if ($serviceTypeFilter > 0) {
            $whereConditions[] = "s.service_type_id = :service_type";
            $params[':service_type'] = $serviceTypeFilter;
        }

        $whereClause = count($whereConditions) > 0 ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

        $query = "SELECT s.id, s.name, s.description, s.location, 
                         s.latitude, s.longitude, s.geofence_radius,
                         s.start_time, s.end_time, s.is_recurring, 
                         s.recurrence_pattern, s.recurrence_interval, s.recurrence_end_date,
                         s.is_active, s.service_type_id, s.created_at, s.updated_at,
                         st.name as service_type, st.allows_delegates,
                         COUNT(DISTINCT a.user_id) as total_attendees,
                         COUNT(DISTINCT sr.id) as rewards_count
                  FROM services s
                  LEFT JOIN service_types st ON s.service_type_id = st.id
                  LEFT JOIN attendance a ON s.id = a.service_id
                  LEFT JOIN service_rewards sr ON s.id = sr.service_id AND sr.is_active = TRUE
                  $whereClause
                  GROUP BY s.id
                  ORDER BY s.start_time DESC
                  LIMIT :limit OFFSET :offset";

        $stmt = $db->prepare($query);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();

        $services = $stmt->fetchAll(PDO::FETCH_ASSOC);

        Helpers::sendResponse(true, 'Services retrieved successfully', [
            'services' => $services,
            'count' => count($services)
        ]);
    }

    // POST: Create new service
    elseif ($method === 'POST') {
        $data = json_decode(file_get_contents("php://input"));

        // Validate required fields
        if (empty($data->name) || empty($data->start_time) || empty($data->end_time)) {
            Helpers::sendResponse(false, 'Service name, start time, and end time are required', null, 400);
        }

        // Validate service type if provided
        if (isset($data->service_type_id)) {
            $query = "SELECT id FROM service_types WHERE id = :type_id";
            $stmt = $db->prepare($query);
            $stmt->bindParam(':type_id', $data->service_type_id);
            $stmt->execute();

            if ($stmt->rowCount() === 0) {
                Helpers::sendResponse(false, 'Invalid service type', null, 400);
            }
        }

        // Insert new service
        $query = "INSERT INTO services 
                  (name, description, service_type_id, location, latitude, longitude, 
                   geofence_radius, start_time, end_time, is_recurring, recurrence_pattern,
                   recurrence_interval, recurrence_end_date, is_active, created_at) 
                  VALUES 
                  (:name, :description, :service_type_id, :location, :latitude, :longitude,
                   :geofence_radius, :start_time, :end_time, :is_recurring, :recurrence_pattern,
                   :recurrence_interval, :recurrence_end_date, TRUE, NOW())";

        $stmt = $db->prepare($query);
        $stmt->bindParam(':name', $data->name);
        $description = $data->description ?? '';
        $stmt->bindParam(':description', $description);
        $serviceTypeId = $data->service_type_id ?? null;
        $stmt->bindParam(':service_type_id', $serviceTypeId);
        $location = $data->location ?? '';
        $stmt->bindParam(':location', $location);
        $latitude = $data->latitude ?? null;
        $stmt->bindParam(':latitude', $latitude);
        $longitude = $data->longitude ?? null;
        $stmt->bindParam(':longitude', $longitude);
        $geofenceRadius = $data->geofence_radius ?? 100;
        $stmt->bindParam(':geofence_radius', $geofenceRadius);
        $stmt->bindParam(':start_time', $data->start_time);
        $stmt->bindParam(':end_time', $data->end_time);
        $isRecurring = isset($data->is_recurring) ? (bool)$data->is_recurring : false;
        $stmt->bindParam(':is_recurring', $isRecurring, PDO::PARAM_BOOL);
        $recurrencePattern = $data->recurrence_pattern ?? null;
        $stmt->bindParam(':recurrence_pattern', $recurrencePattern);
        $recurrenceInterval = $data->recurrence_interval ?? 1;
        $stmt->bindParam(':recurrence_interval', $recurrenceInterval);
        $recurrenceEndDate = $data->recurrence_end_date ?? null;
        $stmt->bindParam(':recurrence_end_date', $recurrenceEndDate);

        if ($stmt->execute()) {
            $newServiceId = $db->lastInsertId();

            // Log admin activity
            $logQuery = "INSERT INTO admin_logs 
                        (admin_id, action, action_type, target_type, target_id, details, ip_address, created_at) 
                        VALUES 
                        (:admin_id, 'create_service', 'create', 'service', :service_id, :details, :ip, NOW())";

            $details = json_encode([
                'name' => $data->name,
                'start_time' => $data->start_time,
                'end_time' => $data->end_time
            ]);
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

            $stmt = $db->prepare($logQuery);
            $stmt->bindParam(':admin_id', $userData['user_id']);
            $stmt->bindParam(':service_id', $newServiceId);
            $stmt->bindParam(':details', $details);
            $stmt->bindParam(':ip', $ip);
            $stmt->execute();

            Helpers::sendResponse(true, 'Service created successfully', [
                'service_id' => $newServiceId
            ], 201);
        } else {
            Helpers::sendResponse(false, 'Failed to create service', null, 500);
        }
    }

    // PUT: Update service
    elseif ($method === 'PUT') {
        $serviceId = isset($_GET['id']) ? intval($_GET['id']) : null;

        if (!$serviceId) {
            Helpers::sendResponse(false, 'Service ID is required', null, 400);
        }

        $data = json_decode(file_get_contents("php://input"));

        // Check if service exists
        $query = "SELECT id FROM services WHERE id = :service_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':service_id', $serviceId);
        $stmt->execute();

        if ($stmt->rowCount() === 0) {
            Helpers::sendResponse(false, 'Service not found', null, 404);
        }

        // Build dynamic update query
        $updateFields = [];
        $params = [':service_id' => $serviceId];

        if (isset($data->name)) {
            $updateFields[] = "name = :name";
            $params[':name'] = $data->name;
        }

        if (isset($data->description)) {
            $updateFields[] = "description = :description";
            $params[':description'] = $data->description;
        }

        if (isset($data->service_type_id)) {
            // Validate service type
            $checkQuery = "SELECT id FROM service_types WHERE id = :type_id";
            $checkStmt = $db->prepare($checkQuery);
            $checkStmt->bindParam(':type_id', $data->service_type_id);
            $checkStmt->execute();

            if ($checkStmt->rowCount() === 0) {
                Helpers::sendResponse(false, 'Invalid service type', null, 400);
            }

            $updateFields[] = "service_type_id = :service_type_id";
            $params[':service_type_id'] = $data->service_type_id;
        }

        if (isset($data->location)) {
            $updateFields[] = "location = :location";
            $params[':location'] = $data->location;
        }

        if (isset($data->latitude)) {
            $updateFields[] = "latitude = :latitude";
            $params[':latitude'] = $data->latitude;
        }

        if (isset($data->longitude)) {
            $updateFields[] = "longitude = :longitude";
            $params[':longitude'] = $data->longitude;
        }

        if (isset($data->geofence_radius)) {
            $updateFields[] = "geofence_radius = :geofence_radius";
            $params[':geofence_radius'] = $data->geofence_radius;
        }

        if (isset($data->start_time)) {
            $updateFields[] = "start_time = :start_time";
            $params[':start_time'] = $data->start_time;
        }

        if (isset($data->end_time)) {
            $updateFields[] = "end_time = :end_time";
            $params[':end_time'] = $data->end_time;
        }

        if (isset($data->is_recurring)) {
            $updateFields[] = "is_recurring = :is_recurring";
            $params[':is_recurring'] = (bool)$data->is_recurring;
        }

        if (isset($data->recurrence_pattern)) {
            $updateFields[] = "recurrence_pattern = :recurrence_pattern";
            $params[':recurrence_pattern'] = $data->recurrence_pattern;
        }

        if (isset($data->recurrence_interval)) {
            $updateFields[] = "recurrence_interval = :recurrence_interval";
            $params[':recurrence_interval'] = $data->recurrence_interval;
        }

        if (isset($data->recurrence_end_date)) {
            $updateFields[] = "recurrence_end_date = :recurrence_end_date";
            $params[':recurrence_end_date'] = $data->recurrence_end_date;
        }

        if (isset($data->is_active)) {
            $updateFields[] = "is_active = :is_active";
            $params[':is_active'] = (bool)$data->is_active;
        }

        if (empty($updateFields)) {
            Helpers::sendResponse(false, 'No fields to update', null, 400);
        }

        $updateFields[] = "updated_at = NOW()";

        $query = "UPDATE services SET " . implode(', ', $updateFields) . " WHERE id = :service_id";
        $stmt = $db->prepare($query);

        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }

        if ($stmt->execute()) {
            // Log admin activity
            $logQuery = "INSERT INTO admin_logs 
                        (admin_id, action, action_type, target_type, target_id, details, ip_address, created_at) 
                        VALUES 
                        (:admin_id, 'update_service', 'update', 'service', :service_id, :details, :ip, NOW())";

            $details = json_encode($data);
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

            $stmt = $db->prepare($logQuery);
            $stmt->bindParam(':admin_id', $userData['user_id']);
            $stmt->bindParam(':service_id', $serviceId);
            $stmt->bindParam(':details', $details);
            $stmt->bindParam(':ip', $ip);
            $stmt->execute();

            Helpers::sendResponse(true, 'Service updated successfully');
        } else {
            Helpers::sendResponse(false, 'Failed to update service', null, 500);
        }
    }

    // DELETE: Delete service
    elseif ($method === 'DELETE') {
        $serviceId = isset($_GET['id']) ? intval($_GET['id']) : null;

        if (!$serviceId) {
            Helpers::sendResponse(false, 'Service ID is required', null, 400);
        }

        // Get service info before deletion
        $query = "SELECT name FROM services WHERE id = :service_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':service_id', $serviceId);
        $stmt->execute();
        $service = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$service) {
            Helpers::sendResponse(false, 'Service not found', null, 404);
        }

        // Delete service (cascades to attendance, service_rewards, etc.)
        $query = "DELETE FROM services WHERE id = :service_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':service_id', $serviceId);

        if ($stmt->execute()) {
            // Log admin activity
            $logQuery = "INSERT INTO admin_logs 
                        (admin_id, action, action_type, target_type, target_id, details, ip_address, created_at) 
                        VALUES 
                        (:admin_id, 'delete_service', 'delete', 'service', :service_id, :details, :ip, NOW())";

            $details = json_encode(['name' => $service['name']]);
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

            $stmt = $db->prepare($logQuery);
            $stmt->bindParam(':admin_id', $userData['user_id']);
            $stmt->bindParam(':service_id', $serviceId);
            $stmt->bindParam(':details', $details);
            $stmt->bindParam(':ip', $ip);
            $stmt->execute();

            Helpers::sendResponse(true, 'Service deleted successfully');
        } else {
            Helpers::sendResponse(false, 'Failed to delete service', null, 500);
        }
    } else {
        Helpers::sendResponse(false, 'Method not allowed', null, 405);
    }
} catch (PDOException $e) {
    ErrorLogger::logDatabaseError($e, $userData['user_id'] ?? 'unknown', [
        'endpoint' => 'admin/services',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'Database error in services management: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    ErrorLogger::logError($e, [
        'endpoint' => 'admin/services',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'Error in services management: ' . $e->getMessage(), null, 500);
}
