<?php
session_start();
require_once '../../../DataBase/koneksi.php';
require_once '../../../config/RencanaKerjaPermission.php';

header('Content-Type: application/json');

// Validasi session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Session tidak valid']);
    exit;
}

try {
    // Validasi input
    if (empty($_POST['task_id'])) {
        echo json_encode(['success' => false, 'message' => 'Task ID tidak ditemukan']);
        exit;
    }

    $task_id = intval($_POST['task_id']);

    // Initialize permission
    $permission = new RencanaKerjaPermission($conn, $_SESSION['user_id'], $_SESSION['role']);
    $canEdit = $permission->hasPermission(RencanaKerjaPermission::PERM_EDIT, $task_id);

    if (!$canEdit['allowed']) {
        echo json_encode(['success' => false, 'message' => 'Anda tidak memiliki izin untuk mengedit tugas ini']);
        exit;
    }

    // Validasi required fields
    $required_fields = ['judul_tugas', 'prioritas', 'status', 'assigned_to', 'tenggat_waktu'];
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            echo json_encode(['success' => false, 'message' => 'Field ' . $field . ' wajib diisi']);
            exit;
        }
    }

    $judul_tugas = trim($_POST['judul_tugas']);
    $deskripsi = trim($_POST['deskripsi'] ?? '');
    $prioritas = $_POST['prioritas'];
    $status = $_POST['status'];
    $assigned_to = intval($_POST['assigned_to']);
    $tenggat_waktu = $_POST['tenggat_waktu'];
    $progress_percentage = intval($_POST['progress_percentage'] ?? 0);

    // Update completed_at jika status berubah ke done
    $completed_at = ($status === 'done') ? 'NOW()' : 'NULL';

    // Jika user adalah admin, update langsung
    // Jika manager, mungkin perlu approval (tergantung business logic)
    if ($canEdit['full_edit']) {
        $stmt = $conn->prepare("
            UPDATE rencana_kerja 
            SET judul_tugas = ?,
                deskripsi = ?,
                prioritas = ?,
                status = ?,
                assigned_to = ?,
                tenggat_waktu = ?,
                progress_percentage = ?,
                completed_at = " . $completed_at . ",
                updated_at = NOW()
            WHERE id = ? AND is_deleted = 0
        ");

        $stmt->bind_param(
            "ssssissi",
            $judul_tugas,
            $deskripsi,
            $prioritas,
            $status,
            $assigned_to,
            $tenggat_waktu,
            $progress_percentage,
            $task_id
        );
    } else {
        // Staff hanya bisa update status dan progress
        $stmt = $conn->prepare("
            UPDATE rencana_kerja 
            SET status = ?,
                progress_percentage = ?,
                completed_at = " . $completed_at . ",
                updated_at = NOW()
            WHERE id = ? AND is_deleted = 0
        ");

        $stmt->bind_param(
            "sii",
            $status,
            $progress_percentage,
            $task_id
        );
    }

    if ($stmt->execute()) {
        // Log activity
        $permission->logAction($task_id, 'update', 'Task updated: ' . $judul_tugas);

        echo json_encode([
            'success' => true,
            'message' => 'Tugas berhasil diupdate'
        ]);
    } else {
        throw new Exception('Gagal mengupdate data: ' . $stmt->error);
    }

    $stmt->close();

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

$conn->close();
?>