<div class="container-fluid">
    <!-- Project Header -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <div>
            <h1 class="h3 mb-1 text-gray-800"><?php echo htmlspecialchars($project_data->project_name); ?></h1>
            <p class="mb-0 text-muted"><?php echo htmlspecialchars($project_data->description); ?></p>
        </div>
        <a href="?page=projects" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-2"></i>Kembali ke Daftar Proyek
        </a>
    </div>

    <!-- Project Details -->
    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Status</div>
                            <select class="form-select form-select-lg" id="project-status-select" data-project-id="<?php echo htmlspecialchars($project_data->id_project); ?>">
                                <option value="Planning" <?php echo $project_data->status == 'Planning' ? 'selected' : ''; ?>>Planning</option>
                                <option value="In Progress" <?php echo $project_data->status == 'In Progress' ? 'selected' : ''; ?>>In Progress</option>
                                <option value="Completed" <?php echo $project_data->status == 'Completed' ? 'selected' : ''; ?>>Completed</option>
                                <option value="On Hold" <?php echo $project_data->status == 'On Hold' ? 'selected' : ''; ?>>On Hold</option>
                            </select>
                        </div>
                        <div class="col-auto"><i class="bi bi-info-circle-fill fs-2 text-gray-300"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Tanggal Mulai</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo date('d M Y', strtotime($project_data->start_date)); ?></div>
                        </div>
                        <div class="col-auto"><i class="bi bi-calendar-event fs-2 text-gray-300"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-danger shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Target Selesai</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $project_data->end_date ? date('d M Y', strtotime($project_data->end_date)) : 'N/A'; ?></div>
                        </div>
                        <div class="col-auto"><i class="bi bi-calendar-check fs-2 text-gray-300"></i></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Task Timeline -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Timeline Tugas</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="tasks-table" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>Tugas</th>
                            <th>Deskripsi</th>
                            <th>Penanggung Jawab</th>
                            <th>Tanggal Mulai</th>
                            <th>Jatuh Tempo</th>
                            <th style="width: 15%;">Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($tasks)): ?>
                            <?php foreach ($tasks as $task): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($task['task_name']); ?></td>
                                    <td><?php echo htmlspecialchars($task['description'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($task['assignee_name'] ?? 'Belum Ditugaskan'); ?></td>
                                    <td><?php echo date('d M Y', strtotime($task['start_date'])); ?></td>
                                    <td><?php echo $task['due_date'] ? date('d M Y', strtotime($task['due_date'])) : 'N/A'; ?></td>
                                    <td>
                                        <select class="form-select form-select-sm task-status-select" data-task-id="<?php echo $task['id_task']; ?>">
                                            <option value="To Do" <?php echo $task['status'] == 'To Do' ? 'selected' : ''; ?>>To Do</option>
                                            <option value="In Progress" <?php echo $task['status'] == 'In Progress' ? 'selected' : ''; ?>>In Progress</option>
                                            <option value="Done" <?php echo $task['status'] == 'Done' ? 'selected' : ''; ?>>Done</option>
                                            <option value="Blocked" <?php echo $task['status'] == 'Blocked' ? 'selected' : ''; ?>>Blocked</option>
                                        </select>
                                    </td>
                                    <td>
                                        <button class="btn btn-danger btn-sm delete-task-btn" data-task-id="<?php echo $task['id_task']; ?>"><i class="bi bi-trash"></i></button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="text-center">Belum ada tugas untuk proyek ini.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add New Task Form -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Tambah Tugas Baru</h6>
        </div>
        <div class="card-body">
            <form action="?page=project_store_task" method="POST">
                <input type="hidden" name="id_project" value="<?php echo htmlspecialchars($project_data->id_project); ?>">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="task_name" class="form-label">Nama Tugas</label>
                        <input type="text" class="form-control" id="task_name" name="task_name" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="assignee_user_id" class="form-label">Penanggung Jawab</label>
                        <select class="form-select" id="assignee_user_id" name="assignee_user_id">
                            <option value="">Pilih Pengguna</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id_user']; ?>"><?php echo htmlspecialchars($user['nama_lengkap']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="task_description" class="form-label">Deskripsi Tugas</label>
                    <textarea class="form-control" id="task_description" name="description" rows="2"></textarea>
                </div>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label for="task_start_date" class="form-label">Tanggal Mulai</label>
                        <input type="date" class="form-control" id="task_start_date" name="start_date" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label for="task_due_date" class="form-label">Jatuh Tempo</label>
                        <input type="date" class="form-control" id="task_due_date" name="due_date">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label for="task_status" class="form-label">Status</label>
                        <select class="form-select" id="task_status" name="status">
                            <option value="To Do" selected>To Do</option>
                            <option value="In Progress">In Progress</option>
                            <option value="Done">Done</option>
                             <option value="Blocked">Blocked</option>
                        </select>
                    </div>
                </div>
                <button type="submit" class="btn btn-success">Tambah Tugas</button>
            </form>
        </div>
    </div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Listener for task status changes
    const taskStatusSelects = document.querySelectorAll('.task-status-select');
    taskStatusSelects.forEach(select => {
        select.addEventListener('change', function () {
            const id_task = this.dataset.taskId;
            const new_status = this.value;
            
            const originalColor = this.style.backgroundColor;
            this.style.backgroundColor = '#ffc107'; // Yellow for pending

            fetch('?page=project_update_task_status', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                body: JSON.stringify({ id_task: id_task, status: new_status })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.style.backgroundColor = '#198754'; // Green for success
                    setTimeout(() => { this.style.backgroundColor = originalColor; }, 1000);
                } else {
                    this.style.backgroundColor = '#dc3545'; // Red for error
                    alert('Gagal memperbarui status tugas: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                this.style.backgroundColor = '#dc3545';
                console.error('Error:', error);
                alert('Terjadi kesalahan jaringan.');
            });
        });
    });

    // Listener for project status change
    const projectStatusSelect = document.getElementById('project-status-select');
    if (projectStatusSelect) {
        projectStatusSelect.addEventListener('change', function () {
            const id_project = this.dataset.projectId;
            const new_status = this.value;

            const originalBorderColor = this.style.borderColor;
            this.style.borderColor = '#ffc107';

            fetch('?page=project_update_status', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                body: JSON.stringify({ id_project: id_project, status: new_status })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.style.borderColor = '#198754';
                     setTimeout(() => { this.style.borderColor = originalBorderColor; }, 1500);
                } else {
                    this.style.borderColor = '#dc3545';
                    alert('Gagal memperbarui status proyek: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                this.style.borderColor = '#dc3545';
                console.error('Error:', error);
                alert('Terjadi kesalahan jaringan.');
            });
        });
    }

    // Listener for delete task button
    const deleteButtons = document.querySelectorAll('.delete-task-btn');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function () {
            const id_task = this.dataset.taskId;

            if (confirm('Anda yakin ingin menghapus tugas ini?')) {
                fetch('?page=project_delete_task', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                    body: JSON.stringify({ id_task: id_task })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Remove the table row from the DOM
                        this.closest('tr').remove();
                    } else {
                        alert('Gagal menghapus tugas: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Terjadi kesalahan jaringan.');
                });
            }
        });
    });
});
</script>
