<?php
include '../includes/db.php';
 include 'header.php'; 
$success = '';
$error = '';

// DELETE individual department image
if (isset($_GET['delete_img'])) {
    $imgId = (int)$_GET['delete_img'];
    $imgData = $conn->query("SELECT image_path, department_id FROM department_images WHERE id=$imgId")->fetch_assoc();
    if ($imgData) {
        $path = '../' . $imgData['image_path'];
        if (file_exists($path)) unlink($path);
        $conn->query("DELETE FROM department_images WHERE id=$imgId");
        header("Location: DepartementsAdd.php?edit=" . $imgData['department_id']);
        exit;
    }
}

// DELETE entire department
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $imgs = $conn->query("SELECT image_path FROM department_images WHERE department_id=$id");
    while ($img = $imgs->fetch_assoc()) {
        $path = '../' . $img['image_path'];
        if (file_exists($path)) unlink($path);
    }
    $conn->query("DELETE FROM department_images WHERE department_id=$id");
    $conn->query("DELETE FROM departments WHERE id=$id");
    header("Location: DepartementsAdd.php");
    exit;
}

// EDIT department
$editing = false;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $dept = $conn->query("SELECT * FROM departments WHERE id=$id")->fetch_assoc();
    if (!$dept) die("Department not found");
    $editing = true;

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);

        $stmt = $conn->prepare("UPDATE departments SET name=?, description=? WHERE id=?");
        $stmt->bind_param("ssi", $name, $description, $id);
        $stmt->execute();
        $stmt->close();

        // Upload new images
        if (!empty($_FILES['images']['name'][0])) {
            $targetDir = "../uploads/departments/";
            if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

            $files = $_FILES['images'];
            for ($i = 0; $i < count($files['name']); $i++) {
                if ($files['error'][$i] === 0) {
                    $fileName = time().'_'.$files['name'][$i];
                    $targetFile = $targetDir . $fileName;

                    if (move_uploaded_file($files['tmp_name'][$i], $targetFile)) {
                        $imagePath = "uploads/departments/".$fileName;
                        $imgStmt = $conn->prepare("INSERT INTO department_images (department_id, image_path) VALUES (?, ?)");
                        $imgStmt->bind_param("is", $id, $imagePath);
                        $imgStmt->execute();
                        $imgStmt->close();
                    }
                }
            }
        }

        $success = "Department updated successfully!";
    }
}

// ADD new department
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_GET['edit'])) {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);

    $stmt = $conn->prepare("INSERT INTO departments (name, description) VALUES (?, ?)");
    $stmt->bind_param("ss", $name, $description);
    if($stmt->execute()){
        $deptId = $stmt->insert_id;
        $stmt->close();

        // Upload images
        if (!empty($_FILES['images']['name'][0])) {
            $targetDir = "../uploads/departments/";
            if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

            $files = $_FILES['images'];
            for ($i = 0; $i < count($files['name']); $i++) {
                if ($files['error'][$i] === 0) {
                    $fileName = time().'_'.$files['name'][$i];
                    $targetFile = $targetDir . $fileName;

                    if (move_uploaded_file($files['tmp_name'][$i], $targetFile)) {
                        $imagePath = "uploads/departments/".$fileName;
                        $imgStmt = $conn->prepare("INSERT INTO department_images (department_id, image_path) VALUES (?, ?)");
                        $imgStmt->bind_param("is", $deptId, $imagePath);
                        $imgStmt->execute();
                        $imgStmt->close();
                    }
                }
            }
        }

        // stay in Add mode
        header("Location: DepartementsAdd.php?added=1");
        exit;
    } else {
        $error = "Error adding department: " . $conn->error;
    }
}

// Show success after redirect
if(isset($_GET['added']) && $_GET['added'] == 1){
    $success = "Department added successfully!";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= $editing ? "Edit Department" : "Add Department" ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Load Poppins from Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js"></script>
<script>
tinymce.init({
  selector: '#description',
  height: 400,

  plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table emoticons template paste wordcount',

  toolbar: 'undo redo | formatselect | fontselect | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent | link image media | preview fullscreen | forecolor backcolor emoticons | code',

  menubar: true,
  branding: false,

  // Load Poppins inside TinyMCE iframe so it renders correctly
  content_style: "@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap'); body { font-family: 'Poppins', sans-serif; }",

  // Define fonts for the toolbar dropdown
  font_formats: "Poppins=Poppins,sans-serif; Arial=arial,helvetica,sans-serif; Courier New=courier new,courier,monospace; Georgia=georgia,palatino,serif; Times New Roman=times new roman,times; Verdana=verdana,geneva,sans-serif"
});
</script>

<style>
body { font-family:"Segoe UI",sans-serif; background:#f3f5f9; color:#333; margin:0; padding:0; }
.container { width:90%; max-width:900px; margin:50px auto; background:#fff; padding:30px 40px; border-radius:12px; box-shadow:0 8px 25px rgba(0,0,0,0.1); }
h2 { text-align:center; font-size:2rem; margin-bottom:30px; color:#1a237e; border-bottom:3px solid #1a237e; display:inline-block; padding-bottom:6px; }
form label { display:block; margin-bottom:8px; font-weight:600; color:#444; }
form input[type="text"], form input[type="file"], form textarea { width:100%; padding:12px; margin-bottom:20px; border:1px solid #ccc; border-radius:8px; font-size:1rem; box-sizing:border-box; transition:.3s; }
form input[type="text"]:focus, form textarea:focus { outline:none; border-color:#1a237e; box-shadow:0 0 5px rgba(26,35,126,0.3); }
button { width:200px; background:#1a237e; color:#fff; padding:12px 20px; border:none; border-radius:8px; cursor:pointer; font-weight:bold; transition:.3s; display:block; margin:0 auto; }
button:hover { background:#3949ab; }
.success,.error { padding:12px 18px; border-radius:8px; margin-bottom:20px; text-align:center; font-weight:500; }
.success { background:#d4edda; color:#155724; border:1px solid #c3e6cb; }
.error { background:#f8d7da; color:#721c24; border:1px solid #f5c6cb; }

/* existing images */
.existing-images { display:flex; gap:15px; flex-wrap:wrap; margin-bottom:20px; }
.existing-images .img-box { position:relative; width:130px; height:90px; border:1px solid #ccc; border-radius:8px; overflow:hidden; background:#f8f9fa; transition:.3s; }
.existing-images .img-box img { width:100%; height:100%; object-fit:cover; }
.existing-images .img-box .delete-img { position:absolute; top:-8px; right:-8px; background:#dc3545; color:#fff; border:none; border-radius:50%; width:24px; height:24px; cursor:pointer; font-weight:bold; font-size:16px; display:flex; align-items:center; justify-content:center; }
.existing-images .img-box .delete-img:hover { background:#a71d2a; }

/* departments table */
.department-card { background:#f8fafc; padding:15px; border-radius:10px; display:flex; align-items:center; gap:15px; margin-bottom:20px; box-shadow:0 4px 15px rgba(0,0,0,0.08); }
.department-card img { width:120px; height:80px; object-fit:cover; border-radius:8px; }
.department-card .info { flex:1; }
.department-card .actions a { padding:6px 12px; border-radius:6px; text-decoration:none; text-align:center; font-weight:bold; color:#fff; margin-right:5px; }
.department-card .actions a.edit { background:#007bff; }
.department-card .actions a.edit:hover { background:#0056b3; }
.department-card .actions a.delete { background:#dc3545; }
.department-card .actions a.delete:hover { background:#a71d2a; }

@media(max-width:900px){ .department-card{flex-direction:column;align-items:flex-start;} .department-card img{width:100%;height:auto;} button{width:100%;} .existing-images .img-box{width:100px;height:70px;} }
</style>
</head>
<body>

<div class="container">
<h2><?= $editing ? "Edit Department" : "Add New Department" ?></h2>

<?php if($success): ?><div class="success"><?= $success ?></div><?php endif; ?>
<?php if($error): ?><div class="error"><?= $error ?></div><?php endif; ?>

<form method="POST" enctype="multipart/form-data">
<label>Department Name:</label>
<input type="text" name="name" value="<?= $editing ? htmlspecialchars($dept['name']) : '' ?>" required>

<label>Description:</label>
<textarea name="description" id="description"><?= $editing ? $dept['description'] : '' ?></textarea>

<?php if($editing):
    $imagesQ = $conn->query("SELECT * FROM department_images WHERE department_id=".$dept['id']);
    if($imagesQ->num_rows):
?>
<div class="existing-images">
<?php while($img=$imagesQ->fetch_assoc()): ?>
<div class="img-box">
<img src="../<?= $img['image_path'] ?>" alt="Department Image">
<a class="delete-img" href="?edit=<?= $dept['id'] ?>&delete_img=<?= $img['id'] ?>" onclick="return confirm('Delete this image?')">&times;</a>
</div>
<?php endwhile; ?>
</div>
<?php endif; endif; ?>

<label>Upload New Images:</label>
<input type="file" name="images[]" multiple accept="image/*">

<button type="submit"><?= $editing ? "Update Department" : "Add Department" ?></button>
</form>

<h2>Existing Departments</h2>
<?php
$departments=$conn->query("SELECT * FROM departments ORDER BY id DESC");
while($d=$departments->fetch_assoc()):
    $imgQ=$conn->query("SELECT image_path FROM department_images WHERE department_id=".$d['id']." ORDER BY id ASC LIMIT 1");
    $img=$imgQ->num_rows?$imgQ->fetch_assoc()['image_path']:'uploads/departments/default.jpg';
?>
<div class="department-card">
    <img src="../<?= $img ?>" alt="<?= htmlspecialchars($d['name']) ?>">
    <div class="info">
        <h3><?= htmlspecialchars($d['name']) ?></h3>
        <p><?= substr(strip_tags($d['description']),0,120) ?>...</p>
    </div>
    <div class="actions">
        <a href="?edit=<?= $d['id'] ?>" class="edit">Edit</a>
        <a href="?delete=<?= $d['id'] ?>" class="delete" onclick="return confirm('Are you sure you want to delete this department?')">Delete</a>
    </div>
</div>
<?php endwhile; ?>

</div>
</body>
</html>
