<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/Projects/ProjectManager.php';
require_once __DIR__ . '/../src/Projects/TaskManager.php';
require_once __DIR__ . '/navigation.php';
require_once __DIR__ . '/components/headers/page-header.php';

requirePermission('tasks_view');

$canEdit = hasPermission('tasks_edit');
$canAssign = hasPermission('tasks_assign');

$companyId = (int)$company['id'];
$userId = (int)$user['id'];
$taskId = (int)($_GET['id'] ?? 0);
$projectId = (int)($_GET['project_id'] ?? 0);

if (!$taskId) {
    header('Location: /projects.php?workspace=' . urlencode($company['username'] ?? ''));
    exit;
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_task' && $canEdit) {
        $updates = [
            'title' => $_POST['title'] ?? '',
            'description' => $_POST['description'] ?? '',
            'status_id' => (int)($_POST['status_id'] ?? 0),
            'priority' => $_POST['priority'] ?? 'medium',
            'due_date' => $_POST['due_date'] ?? null,
            'estimated_hours' => !empty($_POST['estimated_hours']) ? (float)$_POST['estimated_hours'] : null
        ];
        TaskManager::updateTask($taskId, $companyId, $userId, $updates);
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    if ($action === 'add_comment') {
        // TaskManager::addComment expects (task_id, user_id, comment)
        TaskManager::addComment($taskId, $userId, $_POST['comment'] ?? '');
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    if ($action === 'upload_attachment' && !empty($_FILES['file']['name'])) {
        // Delegate file handling to TaskManager::addAttachment
        TaskManager::addAttachment($taskId, $companyId, $userId, $_FILES['file']);
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }

    if ($action === 'delete_attachment' && !empty($_POST['attachment_id'])) {
        $attachmentId = (int)$_POST['attachment_id'];
        if ($attachmentId > 0) {
            $pdo = getPDO();
            $stmt = $pdo->prepare('SELECT id, task_id, uploaded_by FROM task_attachments WHERE id = ? AND task_id = ?');
            $stmt->execute([$attachmentId, $taskId]);
            $attachment = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($attachment) {
                $uploadedBy = (int)($attachment['uploaded_by'] ?? 0);
                if ($canEdit || $uploadedBy === $userId) {
                    TaskManager::deleteAttachment($attachmentId, $companyId);
                }
            }
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }

    if ($action === 'delete_comment' && !empty($_POST['comment_id'])) {
        $commentId = (int)$_POST['comment_id'];
        if ($commentId > 0) {
            $pdo = getPDO();
            $stmt = $pdo->prepare('SELECT id, user_id FROM task_comments WHERE id = ? AND task_id = ?');
            $stmt->execute([$commentId, $taskId]);
            $commentRow = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($commentRow && (int)$commentRow['user_id'] === $userId) {
                $del = $pdo->prepare('DELETE FROM task_comments WHERE id = ? AND task_id = ? AND user_id = ?');
                $del->execute([$commentId, $taskId, $userId]);
            }
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }

    if ($action === 'edit_comment' && !empty($_POST['comment_id'])) {
        $commentId = (int)$_POST['comment_id'];
        $newComment = (string)($_POST['comment'] ?? '');
        $newComment = trim($newComment);
        if ($commentId > 0 && $newComment !== '') {
            $pdo = getPDO();
            $stmt = $pdo->prepare('SELECT id, user_id FROM task_comments WHERE id = ? AND task_id = ?');
            $stmt->execute([$commentId, $taskId]);
            $commentRow = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($commentRow && (int)$commentRow['user_id'] === $userId) {
                $upd = $pdo->prepare('UPDATE task_comments SET comment = ? WHERE id = ? AND task_id = ? AND user_id = ?');
                $upd->execute([$newComment, $commentId, $taskId, $userId]);
            }
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    if ($action === 'assign_user' && $canAssign) {
        $assignUserId = (int)($_POST['user_id'] ?? 0);
        if ($assignUserId) {
            // Use TaskManager::assignTask(task_id, user_id, assigned_by)
            TaskManager::assignTask($taskId, $assignUserId, $userId);
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    if ($action === 'unassign_user' && $canAssign) {
        $assignUserId = (int)($_POST['user_id'] ?? 0);
        if ($assignUserId) {
            // Use TaskManager::unassignTask(task_id, user_id)
            TaskManager::unassignTask($taskId, $assignUserId);
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
}

// Get task data
$task = TaskManager::getTask($taskId, $companyId);
if (!$task) {
    header('Location: /projects.php?workspace=' . urlencode($company['username'] ?? ''));
    exit;
}

$project = ProjectManager::getProject($task['project_id'], $companyId);
$statuses = TaskManager::getStatuses($companyId);
// TaskManager::getTask already hydrates comments, attachments, and assignees
$comments = $task['comments'] ?? TaskManager::getTaskComments($taskId);
$attachments = $task['attachments'] ?? TaskManager::getTaskAttachments($taskId);
$assignees = $task['assignees'] ?? TaskManager::getTaskAssignees($taskId);

// Get available members
$pdo = getPDO();
$memberStmt = $pdo->prepare('
    SELECT u.id, u.name, u.email 
    FROM users u
    JOIN user_company_access uca ON u.id = uca.user_id
    WHERE uca.company_id = ?
    ORDER BY u.name ASC
');
$memberStmt->execute([$companyId]);
$members = $memberStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$workspace = $company['username'] ?? $company['subdomain'] ?? '';
$workspaceQuery = $workspace !== '' ? '?workspace=' . urlencode($workspace) : '';
$currentTheme = $_GET['theme'] ?? ($_SESSION['theme_preference'] ?? 'dark');
$currentTheme = in_array($currentTheme, ['dark', 'light'], true) ? $currentTheme : 'dark';

$taskDueDateValue = '';
if (!empty($task['due_date'])) {
    $taskDueDateValue = substr((string)$task['due_date'], 0, 10);
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= htmlspecialchars($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($task['title']) ?> - <?= htmlspecialchars($company['name']) ?></title>
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        (function() {
            var saved = localStorage.getItem('theme') || '<?= $currentTheme ?>';
            document.documentElement.setAttribute('data-theme', saved);
        })();
    </script>
</head>
<body class="projects-page task-page">
<?php renderNavigationNew('Projects', $currentTheme); ?>

<div class="main-container">
    <?php
    renderPageHeader(
        breadcrumbs: [
            ['label' => 'Home', 'url' => '/index.php', 'icon' => 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6'],
            ['label' => 'Projects', 'url' => '/projects.php', 'append_workspace' => true],
            ['label' => $project['name'] ?? 'Project', 'url' => '/projects.php?project=' . urlencode((string) ($project['id'] ?? 0)), 'append_workspace' => true],
        ],
        currentPage: 'Task',
        actions: [],
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <div class="dash-section">
            <form id="updateTaskForm" method="POST" class="is-hidden">
                <input type="hidden" name="action" value="update_task">
            </form>

            <div class="task-detail-grid">
                <div class="task-detail-main">
                    <section class="card">
                        <p class="section-title">Task</p>
                        <h2 class="card-title" style="margin-top: 6px;">Details</h2>
                        <p class="card-subtitle">Project: <?= htmlspecialchars($project['name'] ?? '—') ?></p>

                        <div class="task-detail-fields">
                            <div>
                                <label class="form-label" for="task-title">Title</label>
                                <input id="task-title" type="text" name="title" form="updateTaskForm" value="<?= htmlspecialchars($task['title']) ?>" <?= $canEdit ? '' : 'readonly' ?> class="form-input">
                            </div>

                            <div>
                                <label class="form-label" for="task-description">Description</label>
                                <textarea id="task-description" name="description" form="updateTaskForm" rows="6" <?= $canEdit ? '' : 'readonly' ?> class="form-textarea"><?= htmlspecialchars($task['description'] ?? '') ?></textarea>
                            </div>
                        </div>
                    </section>

                    <section class="card">
                        <p class="section-title">Discussion</p>
                        <h2 class="card-title" style="margin-top: 6px;">Comments</h2>

                        <?php if (empty($comments)): ?>
                            <p class="card-subtitle">No comments yet.</p>
                        <?php else: ?>
                            <div class="task-detail-comments">
                                <?php foreach ($comments as $comment): ?>
                                    <div class="task-detail-comment">
                                        <div class="task-detail-comment__meta">
                                            <span class="task-detail-comment__author"><?= htmlspecialchars($comment['user_name']) ?></span>
                                            <span class="task-detail-comment__time"><?= date('M j, Y g:i A', strtotime($comment['created_at'])) ?></span>
                                        </div>
                                        <div class="task-detail-comment__body"><?= nl2br(htmlspecialchars($comment['comment'])) ?></div>

                                        <?php if ((int)($comment['user_id'] ?? 0) === $userId): ?>
                                            <div class="task-detail-actions">
                                                <details>
                                                    <summary class="btn-secondary" style="display: inline-flex; align-items: center;">Edit</summary>
                                                    <form method="POST" style="margin-top: 10px;">
                                                        <input type="hidden" name="action" value="edit_comment">
                                                        <input type="hidden" name="comment_id" value="<?= (int)$comment['id'] ?>">
                                                        <div>
                                                            <label class="form-label">Update comment</label>
                                                            <textarea name="comment" rows="3" class="form-textarea" required><?= htmlspecialchars($comment['comment']) ?></textarea>
                                                        </div>
                                                        <div class="task-detail-actions">
                                                            <button type="submit" class="btn-primary">Save</button>
                                                        </div>
                                                    </form>
                                                </details>

                                                <form method="POST">
                                                    <input type="hidden" name="action" value="delete_comment">
                                                    <input type="hidden" name="comment_id" value="<?= (int)$comment['id'] ?>">
                                                    <button type="submit" class="btn-secondary">Delete</button>
                                                </form>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <form method="POST" class="task-detail-comment-form">
                            <input type="hidden" name="action" value="add_comment">
                            <div>
                                <label class="form-label" for="task-comment">Add comment</label>
                                <textarea id="task-comment" name="comment" rows="3" required class="form-textarea" placeholder="Write a comment..."></textarea>
                            </div>
                            <div class="task-detail-actions">
                                <button type="submit" class="btn-primary">Add comment</button>
                            </div>
                        </form>
                    </section>
                </div>

                <aside class="task-detail-sidebar">
                    <section class="card">
                        <p class="section-title">Properties</p>
                        <h2 class="card-title" style="margin-top: 6px;">Task fields</h2>

                        <div class="task-detail-fields">
                            <div>
                                <label class="form-label">Status</label>
                                <select name="status_id" form="updateTaskForm" <?= $canEdit ? '' : 'disabled' ?> class="form-select">
                                    <?php foreach ($statuses as $status): ?>
                                        <option value="<?= $status['id'] ?>" <?= $task['status_id'] == $status['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($status['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div>
                                <label class="form-label">Priority</label>
                                <select name="priority" form="updateTaskForm" <?= $canEdit ? '' : 'disabled' ?> class="form-select">
                                    <option value="low" <?= $task['priority'] === 'low' ? 'selected' : '' ?>>Low</option>
                                    <option value="medium" <?= $task['priority'] === 'medium' ? 'selected' : '' ?>>Medium</option>
                                    <option value="high" <?= $task['priority'] === 'high' ? 'selected' : '' ?>>High</option>
                                    <option value="urgent" <?= $task['priority'] === 'urgent' ? 'selected' : '' ?>>Urgent</option>
                                </select>
                            </div>

                            <div>
                                <label class="form-label">Due date</label>
                                <input type="date" name="due_date" form="updateTaskForm" value="<?= htmlspecialchars($taskDueDateValue) ?>" <?= $canEdit ? '' : 'readonly' ?> class="form-input">
                            </div>

                            <div>
                                <label class="form-label">Estimated hours</label>
                                <input type="number" name="estimated_hours" form="updateTaskForm" step="0.5" value="<?= $task['estimated_hours'] ?? '' ?>" <?= $canEdit ? '' : 'readonly' ?> class="form-input">
                            </div>
                        </div>

                        <?php if ($canEdit): ?>
                            <div class="task-detail-actions">
                                <button type="submit" form="updateTaskForm" class="btn-primary">Save changes</button>
                            </div>
                        <?php endif; ?>
                    </section>

                    <section class="card">
                        <p class="section-title">People</p>
                        <h2 class="card-title" style="margin-top: 6px;">Assignees</h2>

                        <?php if (empty($assignees)): ?>
                            <p class="card-subtitle">No one assigned.</p>
                        <?php else: ?>
                            <div class="task-detail-assignees">
                                <?php foreach ($assignees as $assignee): ?>
                                    <div class="task-detail-assignee">
                                        <span class="task-detail-assignee__name"><?= htmlspecialchars($assignee['name']) ?></span>
                                        <?php if ($canAssign): ?>
                                            <form method="POST">
                                                <input type="hidden" name="action" value="unassign_user">
                                                <input type="hidden" name="user_id" value="<?= $assignee['id'] ?>">
                                                <button type="submit" class="btn-secondary">Remove</button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($canAssign): ?>
                            <form method="POST" class="task-detail-assign-form">
                                <input type="hidden" name="action" value="assign_user">
                                <div>
                                    <label class="form-label">Assign member</label>
                                    <select name="user_id" class="form-select">
                                        <option value="">Select member...</option>
                                        <?php foreach ($members as $member): ?>
                                            <?php if (!in_array($member['id'], array_column($assignees, 'id'))): ?>
                                                <option value="<?= $member['id'] ?>"><?= htmlspecialchars($member['name']) ?></option>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="task-detail-actions">
                                    <button type="submit" class="btn-secondary">Assign</button>
                                </div>
                            </form>
                        <?php endif; ?>
                    </section>

                    <section class="card">
                        <p class="section-title">Files</p>
                        <h2 class="card-title" style="margin-top: 6px;">Attachments</h2>

                        <?php if (empty($attachments)): ?>
                            <p class="card-subtitle">No attachments yet.</p>
                        <?php else: ?>
                            <div class="task-detail-attachments">
                                <?php foreach ($attachments as $attachment): ?>
                                    <div class="task-detail-attachment">
                                        <div class="task-detail-attachment__meta">
                                            <span class="task-detail-attachment__name"><?= htmlspecialchars($attachment['original_filename']) ?></span>
                                            <span class="task-detail-attachment__sub">
                                                <?php
                                                $uploadedAt = $attachment['uploaded_at'] ?? ($attachment['created_at'] ?? null);
                                                $uploadedAtText = 'Unknown';
                                                if (is_string($uploadedAt) && $uploadedAt !== '') {
                                                    $uploadedAtTs = strtotime($uploadedAt);
                                                    if ($uploadedAtTs !== false) {
                                                        $uploadedAtText = date('M j, Y', $uploadedAtTs);
                                                    }
                                                }
                                                ?>
                                                <?= number_format(((float)($attachment['file_size'] ?? 0)) / 1024, 1) ?> KB · <?= htmlspecialchars($uploadedAtText) ?>
                                            </span>
                                        </div>
                                        <div class="task-detail-attachment__actions">
                                            <a class="btn-secondary" href="/storage/companies/<?= $companyId ?>/project-attachments/<?= htmlspecialchars(basename($attachment['file_path'])) ?>" download>Download</a>
                                            <?php if ($canEdit || (int)($attachment['uploaded_by'] ?? 0) === $userId): ?>
                                                <form method="POST">
                                                    <input type="hidden" name="action" value="delete_attachment">
                                                    <input type="hidden" name="attachment_id" value="<?= (int)$attachment['id'] ?>">
                                                    <button type="submit" class="btn-secondary">Delete</button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <form method="POST" enctype="multipart/form-data" class="task-detail-upload-form">
                            <input type="hidden" name="action" value="upload_attachment">
                            <div>
                                <label class="form-label">Upload file</label>
                                <input type="file" name="file" required class="form-input">
                            </div>
                            <div class="task-detail-actions">
                                <button type="submit" class="btn-secondary">Upload</button>
                            </div>
                        </form>
                    </section>
                </aside>
            </div>
        </div>
    </div>
</div>
</div>
</div>
</body>
</html>
