<?php 
include "../../includes/db.php";
include "../../includes/auth.php";

$id = (int)$_GET['id'];
$project = $conn->query("SELECT * FROM projects WHERE id=$id")->fetch_assoc();

if (!$project) {
    header("Location: projects.php");
    exit;
}

$typeCol = $conn->query("SHOW COLUMNS FROM projects LIKE 'type'");
if (!$typeCol || $typeCol->num_rows == 0) {
    $conn->query("ALTER TABLE projects ADD COLUMN type VARCHAR(50) NOT NULL DEFAULT 'Civil' AFTER description");
    $project = $conn->query("SELECT * FROM projects WHERE id=$id")->fetch_assoc();
}

$conn->query("CREATE TABLE IF NOT EXISTS project_images (
    id INT PRIMARY KEY AUTO_INCREMENT,
    project_id INT NOT NULL,
    image VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

if ($_POST) {
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $status = $_POST['status'];
    $type = mysqli_real_escape_string($conn, $_POST['type']);
    
    $mainImage = $project['image'];
    $target_dir = "../../../files/";
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0755, true);
    }

    $newImages = [];
    if (!empty($_FILES['images']['name'][0])) {
        $count = count($_FILES['images']['name']);
        for ($i = 0; $i < $count; $i++) {
            $name = $_FILES['images']['name'][$i] ?? '';
            $tmp = $_FILES['images']['tmp_name'][$i] ?? '';
            if ($name && $tmp) {
                $fileName = time() . "_" . ($i + 1) . "_" . basename($name);
                $target_file = $target_dir . $fileName;
                if (move_uploaded_file($tmp, $target_file)) {
                    $newImages[] = "files/" . $fileName;
                }
            }
        }
    }

    if (!empty($newImages)) {
        $mainImage = $newImages[0];
    }

    $conn->query("UPDATE projects SET 
                  title='$title', 
                  description='$description', 
                  image='$mainImage',
                  status='$status',
                  type='$type'
                  WHERE id=$id");

    foreach ($newImages as $img) {
        $imgEsc = mysqli_real_escape_string($conn, $img);
        $conn->query("INSERT INTO project_images (project_id, image) VALUES ($id, '$imgEsc')");
    }

    header("Location: projects.php");
    exit;
}

include "../../includes/header.php"; 
include "../../includes/sidebar.php"; 
?>

<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:30px; padding-bottom:15px; border-bottom:2px solid #f0f0f0;">
    <h2 class="page-title" style="margin:0;">Edit Project</h2>
    <a href="projects.php" class="btn btn-secondary">
        <i class="fas fa-arrow-left"></i> Back to Projects
    </a>
</div>

<form method="post" enctype="multipart/form-data" class="bg-white p-4 rounded">
    <div class="mb-3">
        <label class="form-label">Project Title</label>
        <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($project['title']) ?>" required>
    </div>

    <div class="mb-3">
        <label class="form-label">Project Description</label>
        <textarea name="description" class="form-control" rows="5" required><?= htmlspecialchars($project['description']) ?></textarea>
    </div>

    <div class="mb-3">
        <label class="form-label">Project Images (3-4)</label>
        <?php if (!empty($project['image'])): ?>
            <div class="mb-2">
                <img src="/firstchoice_admin/<?= ltrim($project['image'], '/') ?>" width="100" alt="Project Image" style="object-fit:cover;border-radius:6px;">
            </div>
        <?php endif; ?>
        <?php
        $gallery = $conn->query("SELECT image FROM project_images WHERE project_id=$id ORDER BY id DESC");
        if ($gallery && $gallery->num_rows > 0):
        ?>
            <div class="d-flex flex-wrap gap-2 mb-2">
                <?php while ($g = $gallery->fetch_assoc()): ?>
                    <img src="/firstchoice_admin/<?= ltrim($g['image'], '/') ?>" width="70" height="70" style="object-fit:cover;border-radius:6px;">
                <?php endwhile; ?>
            </div>
        <?php endif; ?>
        <input type="file" id="edit-project-images" name="images[]" class="form-control" accept="image/*" multiple>
        <small class="text-muted">Leave empty to keep current images. New uploads add more images and set the first as main.</small>
        <div id="edit-selected-images" class="small text-muted mt-1"></div>
    </div>

    <div class="mb-3">
        <label class="form-label">Project Type</label>
        <select name="type" class="form-control" required>
            <option value="Civil" <?= ($project['type'] ?? 'Civil') == 'Civil' ? 'selected' : '' ?>>Civil</option>
            <option value="Decor" <?= ($project['type'] ?? '') == 'Decor' ? 'selected' : '' ?>>Decor</option>
        </select>
    </div>

    <div class="mb-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-control" required>
            <option value="completed" <?= $project['status'] == 'completed' ? 'selected' : '' ?>>Completed</option>
            <option value="ongoing" <?= $project['status'] == 'ongoing' ? 'selected' : '' ?>>Ongoing</option>
            <option value="planned" <?= $project['status'] == 'planned' ? 'selected' : '' ?>>Planned</option>
        </select>
    </div>

    <button type="submit" class="btn btn-primary">Update Project</button>
    <a href="projects.php" class="btn btn-secondary">Cancel</a>
</form>

<script>
document.getElementById('edit-project-images').addEventListener('change', function(e) {
    var container = document.getElementById('edit-selected-images');
    container.innerHTML = '';
    if (this.files && this.files.length > 0) {
        var count = this.files.length;
        container.innerHTML = count + ' new image(s) selected';
    }
});
</script>

<?php include "../../includes/footer.php"; ?>
