<?php

class TaskAssignmentsController extends BaseController
{
    protected $pdo;

    public function __construct($pdo = null)
    {
        parent::__construct();
        $this->pdo = $pdo ?: Database::getConnection();
    }

    /**
     * Assign a task to a user (simple version).
     * Expected POST: assignee_id
     */
    public function assign($taskId)
    {
        $this->authCheck();

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return $this->json(['success' => false, 'error' => 'Invalid request method']);
        }

        $tenantId   = $_SESSION['tenant_id'];
        $assigneeId = isset($_POST['assignee_id']) ? (int)$_POST['assignee_id'] : 0;

        if ($assigneeId <= 0) {
            return $this->json(['success' => false, 'error' => 'Invalid assignee']);
        }

        try {
            // Ensure task exists and belongs to this tenant
            $stmt = $this->pdo->prepare("
                SELECT id FROM tasks
                WHERE id = ? AND tenant_id = ?
            ");
            $stmt->execute([$taskId, $tenantId]);
            $task = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$task) {
                return $this->json(['success' => false, 'error' => 'Task not found']);
            }

            // Insert or update assignment (one assignee per task for now)
            // You can change this to allow multiple assignees if desired.
            $stmt = $this->pdo->prepare("
                INSERT INTO task_assignments (task_id, tenant_id, assignee_id, created_by, created_at)
                VALUES (:task_id, :tenant_id, :assignee_id, :created_by, NOW())
                ON DUPLICATE KEY UPDATE
                    assignee_id = VALUES(assignee_id),
                    created_by = VALUES(created_by),
                    created_at = VALUES(created_at)
            ");

            $stmt->execute([
                ':task_id'    => $taskId,
                ':tenant_id'  => $tenantId,
                ':assignee_id'=> $assigneeId,
                ':created_by' => $_SESSION['user_id'],
            ]);

            return $this->json(['success' => true]);
        } catch (Exception $e) {
            error_log("Task assignment error: " . $e->getMessage());
            return $this->json(['success' => false, 'error' => 'Failed to assign task']);
        }
    }

    /**
     * Get tasks assigned to current user (simple JSON API).
     */
    public function myAssignments()
    {
        $this->authCheck();

        $tenantId = $_SESSION['tenant_id'];
        $userId   = $_SESSION['user_id'];

        try {
            $stmt = $this->pdo->prepare("
                SELECT 
                    ta.id as assignment_id,
                    t.*
                FROM task_assignments ta
                INNER JOIN tasks t ON ta.task_id = t.id
                WHERE ta.tenant_id = :tenant_id
                  AND ta.assignee_id = :user_id
                ORDER BY t.due_date IS NULL, t.due_date ASC, t.created_at DESC
            ");
            $stmt->execute([
                ':tenant_id' => $tenantId,
                ':user_id'   => $userId,
            ]);

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

            return $this->json([
                'success'     => true,
                'assignments' => $rows,
            ]);
        } catch (Exception $e) {
            error_log("My assignments error: " . $e->getMessage());
            return $this->json(['success' => false, 'error' => 'Failed to load assignments']);
        }
    }

    /**
     * Get a single assignment details (basic permissions: same tenant).
     */
    public function showAssignment($assignmentId)
    {
        $this->authCheck();

        $tenantId = $_SESSION['tenant_id'];
        $userId   = $_SESSION['user_id'];

        try {
            $stmt = $this->pdo->prepare("
                SELECT 
                    ta.*,
                    t.title,
                    t.description,
                    t.status,
                    t.priority,
                    t.due_date
                FROM task_assignments ta
                INNER JOIN tasks t ON ta.task_id = t.id
                WHERE ta.id = :id
                  AND ta.tenant_id = :tenant_id
            ");
            $stmt->execute([
                ':id'        => $assignmentId,
                ':tenant_id' => $tenantId,
            ]);

            $assignment = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$assignment) {
                return $this->json(['success' => false, 'error' => 'Assignment not found']);
            }

            // Very simple permission: assignee or creator (you can tighten later)
            if ($assignment['assignee_id'] != $userId && $assignment['created_by'] != $userId) {
                return $this->json(['success' => false, 'error' => 'Access denied']);
            }

            return $this->json(['success' => true, 'assignment' => $assignment]);
        } catch (Exception $e) {
            error_log("Assignment detail error: " . $e->getMessage());
            return $this->json(['success' => false, 'error' => 'Failed to load assignment']);
        }
    }
}
