<?php
require_once '../config.php';
require_once '../middleware.php';

### API Blueprint: /admin/website_tasks
# Description: Manages website visit tasks.

# GET /admin/website_tasks?action=list
# Description: Lists all website visit tasks.
# Headers:
#   - Authorization: Bearer <token>
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Website tasks fetched",
#       "data": {
#         "tasks": [
#           {
#             "id": 1,
#             "web_url": "https://example.com",
#             "timer": 30,
#             "created_at": "2025-06-01 10:00:00"
#           }
#         ]
#       }
#     }

# POST /admin/website_tasks?action={add|edit|delete}
# Description: Adds, edits, or deletes a website visit task.
# Headers:
#   - Authorization: Bearer <token>
# Request Body (for add):
#   - web_url: string (required, valid URL)
#   - timer: integer (required, timer in seconds)
# Request Body (for edit):
#   - id: integer (required, task_id to edit)
#   - web_url: string (optional, valid URL)
#   - timer: integer (optional, timer in seconds)
# Request Body (for delete):
#   - id: integer (required, task_id to delete)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Operation successful"
#     }
#   - 400: Invalid input, URL already exists, Task not found
#   - 401: Unauthorized
#   - 500: Database connection failed

$token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
authenticateAdmin(str_replace('Bearer ', '', $token));

$action = $_GET['action'] ?? '';
$conn = getDbConnection();

switch ($action) {
    case 'list':
        $stmt = $conn->prepare("SELECT id, web_url, timer, created_at FROM website_visit_tasks ORDER BY created_at DESC");
        if (!$stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        $tasks = [];
        while ($row = $result->fetch_assoc()) {
            $tasks[] = $row;
        }
        sendResponse(200, 'Website tasks fetched', ['tasks' => $tasks]);
        break;

    case 'add':
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        validateInput($data, ['web_url', 'timer']);

        $web_url = $data['web_url'];
        $timer = (int)$data['timer'];

        // Validate URL format
        if (!filter_var($web_url, FILTER_VALIDATE_URL)) {
            sendResponse(400, 'Invalid URL format provided.');
        }

        if ($timer <= 0) {
            sendResponse(400, 'Timer must be a positive integer.');
        }

        // Check if URL already exists
        $check_stmt = $conn->prepare("SELECT id FROM website_visit_tasks WHERE web_url = ?");
        $check_stmt->bind_param("s", $web_url);
        $check_stmt->execute();
        $check_stmt->store_result();
        if ($check_stmt->num_rows > 0) {
            sendResponse(400, 'Website URL already exists.');
        }
        $check_stmt->close();

        $stmt = $conn->prepare("INSERT INTO website_visit_tasks (web_url, timer) VALUES (?, ?)");
        if (!$stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->bind_param("si", $web_url, $timer);
        $stmt->execute();
        if ($stmt->affected_rows > 0) {
            sendResponse(200, 'Website task added successfully.');
        } else {
            sendResponse(500, 'Failed to add website task.');
        }
        break;

    case 'edit':
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        validateInput($data, ['id']);
        $task_id = (int)$data['id'];

        $updates = [];
        $params = [];
        $types = '';

        if (isset($data['web_url'])) {
            // Validate URL format
            if (!filter_var($data['web_url'], FILTER_VALIDATE_URL)) {
                sendResponse(400, 'Invalid URL format provided.');
            }
            $updates[] = "web_url = ?";
            $params[] = $data['web_url'];
            $types .= 's';

            // Check if updated URL already exists for another ID
            $check_stmt = $conn->prepare("SELECT id FROM website_visit_tasks WHERE web_url = ? AND id != ?");
            $check_stmt->bind_param("si", $data['web_url'], $task_id);
            $check_stmt->execute();
            $check_stmt->store_result();
            if ($check_stmt->num_rows > 0) {
                sendResponse(400, 'Another task with this URL already exists.');
            }
            $check_stmt->close();
        }

        if (isset($data['timer'])) {
            $timer = (int)$data['timer'];
            if ($timer <= 0) {
                sendResponse(400, 'Timer must be a positive integer.');
            }
            $updates[] = "timer = ?";
            $params[] = $timer;
            $types .= 'i';
        }

        if (empty($updates)) {
            sendResponse(400, 'No fields to update provided.');
        }

        $sql = "UPDATE website_visit_tasks SET " . implode(', ', $updates) . " WHERE id = ?";
        $params[] = $task_id;
        $types .= 'i';

        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->bind_param($types, ...$params);
        $stmt->execute();

        if ($stmt->affected_rows > 0) {
            sendResponse(200, 'Website task updated successfully.');
        } else {
            sendResponse(404, 'Website task not found or no changes made.');
        }
        break;

    case 'delete':
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        validateInput($data, ['id']);
        $task_id = (int)$data['id'];

        $stmt = $conn->prepare("DELETE FROM website_visit_tasks WHERE id = ?");
        if (!$stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->bind_param("i", $task_id);
        $stmt->execute();

        if ($stmt->affected_rows > 0) {
            sendResponse(200, 'Website task deleted successfully.');
        } else {
            sendResponse(404, 'Website task not found.');
        }
        break;

    default:
        sendResponse(400, 'Invalid action. Use: list, add, edit, or delete');
        break;
}

$stmt->close();
$conn->close();
?>
