<?php
/**
 * AJAX Handler - Create 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. Silakan login kembali.']);
    exit;
}

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

// Check if user can create
if (!$permSummary['can_create']) {
    echo json_encode(['success' => false, 'message' => 'Anda tidak memiliki akses untuk membuat tugas']);
    exit;
}

// Get form data
$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']) : 'pending';
$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;

// ========================================
// VALIDATION PHASE
// ========================================

// 1. Required fields validation
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;
}

// 2. 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;
}

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

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

// 5. Deadline validation
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;
}

// Check if deadline is not in the past
$today = new DateTime('today');
if ($dateObj < $today) {
    echo json_encode(['success' => false, 'message' => 'Tenggat waktu tidak boleh di masa lalu']);
    exit;
}

// ========================================
// PERMISSION VALIDATION PHASE (CRITICAL)
// ========================================

// Get creator data
$creatorStmt = $conn->prepare("SELECT id, full_name, role, department, is_active FROM users WHERE id = ? AND is_active = 1");
$creatorStmt->bind_param("i", $_SESSION['user_id']);
$creatorStmt->execute();
$creatorResult = $creatorStmt->get_result();

if ($creatorResult->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Data pembuat tugas tidak valid']);
    exit;
}

$creator = $creatorResult->fetch_assoc();
$creatorStmt->close();

// Get assigned user data
$assigneeStmt = $conn->prepare("SELECT id, full_name, 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();

// CRITICAL: Validate assignment permission based on role
$canAssign = false;
$permissionMessage = '';

if (in_array($creator['role'], ['admin', 'director'], true)) {
    // Admin & Director can assign to anyone
    $canAssign = true;
    
} elseif ($creator['role'] === 'dept_head') {
    // Dept Head can only assign to staff in same department
    if ($assignee['role'] === 'staff' && 
        $creator['department'] !== null && 
        $creator['department'] === $assignee['department']) {
        $canAssign = true;
    } else {
        $permissionMessage = 'Dept Head hanya dapat menugaskan ke staff di departemen yang sama';
    }
    
} elseif ($creator['role'] === 'staff') {
    // Staff can only assign to themselves
    if ($creator['id'] === $assignee['id']) {
        $canAssign = true;
    } else {
        $permissionMessage = 'Staff hanya dapat membuat tugas untuk diri sendiri';
    }
    
} else {
    $permissionMessage = 'Role tidak dikenali';
}

// If permission check failed, return error
if (!$canAssign) {
    echo json_encode([
        'success' => false, 
        'message' => $permissionMessage ?: 'Anda tidak memiliki hak untuk menugaskan kepada user ini'
    ]);
    exit;
}

// ========================================
// DATABASE INSERTION PHASE
// ========================================

// Department is automatically set from assignee (SECURE - cannot be manipulated)
$department = $assignee['department'];

// Begin transaction for data integrity
$conn->begin_transaction();

try {
    // Insert task
    $stmt = $conn->prepare("
        INSERT INTO rencana_kerja (
            judul_tugas, 
            deskripsi, 
            prioritas, 
            status, 
            assigned_to, 
            tenggat_waktu,
            progress_percentage,
            department,
            created_by,
            created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");

    $stmt->bind_param(
        "ssssisisi",
        $judulTugas,
        $deskripsi,
        $prioritas,
        $status,
        $assignedTo,
        $tenggatWaktu,
        $progressPercentage,
        $department,
        $_SESSION['user_id']
    );

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

    $insertedId = $stmt->insert_id;
    $stmt->close();
    
    // Commit transaction
    $conn->commit();

    // Success response
    echo json_encode([
        'success' => true,
        'message' => 'Tugas berhasil dibuat!',
        'task_id' => $insertedId
    ]);

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

$conn->close();