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

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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$message = '';
$error = false;

// 1. AMBIL DATA PROJECT LAMA
$sql_proj = "SELECT * FROM projects WHERE project_id = $id";
$res_proj = mysqli_query($conn, $sql_proj);
$project = mysqli_fetch_assoc($res_proj);

if (!$project) {
    echo "<script>alert('Project tidak ditemukan!'); window.location='superadmin_list_project.php';</script>";
    exit;
}

// 2. AMBIL SEMUA EMPLOYER & MEMBER
$all_employers = mysqli_query($conn, "SELECT id, username FROM users WHERE role='employer'");
$all_members = mysqli_query($conn, "SELECT id, username FROM users WHERE role='member'");

// 3. AMBIL DATA TERPILIH SAAT INI (Untuk dicentang otomatis)
$selected_emps = [];
$q_se = mysqli_query($conn, "SELECT employer_id FROM employer_projects WHERE project_id = $id");
while($r = mysqli_fetch_assoc($q_se)) $selected_emps[] = $r['employer_id'];

$selected_mems = [];
$q_sm = mysqli_query($conn, "SELECT member_id FROM member_projects WHERE project_id = $id");
while($r = mysqli_fetch_assoc($q_sm)) $selected_mems[] = $r['member_id'];


// 4. PROSES SIMPAN DATA
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $p_name = mysqli_real_escape_string($conn, $_POST['project_name']);
    $p_desc = mysqli_real_escape_string($conn, $_POST['description']);
    $post_emps = isset($_POST['employers']) ? $_POST['employers'] : [];
    $post_mems = isset($_POST['members']) ? $_POST['members'] : [];

    if (empty($p_name)) {
        $message = "Nama Project wajib diisi.";
        $error = true;
    } else {
        // A. Update Tabel Project
        $update_sql = "UPDATE projects SET project_name = '$p_name', description = '$p_desc' WHERE project_id = $id";
        if (mysqli_query($conn, $update_sql)) {
            
            // B. Update Employer (Hapus semua yg lama -> Insert yg baru)
            mysqli_query($conn, "DELETE FROM employer_projects WHERE project_id = $id");
            if (!empty($post_emps)) {
                foreach ($post_emps as $eid) {
                    $eid = (int)$eid;
                    mysqli_query($conn, "INSERT INTO employer_projects (employer_id, project_id) VALUES ($eid, $id)");
                }
            }

            // C. Update Member (Hapus semua yg lama -> Insert yg baru)
            mysqli_query($conn, "DELETE FROM member_projects WHERE project_id = $id");
            if (!empty($post_mems)) {
                foreach ($post_mems as $mid) {
                    $mid = (int)$mid;
                    mysqli_query($conn, "INSERT INTO member_projects (member_id, project_id) VALUES ($mid, $id)");
                }
            }

            echo "<script>alert('✅ Project berhasil diperbarui!'); window.location='superadmin_list_project.php';</script>";
        } else {
            $message = "Gagal update database: " . mysqli_error($conn);
            $error = true;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <title>Edit Project</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #FFC107; --bg: #f4f6f9; --dark: #333; }
        body { font-family: 'Poppins', sans-serif; background: var(--bg); padding: 40px; color: #333; }
        
        .card { 
            max-width: 800px; margin: 0 auto; background: white; padding: 40px; 
            border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); 
            border-top: 5px solid var(--primary); 
        }
        h2 { margin-bottom: 25px; color: var(--dark); border-bottom: 2px solid #eee; padding-bottom: 15px; }
        
        .form-group { margin-bottom: 20px; }
        label { display: block; font-weight: 600; margin-bottom: 8px; color: #555; }
        input[type="text"], textarea { 
            width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; 
            font-family: inherit; font-size: 14px;
        }
        
        /* CHECKBOX GRID */
        .checkbox-container { 
            display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); 
            gap: 10px; background: #f8f9fa; padding: 15px; 
            border-radius: 8px; border: 1px solid #eee; 
            max-height: 200px; overflow-y: auto; 
        }
        .cb-item { display: flex; align-items: center; gap: 8px; font-size: 14px; cursor: pointer; }
        .cb-item input { accent-color: var(--primary); transform: scale(1.2); }

        .btn-save { 
            background: var(--primary); color: #000; padding: 12px 25px; border: none; 
            border-radius: 8px; font-weight: 700; cursor: pointer; font-size: 16px; 
            width: 100%; margin-top: 20px; transition: 0.2s; 
        }
        .btn-save:hover { filter: brightness(0.9); }
        
        .btn-back { display: inline-block; margin-top: 15px; text-decoration: none; color: #666; font-size: 14px; font-weight: 600; }
        .btn-back:hover { color: #000; }

        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: 600; background: #f8d7da; color: #721c24; }
    </style>
</head>
<body>

<div class="card">
    <h2>✏️ Edit Project</h2>

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

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

        <div class="form-group">
            <label>Deskripsi</label>
            <textarea name="description" rows="4"><?php echo htmlspecialchars($project['description']); ?></textarea>
        </div>

        <div class="form-group">
            <label>Pilih Employer (Atasan)</label>
            <div class="checkbox-container">
                <?php while ($emp = mysqli_fetch_assoc($all_employers)): ?>
                    <label class="cb-item">
                        <input type="checkbox" name="employers[]" value="<?php echo $emp['id']; ?>" 
                        <?php echo in_array($emp['id'], $selected_emps) ? 'checked' : ''; ?>>
                        <?php echo htmlspecialchars($emp['username']); ?>
                    </label>
                <?php endwhile; ?>
            </div>
        </div>

        <div class="form-group">
            <label>Pilih Member (Tim Pelaksana)</label>
            <div class="checkbox-container">
                <?php while ($mem = mysqli_fetch_assoc($all_members)): ?>
                    <label class="cb-item">
                        <input type="checkbox" name="members[]" value="<?php echo $mem['id']; ?>" 
                        <?php echo in_array($mem['id'], $selected_mems) ? 'checked' : ''; ?>>
                        <?php echo htmlspecialchars($mem['username']); ?>
                    </label>
                <?php endwhile; ?>
            </div>
        </div>

        <button type="submit" class="btn-save">SIMPAN PERUBAHAN</button>
    </form>

    <div style="text-align: center;">
        <a href="superadmin_list_project.php" class="btn-back">← Batal & Kembali</a>
    </div>
</div>

</body>
</html>