<?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;
}

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

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

try {
    // Validasi input
    $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);
    $created_by = $_SESSION['user_id'];

    // Untuk Admin, approval_status langsung 'approved'
    // Untuk Manager, approval_status = 'pending'
    $approval_status = ($canCreate['needs_approval']) ? 'pending' : 'approved';

    // Insert ke database
    $stmt = $conn->prepare("
        INSERT INTO rencana_kerja 
        (judul_tugas, deskripsi, created_by, assigned_to, prioritas, status, 
         tenggat_waktu, approval_status, progress_percentage, is_active, is_deleted, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, NOW())
    ");

    $stmt->bind_param(
        "ssiissssi",
        $judul_tugas,
        $deskripsi,
        $created_by,
        $assigned_to,
        $prioritas,
        $status,
        $tenggat_waktu,
        $approval_status,
        $progress_percentage
    );

    if ($stmt->execute()) {
        $task_id = $stmt->insert_id;

        // Log activity
        $permission->logAction($task_id, 'create', 'Task created: ' . $judul_tugas);

        $message = ($approval_status === 'pending') 
            ? 'Tugas berhasil dibuat dan menunggu approval admin' 
            : 'Tugas berhasil dibuat';

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

    $stmt->close();

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

$conn->close();
?>