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

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

        if ($templateId > 0) {
            $whereConditions[] = "so.service_template_id = :template_id";
            $params[':template_id'] = $templateId;
        }

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

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

        $query = "SELECT so.*, st.name as service_name, st.location,
                         COUNT(DISTINCT a.user_id) as total_attendees
                  FROM service_occurrences so
                  JOIN service_templates st ON so.service_template_id = st.id
                  LEFT JOIN attendance a ON so.id = a.service_occurrence_id
                  $whereClause
                  GROUP BY so.id
                  ORDER BY so.occurrence_date DESC, so.start_time DESC";

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

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

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

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

        // Validate required fields
        if (
            empty($data->service_template_id) || empty($data->occurrence_date) ||
            empty($data->start_time) || empty($data->end_time)
        ) {
            Helpers::sendResponse(false, 'Template ID, occurrence date, start time, and end time are required', null, 400);
        }

        // Check if template exists
        $query = "SELECT id, name FROM service_templates WHERE id = :template_id AND is_active = TRUE";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':template_id', $data->service_template_id);
        $stmt->execute();
        $template = $stmt->fetch(PDO::FETCH_ASSOC);

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

        // Check if occurrence already exists for this date
        $query = "SELECT id FROM service_occurrences 
                  WHERE service_template_id = :template_id AND occurrence_date = :occurrence_date";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':template_id', $data->service_template_id);
        $stmt->bindParam(':occurrence_date', $data->occurrence_date);
        $stmt->execute();

        if ($stmt->rowCount() > 0) {
            Helpers::sendResponse(false, 'A service occurrence already exists for this date', null, 400);
        }

        // Insert new occurrence
        $query = "INSERT INTO service_occurrences 
                  (service_template_id, occurrence_date, start_time, end_time, notes, is_active) 
                  VALUES 
                  (:service_template_id, :occurrence_date, :start_time, :end_time, :notes, TRUE)";

        $stmt = $db->prepare($query);
        $stmt->bindParam(':service_template_id', $data->service_template_id);
        $stmt->bindParam(':occurrence_date', $data->occurrence_date);
        $stmt->bindParam(':start_time', $data->start_time);
        $stmt->bindParam(':end_time', $data->end_time);
        $notes = $data->notes ?? '';
        $stmt->bindParam(':notes', $notes);

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

            // Log admin activity
            Helpers::logAdminAction($db, $userData['user_id'], 'activate_service', 'create', 'service_occurrence', $newOccurrenceId, json_encode([
                'template_name' => $template['name'],
                'occurrence_date' => $data->occurrence_date,
                'start_time' => $data->start_time,
                'end_time' => $data->end_time
            ]));

            Helpers::sendResponse(true, 'Service activated successfully', [
                'occurrence_id' => $newOccurrenceId
            ], 201);
        } else {
            Helpers::sendResponse(false, 'Failed to activate service', null, 500);
        }
    }

    // PATCH: Update service occurrence (cancel, reactivate, etc.)
    elseif ($method === 'PATCH') {
        $occurrenceId = isset($_GET['id']) ? intval($_GET['id']) : null;

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

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

        // Build dynamic update query
        $updateFields = [];
        $params = [':occurrence_id' => $occurrenceId];

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

        if (isset($data->was_cancelled)) {
            $updateFields[] = "was_cancelled = :was_cancelled";
            $params[':was_cancelled'] = $data->was_cancelled ? 1 : 0;
        }

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

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

        $query = "UPDATE service_occurrences SET " . implode(', ', $updateFields) . " WHERE id = :occurrence_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_occurrence', 'update', 'service_occurrence', $occurrenceId, json_encode($data));
            Helpers::sendResponse(true, 'Service occurrence updated successfully');
        } else {
            Helpers::sendResponse(false, 'Failed to update service occurrence', null, 500);
        }
    }

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

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

        // Get occurrence info before deletion
        $query = "SELECT so.*, st.name as service_name 
                  FROM service_occurrences so
                  JOIN service_templates st ON so.service_template_id = st.id
                  WHERE so.id = :occurrence_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':occurrence_id', $occurrenceId);
        $stmt->execute();
        $occurrence = $stmt->fetch(PDO::FETCH_ASSOC);

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

        // Delete occurrence
        $query = "DELETE FROM service_occurrences WHERE id = :occurrence_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':occurrence_id', $occurrenceId);

        if ($stmt->execute()) {
            Helpers::logAdminAction($db, $userData['user_id'], 'delete_service_occurrence', 'delete', 'service_occurrence', $occurrenceId, json_encode([
                'service_name' => $occurrence['service_name'],
                'occurrence_date' => $occurrence['occurrence_date']
            ]));
            Helpers::sendResponse(true, 'Service occurrence deleted successfully');
        } else {
            Helpers::sendResponse(false, 'Failed to delete service occurrence', 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);
}
