<?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 service templates
    if ($method === 'GET') {
        $includeInactive = isset($_GET['include_inactive']) ? filter_var($_GET['include_inactive'], FILTER_VALIDATE_BOOLEAN) : false;

        $whereClause = $includeInactive ? '' : 'WHERE st.is_active = TRUE';

        $query = "SELECT st.*, sty.name as service_type_name, sty.allows_delegates
                  FROM service_templates st
                  LEFT JOIN service_types sty ON st.service_type_id = sty.id
                  $whereClause
                  ORDER BY st.name ASC";

        $stmt = $db->prepare($query);
        $stmt->execute();

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

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

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

        // Validate required fields
        if (empty($data->name)) {
            Helpers::sendResponse(false, 'Service name is required', null, 400);
        }

        // Check if updating existing template
        if (isset($data->id) && $data->id > 0) {
            // Update existing template
            $updateFields = [];
            $params = [':id' => $data->id];

            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)) {
                $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->is_recurring)) {
                $updateFields[] = "is_recurring = :is_recurring";
                $params[':is_recurring'] = $data->is_recurring ? 1 : 0;
            }
            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_days)) {
                $updateFields[] = "recurrence_days = :recurrence_days";
                $params[':recurrence_days'] = $data->recurrence_days;
            }
            if (isset($data->recurrence_start_date)) {
                $updateFields[] = "recurrence_start_date = :recurrence_start_date";
                $params[':recurrence_start_date'] = $data->recurrence_start_date;
            }
            if (isset($data->recurrence_end_date)) {
                $updateFields[] = "recurrence_end_date = :recurrence_end_date";
                $params[':recurrence_end_date'] = $data->recurrence_end_date;
            }
            if (isset($data->default_start_time)) {
                $updateFields[] = "default_start_time = :default_start_time";
                $params[':default_start_time'] = $data->default_start_time;
            }
            if (isset($data->default_end_time)) {
                $updateFields[] = "default_end_time = :default_end_time";
                $params[':default_end_time'] = $data->default_end_time;
            }

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

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

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

            if ($stmt->execute()) {
                Helpers::logAdminAction($db, $userData['user_id'], 'update_service_template', 'update', 'service_template', $data->id, json_encode($data));
                Helpers::sendResponse(true, 'Service template updated successfully');
            } else {
                Helpers::sendResponse(false, 'Failed to update service template', null, 500);
            }
        } else {
            // Create new template
            $query = "INSERT INTO `service_templates` 
                      (`name`, `description`, `service_type_id`, `location`, `latitude`, `longitude`, 
                       `geofence_radius`, `is_recurring`, `recurrence_pattern`, `recurrence_interval`,
                       `recurrence_days`, `recurrence_start_date`, `recurrence_end_date`,
                       `default_start_time`, `default_end_time`, `is_active`) 
                      VALUES 
                      (:name, :description, :service_type_id, :location, :latitude, :longitude,
                       :geofence_radius, :is_recurring, :recurrence_pattern, :recurrence_interval,
                       :recurrence_days, :recurrence_start_date, :recurrence_end_date,
                       :default_start_time, :default_end_time, TRUE)";

            $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);
            $isRecurring = isset($data->is_recurring) ? ($data->is_recurring ? 1 : 0) : 0;
            $stmt->bindParam(':is_recurring', $isRecurring);
            $recurrencePattern = $data->recurrence_pattern ?? 'none';
            $stmt->bindParam(':recurrence_pattern', $recurrencePattern);
            $recurrenceInterval = $data->recurrence_interval ?? 1;
            $stmt->bindParam(':recurrence_interval', $recurrenceInterval);
            $recurrenceDays = $data->recurrence_days ?? null;
            $stmt->bindParam(':recurrence_days', $recurrenceDays);
            $recurrenceStartDate = $data->recurrence_start_date ?? null;
            $stmt->bindParam(':recurrence_start_date', $recurrenceStartDate);
            $recurrenceEndDate = $data->recurrence_end_date ?? null;
            $stmt->bindParam(':recurrence_end_date', $recurrenceEndDate);
            $defaultStartTime = $data->default_start_time ?? null;
            $stmt->bindParam(':default_start_time', $defaultStartTime);
            $defaultEndTime = $data->default_end_time ?? null;
            $stmt->bindParam(':default_end_time', $defaultEndTime);

            if ($stmt->execute()) {
                $newTemplateId = $db->lastInsertId();
                Helpers::logAdminAction($db, $userData['user_id'], 'create_service_template', 'create', 'service_template', $newTemplateId, json_encode($data));
                Helpers::sendResponse(true, 'Service template created successfully', ['template_id' => $newTemplateId], 201);
            } else {
                Helpers::sendResponse(false, 'Failed to create service template', null, 500);
            }
        }
    }

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

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

        // Get template info before deletion
        $query = "SELECT name FROM service_templates WHERE id = :template_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':template_id', $templateId);
        $stmt->execute();
        $template = $stmt->fetch(PDO::FETCH_ASSOC);

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

        // Delete template (cascades to service_occurrences)
        $query = "DELETE FROM service_templates WHERE id = :template_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':template_id', $templateId);

        if ($stmt->execute()) {
            Helpers::logAdminAction($db, $userData['user_id'], 'delete_service_template', 'delete', 'service_template', $templateId, json_encode(['name' => $template['name']]));
            Helpers::sendResponse(true, 'Service template deleted successfully');
        } else {
            Helpers::sendResponse(false, 'Failed to delete service template', null, 500);
        }
    } else {
        Helpers::sendResponse(false, 'Method not allowed', null, 405);
    }
} catch (PDOException $e) {
    Helpers::sendResponse(false, 'Database error: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    Helpers::sendResponse(false, 'Error: ' . $e->getMessage(), null, 500);
}
