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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Helpers::sendResponse(false, 'Method not allowed', null, 405);
}

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

if (!$userData || $userData['role'] !== 'admin') {
    Helpers::sendResponse(false, 'Unauthorized. Admin access required.', null, 403);
}

$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, 'Name, start time, and end time are required', null, 400);
}

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

// Create service
$query = "INSERT INTO services (name, description, location, latitude, longitude, geofence_radius, start_time, end_time, is_reward_based, tickets_required) 
          VALUES (:name, :description, :location, :latitude, :longitude, :geofence_radius, :start_time, :end_time, :is_reward_based, :tickets_required)";

$stmt = $db->prepare($query);
$stmt->bindParam(':name', $data->name);
$stmt->bindParam(':description', $data->description);
$stmt->bindParam(':location', $data->location);
$stmt->bindParam(':latitude', $data->latitude);
$stmt->bindParam(':longitude', $data->longitude);
$stmt->bindParam(':geofence_radius', $data->geofence_radius);
$stmt->bindParam(':start_time', $data->start_time);
$stmt->bindParam(':end_time', $data->end_time);
$stmt->bindParam(':is_reward_based', $data->is_reward_based);
$stmt->bindParam(':tickets_required', $data->tickets_required);

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

    // Log admin activity
    $query = "INSERT INTO admin_logs (admin_id, action, target_type, target_id, details) 
              VALUES (:admin_id, 'create_service', 'service', :service_id, :details)";

    $details = json_encode(['name' => $data->name]);
    $stmt = $db->prepare($query);
    $stmt->bindParam(':admin_id', $userData['user_id']);
    $stmt->bindParam(':service_id', $serviceId);
    $stmt->bindParam(':details', $details);
    $stmt->execute();

    Helpers::sendResponse(true, 'Service created successfully', [
        'service_id' => $serviceId
    ], 201);
} else {
    Helpers::sendResponse(false, 'Service creation failed', null, 500);
}
