<?php
// backend/api/tasks/update-section.php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once __DIR__ . '/../services/db.php';

try {
    $conn = db();

    // 1. Parse incoming request body
    $rawInput = file_get_contents("php://input");
    $data = json_decode($rawInput, true);

    if (!is_array($data) || empty($data)) {
        $data = $_POST ?: $_GET ?: $_REQUEST ?: [];
    }

    $taskId = $data['task_id'] ?? $data['taskId'] ?? $data['id'] ?? null;
    $sectionId = $data['section_id'] ?? $data['sectionId'] ?? null;

    if (!$taskId || !$sectionId) {
        http_response_code(400);
        echo json_encode([
            "success" => false, 
            "error" => "Missing required parameters: task_id and section_id"
        ]);
        exit;
    }

    // 2. Execute DB update without updated_at column dependency
    if (function_exists('sqlsrv_query') && !($conn instanceof PDO)) {
        $sql = "UPDATE tasks SET section_id = ? WHERE id = ?";
        $params = [(int)$sectionId, (int)$taskId];
        $stmt = sqlsrv_query($conn, $sql, $params);

        if ($stmt === false) {
            http_response_code(500);
            echo json_encode([
                "success" => false,
                "error" => "SQL Server Update Failed",
                "sqlsrv_errors" => sqlsrv_errors()
            ]);
            exit;
        }
    } else if ($conn instanceof PDO) {
        $stmt = $conn->prepare("UPDATE tasks SET section_id = :section_id WHERE id = :id");
        $stmt->execute([
            ':section_id' => (int)$sectionId, 
            ':id' => (int)$taskId
        ]);
    } else if ($conn instanceof mysqli) {
        $stmt = $conn->prepare("UPDATE tasks SET section_id = ? WHERE id = ?");
        $stmt->bind_param("ii", $sectionId, $taskId);
        $stmt->execute();
    }

    echo json_encode([
        "success" => true,
        "message" => "Task section updated successfully",
        "task_id" => (int)$taskId,
        "section_id" => (int)$sectionId
    ]);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        "success" => false, 
        "error" => $e->getMessage()
    ]);
}