<?php
// File: superadmin/superadmin_create_project.php

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

$message = "";
$project_name_input = ''; 
$selected_employers = [];
$selected_members = []; 

// --- AMBIL DATA ---
$employers = [];
$res_emp = mysqli_query($conn, "SELECT id, username FROM users WHERE role = 'employer' ORDER BY username");
while ($row = mysqli_fetch_assoc($res_emp)) { $employers[] = $row; }

$members = [];
$res_mem = mysqli_query($conn, "SELECT id, username FROM users WHERE role = 'member' ORDER BY username");
while ($row = mysqli_fetch_assoc($res_mem)) { $members[] = $row; }


// --- LOGIKA CREATE PROJECT ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $project_name = trim($_POST['project_name']);
    $description = trim($_POST['description']);
    $project_name_input = $project_name; 
    
    $selected_employers = array_map('intval', $_POST['employers'] ?? []); 
    $selected_members = array_map('intval', $_POST['members'] ?? []); 
    $member_count = count($selected_members);

    if (empty($project_name)) {
        $message = "Nama Project harus diisi!";
    } elseif (empty($selected_employers)) {
        $message = "Minimal harus memilih satu Employer!";
    } elseif ($member_count < 1 || $member_count > 7) {
        $message = "Jumlah Member harus antara 1 sampai 7 orang.";
    } else {
        $check_stmt = mysqli_prepare($conn, "SELECT project_id FROM projects WHERE project_name = ?");
        mysqli_stmt_bind_param($check_stmt, "s", $project_name);
        mysqli_stmt_execute($check_stmt);
        mysqli_stmt_store_result($check_stmt);
        
        if (mysqli_stmt_num_rows($check_stmt) > 0) {
            $message = "Nama Project **'{$project_name}'** sudah terpakai.";
            mysqli_stmt_close($check_stmt);
        } else {
            mysqli_stmt_close($check_stmt);
            
            // Insert Project
            $insert_proj_stmt = mysqli_prepare($conn, "INSERT INTO projects (project_name, description) VALUES (?, ?)");
            mysqli_stmt_bind_param($insert_proj_stmt, "ss", $project_name, $description);

            if (mysqli_stmt_execute($insert_proj_stmt)) {
                $new_project_id = mysqli_insert_id($conn);
                mysqli_stmt_close($insert_proj_stmt);
                
                // Insert Employer Links
                if (!empty($selected_employers)) {
                    $link_query_parts_emp = []; $types_emp = ''; $bind_values_emp = []; 
                    foreach ($selected_employers as $emp_id) {
                        $link_query_parts_emp[] = "(?, ?)"; $types_emp .= 'ii';
                        $bind_values_emp[] = $emp_id; $bind_values_emp[] = $new_project_id;
                    }
                    $link_query_emp = "INSERT INTO employer_projects (employer_id, project_id) VALUES " . implode(', ', $link_query_parts_emp);
                    $link_stmt_emp = mysqli_prepare($conn, $link_query_emp);
                    $params_emp = [&$link_stmt_emp, &$types_emp]; 
                    foreach ($bind_values_emp as $key => $value) { $params_emp[] = &$bind_values_emp[$key]; }
                    if (count($params_emp) > 2) { call_user_func_array('mysqli_stmt_bind_param', $params_emp); }
                    mysqli_stmt_execute($link_stmt_emp);
                    mysqli_stmt_close($link_stmt_emp);
                }

                // Insert Member Links
                if (!empty($selected_members)) {
                    $link_query_parts_mem = []; $types_mem = ''; $bind_values_mem = []; 
                    foreach ($selected_members as $mem_id) {
                        $link_query_parts_mem[] = "(?, ?)"; $types_mem .= 'ii';
                        $bind_values_mem[] = $mem_id; $bind_values_mem[] = $new_project_id;
                    }
                    $link_query_mem = "INSERT INTO member_projects (member_id, project_id) VALUES " . implode(', ', $link_query_parts_mem);
                    $link_stmt_mem = mysqli_prepare($conn, $link_query_mem);
                    $params_mem = [&$link_stmt_mem, &$types_mem]; 
                    foreach ($bind_values_mem as $key => $value) { $params_mem[] = &$bind_values_mem[$key]; }
                    if (count($params_mem) > 2) { call_user_func_array('mysqli_stmt_bind_param', $params_mem); }
                    mysqli_stmt_execute($link_stmt_mem);
                    mysqli_stmt_close($link_stmt_mem);
                }

                $message = "SUCCESS: Project **'$project_name'** berhasil dibuat!";
                $project_name_input = ''; $selected_employers = []; $selected_members = [];
                
                // Redirect ke List Project setelah sukses
                echo "<meta http-equiv='refresh' content='1;url=superadmin_list_project.php'>"; 

            } else {
                $message = "Gagal membuat Project: " . mysqli_error($conn);
            }
        } 
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <title>Buat Project</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #FF9800; --bg: #f4f6f9; }
        body { font-family: 'Poppins', sans-serif; background-color: var(--bg); padding: 40px 20px; color: #333; }
        
        .container { max-width: 800px; margin: 0 auto; }
        
        /* FORM CARD */
        .card { background: white; padding: 40px; border-radius: 16px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); border-top: 5px solid var(--primary); margin-bottom: 40px; }
        h2 { margin-top: 0; color: #333; font-size: 26px; }
        
        .form-group { margin-bottom: 25px; }
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #444; }
        input[type="text"], textarea { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-family: 'Poppins'; box-sizing: border-box; }
        
        .checkbox-container { border: 1px solid #eee; border-radius: 8px; padding: 15px; max-height: 150px; overflow-y: auto; background: #f9f9f9; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        .check-item { display: flex; align-items: center; background: white; padding: 8px; border-radius: 6px; border: 1px solid #eee; }
        .check-item input { margin-right: 10px; }

        .btn-submit { background: var(--primary); color: white; width: 100%; padding: 15px; border: none; border-radius: 8px; font-weight: 700; cursor: pointer; transition: 0.2s; font-size: 16px; }
        .btn-submit:hover { background: #F57C00; transform: translateY(-2px); }

        .btn-back { display: block; text-align: center; margin-top: 20px; color: #666; text-decoration: none; font-weight: 600; }

        .alert-success { background: #e0f2f1; color: #00695c; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #b2dfdb; }
        .alert-error { background: #ffebee; color: #c62828; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #ffcdd2; }
    </style>
</head>
<body>

<div class="container">
    
    <div class="card">
        <h2>🏗️ Buat Project Baru</h2>
        <p style="color:#666; margin-bottom:30px;">Isi form di bawah ini untuk membuat project baru.</p>

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

        <form method="POST">
            <div class="form-group">
                <label>Nama Project</label>
                <input type="text" name="project_name" required value="<?php echo htmlspecialchars($project_name_input); ?>" placeholder="Nama Project...">
            </div>

            <div class="form-group">
                <label>Deskripsi</label>
                <textarea name="description" rows="3" placeholder="Deskripsi singkat..."></textarea>
            </div>

            <div class="form-group">
                <label>Pilih Employer</label>
                <div class="checkbox-container">
                    <?php foreach ($employers as $emp): ?>
                        <div class="check-item">
                            <input type="checkbox" name="employers[]" value="<?php echo $emp['id']; ?>" <?php echo in_array($emp['id'], $selected_employers) ? 'checked' : ''; ?>>
                            <label><?php echo htmlspecialchars($emp['username']); ?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="form-group">
                <label>Pilih Member (1-7 Orang)</label>
                <div class="checkbox-container">
                    <?php foreach ($members as $mem): ?>
                        <div class="check-item">
                            <input type="checkbox" name="members[]" value="<?php echo $mem['id']; ?>" <?php echo in_array($mem['id'], $selected_members) ? 'checked' : ''; ?>>
                            <label><?php echo htmlspecialchars($mem['username']); ?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <button type="submit" class="btn-submit">SIMPAN PROJECT</button>
        </form>
        
        <a href="superadmin_dashboard.php" class="btn-back">← Kembali ke Dashboard</a>
    </div>

</div>

</body>
</html>