<?php
session_start();
require_once __DIR__ . "/../config/db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

if (!isset($_GET['id'])) {
    die("Invalid request");
}

$id = intval($_GET['id']);

/* ===============================
   FETCH DATA
=================================*/
$stmt = mysqli_prepare($conn, "SELECT * FROM equipment WHERE id=?");
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if (mysqli_num_rows($result) == 0) {
    die("Equipment not found");
}

$data = mysqli_fetch_assoc($result);

/* ===============================
   UPDATE
=================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $name = $_POST['equipment_name'];
    $serial = $_POST['serial_number'];
    $category = $_POST['category'];
    $location = $_POST['location'];
    $status = $_POST['status'];
    $department_id = $_POST['department_id'];
    $purchase = $_POST['purchase_date'] ?: NULL;
    $next_due = !empty($_POST['next_due_date'])
    ? date("Y-m-d H:i:s", strtotime($_POST['next_due_date']))
    : NULL;
    $description = $_POST['description'];

    if (strpos($category, "Other_") === 0 && !empty($_POST['other_category'])) {
        $category = $_POST['other_category'];
    }

    /* IMAGE */
    $imageName = $data['image'];

    if (!empty($_FILES['equipment_image']['name'])) {
        $targetDir = "../assets/uploads/";
        $imageName = time() . "_" . basename($_FILES["equipment_image"]["name"]);

if (!empty($_FILES['equipment_image']['name'])) {

    $targetDir = __DIR__ . "/../assets/uploads/";

    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $imageName = time() . "_" . basename($_FILES["equipment_image"]["name"]);
    $targetFile = $targetDir . $imageName;

    if (move_uploaded_file($_FILES["equipment_image"]["tmp_name"], $targetFile)) {
        // success
    } else {
        die("Failed to upload image.");
    }
}    }

    $sql = "UPDATE equipment 
            SET equipment_name=?, serial_number=?, category=?, location=?, status=?, 
                department_id=?, purchase_date=?, next_due_date=?, description=?, image=? 
            WHERE id=?";

    $stmt = mysqli_prepare($conn, $sql);

    mysqli_stmt_bind_param($stmt, "sssssissssi",
        $name,
        $serial,
        $category,
        $location,
        $status,
        $department_id,
        $purchase,
        $next_due,
        $description,
        $imageName,
        $id
    );

    mysqli_stmt_execute($stmt);

    header("Location: ../items.php?updated=1");
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Equipment</title>
    <link rel="stylesheet" href="../assets/style.css">

    <style>
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full {
            grid-column: span 2;
        }

        .form-group label {
            font-weight: 600;
            margin-bottom: 6px;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
        }

        .form-group textarea {
            min-height: 100px;
            resize: vertical;
        }

        .image-preview {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .image-preview img {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 10px;
            border: 1px solid #ccc;
        }

        .box {
            max-width: 900px;
            margin: auto;
        }

        .modal-actions {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        @media(max-width: 768px) {
            .form-grid {
                grid-template-columns: 1fr;
            }

            .form-group.full {
                grid-column: span 1;
            }
        }
    </style>
</head>

<body>

<?php include __DIR__ . '/../includes/sidebar.php'; ?>

<div class="main">

    <div class="page-header">
        <div>
            <h1>Edit Equipment</h1>
            <p>Update equipment details.</p>
        </div>
    </div>

    <div class="box">

        <form method="POST" enctype="multipart/form-data">

            <div class="form-grid">

                <div class="form-group">
                    <label>Equipment Name *</label>
                    <input name="equipment_name" value="<?= htmlspecialchars($data['equipment_name']) ?>" required>
                </div>

                <div class="form-group">
                    <label>Serial Number *</label>
                    <input name="serial_number" value="<?= htmlspecialchars($data['serial_number']) ?>" required>
                </div>

                <div class="form-group">
                    <label>Category *</label>
                    <select name="category" id="categorySelect" onchange="toggleOtherCategory()" required>
                        <option value="<?= htmlspecialchars($data['category']) ?>">
                            Current: <?= htmlspecialchars($data['category']) ?>
                        </option>

                        <optgroup label="Biomedical Engineering">
                            <option value="Ventilator">Ventilator</option>
                            <option value="ECG Machine">ECG Machine</option>
                            <option value="Infusion Pump">Infusion Pump</option>
                            <option value="Defibrillator">Defibrillator</option>
                            <option value="Patient Monitor">Patient Monitor</option>
                            <option value="Other_Biomedical_Engineering">Others</option>
                        </optgroup>
                    </select>
                </div>

                <div class="form-group" id="otherCategoryBox" style="display:none;">
                    <label>Specify Category</label>
                    <input type="text" name="other_category" id="otherCategoryInput">
                </div>

                <div class="form-group">
                    <label>Location *</label>
                    <input name="location" value="<?= htmlspecialchars($data['location']) ?>" required>
                </div>

                <div class="form-group">
                    <label>Status *</label>
                    <select name="status" required>
                        <option value="Active" <?= $data['status']=="Active"?'selected':'' ?>>Active</option>
                        <option value="Under Maintenance" <?= $data['status']=="Under Maintenance"?'selected':'' ?>>Under Maintenance</option>
                        <option value="Inactive" <?= $data['status']=="Inactive"?'selected':'' ?>>Inactive</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Department *</label>
                    <select name="department_id" required>
                        <?php
                        $deptQuery = mysqli_query($conn, "SELECT id, name FROM departments ORDER BY name ASC");
                        while ($dept = mysqli_fetch_assoc($deptQuery)) {
                            $selected = ($data['department_id'] == $dept['id']) ? 'selected' : '';
                            echo "<option value='{$dept['id']}' $selected>" . htmlspecialchars($dept['name']) . "</option>";
                        }
                        ?>
                    </select>
                </div>

                <div class="form-group">
                    <label>Purchase Date</label>
                    <input type="date" name="purchase_date" value="<?= $data['purchase_date'] ?>">
                </div>

                <div class="form-group">
                    <label>Next Due Date</label>
                    <input 
    type="datetime-local" 
    name="next_due_date" 
    value="<?= !empty($data['next_due_date']) ? date('Y-m-d\TH:i', strtotime($data['next_due_date'])) : '' ?>"
>
                </div>

                <div class="form-group full">
                    <label>Description</label>
                    <textarea name="description"><?= htmlspecialchars($data['description']) ?></textarea>
                </div>

                <div class="form-group full">
                    <label>Image</label>

                    <div class="image-preview">
                        <?php if(!empty($data['image'])): ?>
                            <img src="../assets/uploads/<?= $data['image'] ?>">
                        <?php else: ?>
                            <span>No image</span>
                        <?php endif; ?>

                        <input type="file" name="equipment_image">
                    </div>
                </div>

            </div>

            <div class="modal-actions">
                <a href="../items.php" class="btn cancel">Cancel</a>
                <button type="submit" class="btn primary">Update Equipment</button>
            </div>

        </form>

    </div>

</div>

<script>
function toggleOtherCategory(){
    let val = document.getElementById("categorySelect").value;
    let box = document.getElementById("otherCategoryBox");

    if(val.startsWith("Other_")){
        box.style.display = "block";
    } else {
        box.style.display = "none";
    }
}
</script>

</body>
</html>