<?php
// app/controllers/TaskController.php

// Define Application Root for cleaner imports
$appRoot = __DIR__ . '/..'; 

// Load Models
require_once $appRoot . '/models/Task.php';
require_once $appRoot . '/models/Project.php'; 
require_once $appRoot . '/models/User.php';
require_once $appRoot . '/models/Comment.php'; // NEW: For Chat

class TaskController {
    private $pdo;
    private $taskModel;
    private $projectModel;
    private $commentModel;

    public function __construct($pdo) {
        $this->pdo = $pdo;
        $this->taskModel = new Task($pdo);
        $this->projectModel = new Project($pdo);
        $this->commentModel = new Comment($pdo); // Initialize Comment Model
    }

    // 1. Show the Kanban Board
    public function index() {
        $tasks = $this->taskModel->getAll();
        $pageTitle = "Task Board";
        
        $viewsPath = __DIR__ . '/../views';
        
        require_once $viewsPath . '/layouts/header.php';
        require_once $viewsPath . '/tasks/index.php';
        require_once $viewsPath . '/layouts/footer.php';
    }

    // 2. Show "Create Task" Form
    public function create() {
        $projects = $this->projectModel->getAll();
        
        // Fetch Users manually (since User Model is simple)
        $userStmt = $this->pdo->query("SELECT id, name FROM users WHERE status = 1");
        $users = $userStmt->fetchAll();

        $pageTitle = "New Task";
        $viewsPath = __DIR__ . '/../views';

        require_once $viewsPath . '/layouts/header.php';
        require_once $viewsPath . '/tasks/create.php';
        require_once $viewsPath . '/layouts/footer.php';
    }

    // 3. Save a New Task
    public function store() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = [
                'project_id' => $_POST['project_id'],
                'title' => $_POST['title'],
                'description' => $_POST['description'],
                'assigned_to' => !empty($_POST['assigned_to']) ? $_POST['assigned_to'] : null,
                'priority' => $_POST['priority'],
                'due_date' => $_POST['due_date'],
                'created_by' => $_SESSION['user_id']
            ];

            if ($this->taskModel->create($data)) {
                header('Location: /tasks.php');
                exit;
            } else {
                echo "Error saving task.";
            }
        }
    }

    // 4. Handle Drag & Drop Status Updates (AJAX)
    public function updateStatus() {
        $input = json_decode(file_get_contents('php://input'), true);

        if (isset($input['id']) && isset($input['status'])) {
            $taskId = $input['id'];
            $newStatus = $input['status'];
            
            $validStatuses = ['pending', 'in_process', 'completed'];
            
            if (in_array($newStatus, $validStatuses)) {
                if ($this->taskModel->updateStatus($taskId, $newStatus)) {
                    echo json_encode(['success' => true]);
                    exit;
                }
            }
        }
        
        http_response_code(400);
        echo json_encode(['success' => false]);
        exit;
    }

    // 5. Show Task Details (Info + Files + Comments)
    public function show($id) {
        // A. Fetch Task Info
        $stmt = $this->pdo->prepare("SELECT tasks.*, projects.name as project_name, users.name as assignee_name 
                                     FROM tasks 
                                     LEFT JOIN projects ON tasks.project_id = projects.id 
                                     LEFT JOIN users ON tasks.assigned_to = users.id 
                                     WHERE tasks.id = :id");
        $stmt->execute(['id' => $id]);
        $task = $stmt->fetch();

        if (!$task) {
            echo "Task not found.";
            exit;
        }

        // B. Fetch Uploaded Files
        $uploadStmt = $this->pdo->prepare("SELECT * FROM content_uploads WHERE task_id = :id ORDER BY uploaded_at DESC");
        $uploadStmt->execute(['id' => $id]);
        $uploads = $uploadStmt->fetchAll();

        // C. Fetch Comments (NEW)
        $comments = $this->commentModel->getByTask($id);

        $pageTitle = "Task: " . htmlspecialchars($task['title']);
        $viewsPath = __DIR__ . '/../views';
        
        require_once $viewsPath . '/layouts/header.php';
        require_once $viewsPath . '/tasks/details.php';
        require_once $viewsPath . '/layouts/footer.php';
    }

    // 6. Handle File Uploads
    public function upload() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $taskId = $_POST['task_id'];
            $userId = $_SESSION['user_id'];
            
            if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
                
                $uploadDir = __DIR__ . '/../../storage/uploads/';
                if (!is_dir($uploadDir)) { mkdir($uploadDir, 0777, true); }

                $fileName = time() . '_' . basename($_FILES['file']['name']);
                $targetPath = $uploadDir . $fileName;

                if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
                    // Save to DB
                    $stmt = $this->pdo->prepare("INSERT INTO content_uploads (task_id, file_path, uploaded_by) VALUES (:tid, :path, :uid)");
                    $stmt->execute(['tid' => $taskId, 'path' => $fileName, 'uid' => $userId]);
                    
                    // Auto-update status to "In Process"
                    $this->taskModel->updateStatus($taskId, 'in_process');
                    
                    header("Location: /task_details.php?id=" . $taskId);
                    exit;
                }
            }
        }
        echo "Upload failed.";
    }

    // 7. Handle New Comments (NEW)
    public function storeComment() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $taskId = $_POST['task_id'];
            $text = trim($_POST['comment']);
            $userId = $_SESSION['user_id'];

            if (!empty($text)) {
                $this->commentModel->create($taskId, $userId, $text);
            }

            // Redirect back to task page
            header("Location: /task_details.php?id=" . $taskId);
            exit;
        }
    }
}
?>