<?php
// File: employer/employer_create_task.php
define('PROJECT_ROOT', dirname(__DIR__)); 
$upload_dir_name = 'uploads' . DIRECTORY_SEPARATOR . 'tasks';
$upload_path_abs = PROJECT_ROOT . DIRECTORY_SEPARATOR . $upload_dir_name . DIRECTORY_SEPARATOR;
define('ALLOWED_EXTENSIONS', ['xlsx', 'jpg', 'jpeg', 'png', 'pdf']);
define('MAX_FILE_SIZE', 5 * 1024 * 1024); 

include 'auth_check.php'; 
require_role(['employer']); 
require_once('../db.php'); 

$employer_id = $_SESSION['user_id']; 
$message = ''; 
$projects = []; 
$members = []; 
$error = false; 
$title = $description = $due_date = ''; 

// Fetch Projects
$sql_proj = "SELECT p.project_id, p.project_name FROM projects p JOIN employer_projects ep ON p.project_id = ep.project_id WHERE ep.employer_id = ?"; 
$stmt_proj = $conn->prepare($sql_proj); 
$stmt_proj->bind_param("i", $employer_id); 
$stmt_proj->execute(); 
$result_proj = $stmt_proj->get_result(); 
while ($row = $result_proj->fetch_assoc()) { $projects[] = $row; } 
$stmt_proj->close();

// Fetch Members
$sql_mem = "SELECT DISTINCT u.id, u.username FROM users u JOIN member_projects mp ON u.id = mp.member_id WHERE mp.project_id IN (SELECT project_id FROM employer_projects WHERE employer_id = ?)"; 
$stmt_mem = $conn->prepare($sql_mem); 
$stmt_mem->bind_param("i", $employer_id); 
$stmt_mem->execute(); 
$result_mem = $stmt_mem->get_result(); 
while ($row = $result_mem->fetch_assoc()) { $members[] = $row; } 
$stmt_mem->close();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title']); 
    $description = trim($_POST['description']); 
    $due_date = $_POST['due_date']; 
    $project_id = (int)$_POST['project_id']; 
    $assigned_to = (int)$_POST['assigned_to']; 
    $status = 'pending'; 

    // 1. VALIDASI DATA TEKS (MANDATORY)
    if (empty($title) || empty($description) || empty($due_date) || $project_id === 0 || $assigned_to === 0) { 
        $message = "❌ Semua field teks harus diisi."; 
        $error = true; 
    } 

    // 2. VALIDASI FILE (MANDATORY - WAJIB UPLOAD)
    $uploaded_attachment = null;
    if (!isset($_FILES['attachment']) || $_FILES['attachment']['error'] == UPLOAD_ERR_NO_FILE) {
        $message = "❌ Anda wajib melampirkan file.";
        $error = true;
    } else {
        // Jika file ada, proses validasi lanjutan
        if ($_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
            $file_tmp = $_FILES['attachment']['tmp_name']; 
            $file_size = $_FILES['attachment']['size']; 
            $file_name_original = basename($_FILES['attachment']['name']); 
            $file_ext = strtolower(pathinfo($file_name_original, PATHINFO_EXTENSION));

            if (!in_array($file_ext, ALLOWED_EXTENSIONS)) { 
                $message = "❌ Format file salah. (Hanya: xlsx, jpg, png, pdf)"; 
                $error = true; 
            }
            if ($file_size > MAX_FILE_SIZE) { 
                $message = "❌ File terlalu besar (Max 5MB)."; 
                $error = true; 
            }

            if (!$error) {
                if (!is_dir($upload_path_abs)) { mkdir($upload_path_abs, 0777, true); }
                $file_name_unique = uniqid('attach_') . '.' . $file_ext; 
                $destination = $upload_path_abs . $file_name_unique;

                if (move_uploaded_file($file_tmp, $destination)) { 
                    $uploaded_attachment = ['original_name' => $file_name_original, 'unique_name' => $file_name_unique]; 
                } else { 
                    $message = "❌ Gagal mengupload file ke server."; 
                    $error = true; 
                }
            }
        } else {
             $message = "❌ Terjadi error saat upload file.";
             $error = true;
        }
    }

    // 3. INSERT DATABASE JIKA TIDAK ADA ERROR
    if (!$error) {
        $sql_task = "INSERT INTO tasks (title, description, due_date, status, project_id, assigned_to, creator_id) VALUES (?, ?, ?, ?, ?, ?, ?)"; 
        $stmt_task = $conn->prepare($sql_task); 
        $stmt_task->bind_param("ssssiii", $title, $description, $due_date, $status, $project_id, $assigned_to, $employer_id);
        
        if ($stmt_task->execute()) {
            $new_task_id = mysqli_insert_id($conn); 
            $message = "✅ Tugas berhasil dibuat!";
            
            // Simpan Data Attachment (Pasti ada karena sekarang Mandatory)
            if ($uploaded_attachment) { 
                $sql_attach = "INSERT INTO task_attachments (task_id, original_file_name, unique_file_name) VALUES (?, ?, ?)"; 
                $stmt_attach = $conn->prepare($sql_attach); 
                $stmt_attach->bind_param("iss", $new_task_id, $uploaded_attachment['original_name'], $uploaded_attachment['unique_name']); 
                $stmt_attach->execute(); 
                $stmt_attach->close(); 
            }
            
            // Reset Form
            $title = $description = $due_date = ''; 
        } else { 
            $message = "❌ Gagal Database: " . $stmt_task->error; 
        } 
        $stmt_task->close();
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <title>Employer - Buat Tugas</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* --- GLOBAL --- */
        :root { --bg: #f0f2f5; --primary: #007bff; --text: #333; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); padding: 40px 20px; color: var(--text); }

        .container {
            max-width: 750px; margin: 0 auto; background: white; padding: 50px; 
            border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.08); border-top: 5px solid var(--primary);
        }

        .header { margin-bottom: 35px; border-bottom: 2px solid #f3f4f6; padding-bottom: 20px; }
        .header h1 { font-size: 26px; font-weight: 700; color: #111; margin-bottom: 8px; }
        .back-link { text-decoration: none; color: #666; font-size: 15px; font-weight: 500; display: inline-flex; align-items: center; gap: 5px; transition: 0.2s; }
        .back-link:hover { color: var(--primary); }

        .form-group { margin-bottom: 25px; }
        
        /* Penanda Wajib (Asterisk Merah) */
        label { display: block; margin-bottom: 10px; font-size: 16px; font-weight: 600; color: #1f2937; }
        label .required { color: red; margin-left: 3px; }
        
        input[type="text"], input[type="date"], select, textarea {
            width: 100%; padding: 14px 16px; border: 1px solid #d1d5db; border-radius: 8px; 
            font-size: 16px; font-family: 'Poppins', sans-serif; background-color: #f9fafb; transition: 0.2s; color: #333;
        }
        input:focus, select:focus, textarea:focus { outline: none; border-color: var(--primary); background-color: #fff; box-shadow: 0 0 0 4px rgba(0, 123, 255, 0.1); }
        textarea { resize: vertical; min-height: 120px; }

        /* GRID SYSTEM UNTUK TANGGAL & MEMBER */
        .form-row-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 25px; }

        /* UPLOAD */
        .upload-box { background-color: #f8f9fa; border: 2px dashed #cbd5e1; padding: 30px; border-radius: 10px; text-align: center; transition: 0.2s; }
        .upload-box:hover { border-color: var(--primary); background-color: #f0f7ff; }
        .upload-hint { font-size: 14px; color: #6b7280; margin-top: 8px; display: block; }

        .btn-submit {
            background-color: #4CAF50; color: white; width: 100%; padding: 16px; border: none; border-radius: 8px; 
            font-size: 18px; font-weight: 700; cursor: pointer; transition: all 0.2s; margin-top: 15px; 
            box-shadow: 0 4px 6px rgba(76, 175, 80, 0.2); text-transform: uppercase; letter-spacing: 0.5px;
        }
        .btn-submit:hover { background-color: #43a047; transform: translateY(-2px); }

        .alert { padding: 15px; border-radius: 8px; margin-bottom: 25px; font-size: 15px; font-weight: 500; text-align: center; }
        .alert-success { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
        .alert-error { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

        /* --- MOBILE RESPONSIVE CSS --- */
        @media screen and (max-width: 768px) {
            body { padding: 20px 10px; } 
            .container { padding: 25px 20px; } 
            .header h1 { font-size: 22px; }
            .back-link { font-size: 13px; }
            .form-row-grid { grid-template-columns: 1fr; gap: 0; }
            input, select, textarea { font-size: 14px; padding: 12px; }
            .btn-submit { font-size: 16px; padding: 14px; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h1>🚀 Buat Tugas Baru</h1>
        <a href="employer_dashboard.php" class="back-link">← Kembali ke Dashboard</a>
    </div>

    <?php if ($message): ?><div class="alert <?php echo $error ? 'alert-error' : 'alert-success'; ?>"><?php echo $message; ?></div><?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <div class="form-group">
            <label>Judul Tugas <span class="required">*</span></label>
            <input type="text" name="title" required value="<?php echo htmlspecialchars($title ?? ''); ?>" placeholder="Contoh: Laporan Keuangan...">
        </div>

        <div class="form-group">
            <label>Deskripsi Detail <span class="required">*</span></label>
            <textarea name="description" required placeholder="Jelaskan detail pekerjaan..."><?php echo htmlspecialchars($description ?? ''); ?></textarea>
        </div>

        <div class="form-group">
            <label>Project <span class="required">*</span></label>
            <select name="project_id" required>
                <option value="">-- Pilih Project --</option>
                <?php foreach ($projects as $proj): ?>
                    <option value="<?php echo $proj['project_id']; ?>"><?php echo htmlspecialchars($proj['project_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-row-grid">
            <div class="form-group">
                <label>Deadline <span class="required">*</span></label>
                <input type="date" name="due_date" required value="<?php echo htmlspecialchars($due_date ?? ''); ?>">
            </div>
            <div class="form-group">
                <label>Tugaskan Kepada <span class="required">*</span></label>
                <select name="assigned_to" required>
                    <option value="">-- Pilih Member --</option>
                    <?php foreach ($members as $mem): ?>
                        <option value="<?php echo $mem['id']; ?>"><?php echo htmlspecialchars($mem['username']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <div class="form-group">
            <label>Lampiran File (Wajib) <span class="required">*</span></label>
            <div class="upload-box">
                <input type="file" name="attachment" accept=".xlsx, .jpg, .png, .pdf" required>
                <span class="upload-hint">Format: XLSX, JPG, PNG, PDF (Max 5MB)</span>
            </div>
        </div>

        <button type="submit" class="btn-submit">✅ BUAT & KIRIM TUGAS</button>
    </form>
</div>

</body>
</html>