<?php
/**
 * AJAX Handler - Update Task
 * Enhanced with strict role-based permission validation
 */

session_start();
require_once __DIR__ . '/../../../DataBase/koneksi.php';
require_once __DIR__ . '/../../../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;
}

// Initialize permission
$permission = new RencanaKerjaPermission($conn, $_SESSION['user_id'], $_SESSION['role']);
$permSummary = $permission->getPermissionSummary();

// Get form data
$taskId = isset($_POST['task_id']) ? intval($_POST['task_id']) : 0;
$judulTugas = isset($_POST['judul_tugas']) ? trim($_POST['judul_tugas']) : '';
$deskripsi = isset($_POST['deskripsi']) ? trim($_POST['deskripsi']) : '';
$prioritas = isset($_POST['prioritas']) ? trim($_POST['prioritas']) : '';
$status = isset($_POST['status']) ? trim($_POST['status']) : '';
$assignedTo = isset($_POST['assigned_to']) ? intval($_POST['assigned_to']) : 0;
$tenggatWaktu = isset($_POST['tenggat_waktu']) ? trim($_POST['tenggat_waktu']) : '';
$progressPercentage = isset($_POST['progress_percentage']) ? intval($_POST['progress_percentage']) : 0;

// ========================================
// BASIC VALIDATION
// ========================================

if (!$taskId) {
    echo json_encode(['success' => false, 'message' => 'Task ID diperlukan']);
    exit;
}

// Check if user can update this task
if (!$permission->canUpdate($taskId)) {
    echo json_encode(['success' => false, 'message' => 'Anda tidak memiliki akses untuk mengupdate tugas ini']);
    exit;
}

if (empty($judulTugas)) {
    echo json_encode(['success' => false, 'message' => 'Nama tugas harus diisi']);
    exit;
}

if (strlen($judulTugas) > 255) {
    echo json_encode(['success' => false, 'message' => 'Nama tugas terlalu panjang (maksimal 255 karakter)']);
    exit;
}

if (empty($prioritas)) {
    echo json_encode(['success' => false, 'message' => 'Prioritas harus dipilih']);
    exit;
}

// Priority validation
$validPriorities = ['penting', 'penting_tidak_genting', 'penting_genting'];
if (!in_array($prioritas, $validPriorities, true)) {
    echo json_encode(['success' => false, 'message' => 'Prioritas tidak valid']);
    exit;
}

// Status validation
$validStatuses = ['pending', 'progress', 'stuck', 'done'];
if (!in_array($status, $validStatuses, true)) {
    echo json_encode(['success' => false, 'message' => 'Status tidak valid']);
    exit;
}

if (!$assignedTo) {
    echo json_encode(['success' => false, 'message' => 'User yang ditugaskan harus dipilih']);
    exit;
}

if (empty($tenggatWaktu)) {
    echo json_encode(['success' => false, 'message' => 'Tenggat waktu harus diisi']);
    exit;
}

// Validate date format
$dateObj = DateTime::createFromFormat('Y-m-d', $tenggatWaktu);
if (!$dateObj || $dateObj->format('Y-m-d') !== $tenggatWaktu) {
    echo json_encode(['success' => false, 'message' => 'Format tanggal tidak valid']);
    exit;
}

// ========================================
// PERMISSION VALIDATION FOR REASSIGNMENT
// ========================================

// Get current task data to check if assignee is changing
$checkStmt = $conn->prepare("SELECT assigned_to FROM rencana_kerja WHERE id = ? AND is_deleted = 0");
$checkStmt->bind_param("i", $taskId);
$checkStmt->execute();
$checkResult = $checkStmt->get_result();

if ($checkResult->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Tugas tidak ditemukan']);
    exit;
}

$currentTask = $checkResult->fetch_assoc();
$checkStmt->close();

// If assignee is changing, validate permission like create
if ($currentTask['assigned_to'] != $assignedTo) {
    // Get updater data
    $updaterStmt = $conn->prepare("SELECT id, role, department FROM users WHERE id = ? AND is_active = 1");
    $updaterStmt->bind_param("i", $_SESSION['user_id']);
    $updaterStmt->execute();
    $updaterResult = $updaterStmt->get_result();
    
    if ($updaterResult->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Data user tidak valid']);
        exit;
    }
    
    $updater = $updaterResult->fetch_assoc();
    $updaterStmt->close();
    
    // Get new assignee data
    $assigneeStmt = $conn->prepare("SELECT id, role, department, is_active FROM users WHERE id = ? AND is_active = 1");
    $assigneeStmt->bind_param("i", $assignedTo);
    $assigneeStmt->execute();
    $assigneeResult = $assigneeStmt->get_result();
    
    if ($assigneeResult->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'User yang ditugaskan tidak ditemukan atau tidak aktif']);
        exit;
    }
    
    $assignee = $assigneeResult->fetch_assoc();
    $assigneeStmt->close();
    
    // Validate reassignment permission
    $canReassign = false;
    $permissionMessage = '';
    
    if (in_array($updater['role'], ['admin', 'director'], true)) {
        $canReassign = true;
    } elseif ($updater['role'] === 'dept_head') {
        if ($assignee['role'] === 'staff' && 
            $updater['department'] !== null && 
            $updater['department'] === $assignee['department']) {
            $canReassign = true;
        } else {
            $permissionMessage = 'Dept Head hanya dapat menugaskan ke staff di departemen yang sama';
        }
    } elseif ($updater['role'] === 'staff') {
        if ($updater['id'] === $assignee['id']) {
            $canReassign = true;
        } else {
            $permissionMessage = 'Staff hanya dapat menugaskan ke diri sendiri';
        }
    }
    
    if (!$canReassign) {
        echo json_encode([
            'success' => false, 
            'message' => $permissionMessage ?: 'Anda tidak memiliki hak untuk menugaskan kepada user ini'
        ]);
        exit;
    }
    
    // Update department from new assignee
    $department = $assignee['department'];
} else {
    // Assignee not changing, keep existing department
    $department = null; // Will not be updated
}

// ========================================
// DATABASE UPDATE PHASE
// ========================================

$conn->begin_transaction();

try {
    if ($department !== null) {
        // Update with department change
        $stmt = $conn->prepare("
            UPDATE rencana_kerja SET
                judul_tugas = ?,
                deskripsi = ?,
                prioritas = ?,
                status = ?,
                assigned_to = ?,
                tenggat_waktu = ?,
                progress_percentage = ?,
                department = ?,
                updated_at = NOW()
            WHERE id = ? AND is_deleted = 0
        ");
        
        $stmt->bind_param(
            "sssisisii",
            $judulTugas,
            $deskripsi,
            $prioritas,
            $status,
            $assignedTo,
            $tenggatWaktu,
            $progressPercentage,
            $department,
            $taskId
        );
    } else {
        // Update without department change
        $stmt = $conn->prepare("
            UPDATE rencana_kerja SET
                judul_tugas = ?,
                deskripsi = ?,
                prioritas = ?,
                status = ?,
                assigned_to = ?,
                tenggat_waktu = ?,
                progress_percentage = ?,
                updated_at = NOW()
            WHERE id = ? AND is_deleted = 0
        ");
        
        $stmt->bind_param(
            "ssssisii",
            $judulTugas,
            $deskripsi,
            $prioritas,
            $status,
            $assignedTo,
            $tenggatWaktu,
            $progressPercentage,
            $taskId
        );
    }

    if (!$stmt->execute()) {
        throw new Exception('Gagal mengupdate tugas: ' . $stmt->error);
    }

    if ($stmt->affected_rows > 0) {
        $stmt->close();
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Tugas berhasil diupdate'
        ]);
    } else {
        $stmt->close();
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Tidak ada perubahan pada tugas'
        ]);
    }

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

$conn->close();