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

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']);

    $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");
    }

    $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
    )");

    $target_dir = "../../../files/";
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0755, true);
    }

    $saveUploadedImages = function ($files, $target_dir) {
        $saved = [];
        if (empty($files) || empty($files['name'])) {
            return $saved;
        }
        $names = $files['name'];
        $tmps = $files['tmp_name'];
        $errors = $files['error'] ?? [];
        $count = is_array($names) ? count($names) : 1;
        for ($i = 0; $i < $count; $i++) {
            $name = is_array($names) ? ($names[$i] ?? '') : $names;
            $tmp = is_array($tmps) ? ($tmps[$i] ?? '') : $tmps;
            $err = is_array($errors) ? ($errors[$i] ?? UPLOAD_ERR_OK) : $errors;
            if ($err !== UPLOAD_ERR_OK || !$name || !$tmp) {
                continue;
            }
            $base = pathinfo($name, PATHINFO_FILENAME);
            $ext = pathinfo($name, PATHINFO_EXTENSION);
            $safeBase = preg_replace('/[^a-zA-Z0-9._-]/', '_', $base);
            $fileName = time() . "_" . bin2hex(random_bytes(4)) . "_" . $safeBase;
            if ($ext) {
                $fileName .= "." . $ext;
            }
            $target_file = $target_dir . $fileName;
            if (move_uploaded_file($tmp, $target_file)) {
                $saved[] = "files/" . $fileName;
            }
        }
        return $saved;
    };

    $images = $saveUploadedImages($_FILES['images'] ?? null, $target_dir);

    $mainImage = $images[0] ?? '';

    $conn->query("INSERT INTO projects (title, description, image, status, type) 
                  VALUES ('$title', '$description', '$mainImage', '$status', '$type')");
    $projectId = $conn->insert_id;

    foreach ($images as $img) {
        $imgEsc = mysqli_real_escape_string($conn, $img);
        $conn->query("INSERT INTO project_images (project_id, image) VALUES ($projectId, '$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;">Add Project</h2>
    <a href="projects.php" style="display:inline-block; padding:10px 20px; background:#f0f0f0; color:#333; text-decoration:none; border-radius:6px; font-weight:500; transition:0.3s;">
        <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" placeholder="Enter project title" required>
    </div>

    <div class="mb-3">
        <label class="form-label">Project Description</label>
        <textarea name="description" class="form-control" placeholder="Enter project description" rows="5" required></textarea>
    </div>

    <div class="mb-3">
        <label class="form-label">Project Images (3-4)</label>
        <input type="file" id="project-images" name="images[]" class="form-control" accept="image/*" multiple required>
        <small class="text-muted">You can select multiple images at once.</small>
        <div id="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">Civil</option>
            <option value="Decor">Decor</option>
        </select>
    </div>

    <div class="mb-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-control" required>
            <option value="completed">Completed</option>
            <option value="ongoing">Ongoing</option>
            <option value="planned">Planned</option>
        </select>
    </div>

    <button type="submit" class="btn btn-primary">Save Project</button>
</form>

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

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