<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: index");
    exit;
}
require_once 'db.php';

// Verify role-based access
checkAccess();

$user_name = isset($_SESSION['user_name']) ? $_SESSION['user_name'] : 'Admin User';

// Verify project access if project_id is provided via GET (for direct links)
if (isset($_GET['project_id'])) {
    verifyProjectAccess($_GET['project_id'], $conn);
}

// Handle set project
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['set_project'])) {
    header('Content-Type: application/json');
    
    // Verify project belongs to user before setting
    verifyProjectAccess($_POST['project_id'], $conn);
    
    $_SESSION['project_id'] = $_POST['project_id'];
    echo json_encode(['success' => true]);
    exit;
}

// Clear project session on page load to start fresh every time
// Only clear if this is NOT an AJAX request
if (!isset($_GET['fetch_images']) && !isset($_POST['set_project']) && !isset($_FILES['imageFile']) && !isset($_POST['action'])) {
    unset($_SESSION['project_id']);
}

// Handle fetch images
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['fetch_images'])) {
    header('Content-Type: application/json');
    $imagesByType = ['2d' => [], '3d' => [], 'final' => []];
    $latestImages = ['2d' => null, '3d' => null, 'final' => null];
    
    if (isset($_SESSION['project_id'])) {
        // Get all images for file list
        $stmt = $conn->prepare("SELECT * FROM design_images WHERE project_id = ? ORDER BY uploaded_at DESC");
        $stmt->bind_param('i', $_SESSION['project_id']);
        $stmt->execute();
        $result = $stmt->get_result();
        $images = $result->fetch_all(MYSQLI_ASSOC);
        foreach ($images as $img) {
            $imagesByType[$img['image_type']][] = $img;
        }
        
        // Get latest image for 2D (ORDER BY id DESC LIMIT 1)
        $stmt = $conn->prepare("SELECT * FROM design_images WHERE project_id = ? AND image_type = '2d' ORDER BY id DESC LIMIT 1");
        $stmt->bind_param('i', $_SESSION['project_id']);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $latestImages['2d'] = $row;
        }
        
        // Get latest image for 3D (ORDER BY id DESC LIMIT 1)
        $stmt = $conn->prepare("SELECT * FROM design_images WHERE project_id = ? AND image_type = '3d' ORDER BY id DESC LIMIT 1");
        $stmt->bind_param('i', $_SESSION['project_id']);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $latestImages['3d'] = $row;
        }
        
        // Get final image (only one allowed)
        $stmt = $conn->prepare("SELECT * FROM design_images WHERE project_id = ? AND image_type = 'final' ORDER BY id DESC LIMIT 1");
        $stmt->bind_param('i', $_SESSION['project_id']);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $latestImages['final'] = $row;
        }
    }
    
    echo json_encode([
        'all_images' => $imagesByType,
        'latest_images' => $latestImages
    ]);
    exit;
}

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['imageFile'])) {
    header('Content-Type: application/json');
    if (!isset($_SESSION['project_id'])) {
        echo json_encode(['success' => false, 'message' => 'No project selected']);
        exit;
    }
    $project_id = $_SESSION['project_id'];
    $imageType = $_POST['imageType'];
    
    // Validation for final: only one allowed
    if ($imageType === 'final') {
        $check = $conn->prepare("SELECT id FROM design_images WHERE project_id = ? AND image_type = 'final'");
        $check->bind_param('i', $project_id);
        $check->execute();
        if ($check->get_result()->num_rows > 0) {
            echo json_encode(['success' => false, 'message' => 'Only one final image allowed per project']);
            exit;
        }
        // For final, only allow one file
        if (count($_FILES['imageFile']['name']) > 1) {
            echo json_encode(['success' => false, 'message' => 'Only one final image allowed']);
            exit;
        }
    }
    
    $uploadDir = 'uploads/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
    
    $uploaded = [];
    foreach ($_FILES['imageFile']['tmp_name'] as $key => $tmp_name) {
        if ($tmp_name) {
            $fileName = uniqid() . '-' . basename($_FILES['imageFile']['name'][$key]);
            $filePath = $uploadDir . $fileName;
            
            if (move_uploaded_file($tmp_name, $filePath)) {
                $stmt = $conn->prepare("INSERT INTO design_images (project_id, image_type, file_name, file_path, file_size) VALUES (?, ?, ?, ?, ?)");
                $stmt->bind_param('isssi', $project_id, $imageType, $fileName, $filePath, $_FILES['imageFile']['size'][$key]);
                $stmt->execute();
                $uploaded[] = ['name' => $fileName, 'path' => $filePath, 'id' => $conn->insert_id];
            }
        }
    }
    echo json_encode(['success' => true, 'files' => $uploaded]);
    exit;
}

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    header('Content-Type: application/json');
    
    // Fetch file path first to delete the physical file
    $stmt = $conn->prepare("SELECT file_path FROM design_images WHERE id = ?");
    $stmt->bind_param('i', $_POST['id']);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        if (!empty($row['file_path']) && file_exists($row['file_path'])) {
            unlink($row['file_path']);
        }
    }

    $stmt = $conn->prepare("DELETE FROM design_images WHERE id=?");
    $stmt->bind_param('i', $_POST['id']);
    $stmt->execute();
    echo json_encode(['success' => true]);
    exit;
}

// Fetch projects - Only show projects belonging to the logged-in user
$projects = getUserProjects($conn);

// Fetch current project details if session is set
$currentProject = null;
if (isset($_SESSION['project_id'])) {
    $stmt = $conn->prepare("SELECT p.id, p.project_name, c.client_name FROM projects p JOIN clients c ON p.client_id = c.id WHERE p.id = ?");
    if (!$stmt) die("DB prepare error");

    $stmt->bind_param('i', $_SESSION['project_id']);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows > 0) {
        $currentProject = $res->fetch_assoc();
    }
}

// Fetch images
$imagesByType = ['2d' => [], '3d' => [], 'final' => []];
$latestImages = ['2d' => null, '3d' => null, 'final' => null];
if (isset($_SESSION['project_id'])) {
    $stmt = $conn->prepare("SELECT * FROM design_images WHERE project_id = ? ORDER BY uploaded_at DESC");
    $stmt->bind_param('i', $_SESSION['project_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    $images = $result->fetch_all(MYSQLI_ASSOC);
    foreach ($images as $img) {
        $imagesByType[$img['image_type']][] = $img;
    }
    
    // Get latest 2D image
    $stmt = $conn->prepare("SELECT * FROM design_images WHERE project_id = ? AND image_type = '2d' ORDER BY id DESC LIMIT 1");
    $stmt->bind_param('i', $_SESSION['project_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        $latestImages['2d'] = $row;
    }
    
    // Get latest 3D image
    $stmt = $conn->prepare("SELECT * FROM design_images WHERE project_id = ? AND image_type = '3d' ORDER BY id DESC LIMIT 1");
    $stmt->bind_param('i', $_SESSION['project_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        $latestImages['3d'] = $row;
    }
    
    // Get final image
    $stmt = $conn->prepare("SELECT * FROM design_images WHERE project_id = ? AND image_type = 'final' ORDER BY id DESC LIMIT 1");
    $stmt->bind_param('i', $_SESSION['project_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        $latestImages['final'] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Project Window - ConstructCRM</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
    :root {
        --primary-color: #977C49;
        --primary-dark: #7a633a;
        --primary-light: #f8f5ef;
        --secondary-color: #343a40;
        --secondary-light: #f8f9fa;
        --success-color: #28a745;
        --info-color: #17a2b8;
        --warning-color: #ffc107;
        --danger-color: #dc3545;
        --light-color: #f8f9fa;
        --dark-color: #343a40;
        --sidebar-width: 320px;
        --nav-width: 260px;
        --header-height: 70px;
    --border-radius: 12px;
    --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        --transition: all 0.3s ease;
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Inter', sans-serif;
        background-color: #f5f7fa;
        color: #333;
        font-size: 14px;
        line-height: 1.4;
        overflow-x: hidden;
    }

    /* Header */
    .header {
        background-color: #fff;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: var(--header-height);
        z-index: 1000;
        display: flex;
        align-items: center;
        padding: 0 20px;
    }

    .logo {
        display: flex;
        align-items: center;
        font-weight: 700;
        font-size: 20px;
        color: var(--primary-color);
        text-decoration: none;
    }

    .logo i {
        font-size: 24px;
        margin-right: 10px;
    }

    .header-actions {
        margin-left: auto;
        display: flex;
        align-items: center;
    }

    .mobile-menu-toggle {
        display: none;
        background: none;
        border: none;
        font-size: 24px;
        color: var(--primary-color);
        margin-right: 15px;
        cursor: pointer;
    }

    /* User Dropdown */
    .user-dropdown {
        position: relative;
    }

    .user-profile {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 5px 10px;
        border-radius: var(--border-radius);
        transition: var(--transition);
    }

    .user-profile:hover {
        background-color: #f8f9fa;
    }

    .user-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background-color: var(--primary-color);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        margin-right: 10px;
    }

    .user-name {
        font-weight: 500;
        margin-right: 5px;
    }

    .dropdown-arrow {
        font-size: 12px;
        color: #666;
        transition: var(--transition);
    }

    .user-dropdown.show .dropdown-arrow {
        transform: rotate(180deg);
    }

    .user-dropdown-menu {
        position: absolute;
        top: 100%;
        right: 0;
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        min-width: 180px;
        padding: 8px 0;
        margin-top: 5px;
        opacity: 0;
        visibility: hidden;
        transform: translateY(-10px);
        transition: var(--transition);
        z-index: 1001;
    }

    .user-dropdown.show .user-dropdown-menu {
        opacity: 1;
        visibility: visible;
        transform: translateY(0);
    }

    .dropdown-item {
        display: flex;
        align-items: center;
        padding: 10px 20px;
        color: #555;
        text-decoration: none;
        transition: var(--transition);
    }

    .dropdown-item:hover {
        background-color: #f8f9fa;
        color: var(--primary-color);
    }

    .dropdown-item i {
        margin-right: 10px;
        font-size: 16px;
    }

    .dropdown-divider {
        height: 1px;
        background-color: #eee;
        margin: 8px 0;
    }

    /* Main Layout */
    .main-container {
        display: flex;
        min-height: calc(100vh - var(--header-height));
        margin-top: var(--header-height);
    }

    /* Sidebar Navigation */
    .sidebar-nav {
        width: var(--nav-width);
        background-color: #fff;
        box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
        position: fixed;
        top: var(--header-height);
        left: 0;
        bottom: 0;
        z-index: 999;
        overflow-y: auto;
        transition: var(--transition);
    }

    .nav-section {
        padding: 15px 0;
    }

    .nav-section:last-child {
        padding-bottom: 20px;
    }

    .nav-title {
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #999;
        padding: 0 20px;
        margin-bottom: 10px;
    }

    .nav-list {
        list-style: none;
    }

    .nav-item {
        margin-bottom: 5px;
    }

    .nav-link {
        display: flex;
        align-items: center;
        padding: 12px 20px;
        color: #555;
        text-decoration: none;
        font-weight: 500;
        transition: var(--transition);
        position: relative;
    }

    .nav-link i {
        font-size: 18px;
        margin-right: 12px;
        width: 20px;
        text-align: center;
    }

    .nav-link:hover {
        background-color: rgba(151, 124, 73, 0.05);
        color: var(--primary-color);
    }

    .nav-link.active {
        background-color: rgba(151, 124, 73, 0.1);
        color: var(--primary-color);
    }

    .nav-link.active::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background-color: var(--primary-color);
    }

    /* Content Wrapper */
    .content-wrapper {
        flex: 1;
        margin-left: var(--nav-width);
        display: flex;
        flex-direction: column;
        transition: var(--transition);
    }

    .content-header {
        background-color: #fff;
        padding: 20px 30px;
        border-bottom: 1px solid #eee;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .page-title {
        font-size: 24px;
        font-weight: 600;
        color: #333;
    }

    .breadcrumb {
        background-color: transparent;
        padding: 0;
        margin: 0;
        font-size: 13px;
    }

    .breadcrumb-item {
        color: #999;
    }

    .breadcrumb-item a {
        color: #999;
        text-decoration: none;
        transition: var(--transition);
    }

    .breadcrumb-item a:hover {
        color: var(--primary-color);
    }

    .breadcrumb-item.active {
        color: var(--primary-color);
    }

    .breadcrumb-item + .breadcrumb-item::before {
        content: "›";
        color: #ccc;
    }

    /* Main Content */
    .main-content {
        flex: 1;
        padding: 30px;
        overflow-y: auto;
    }

    /* Project Info Card */
    .project-info-card {
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        margin-bottom: 30px;
        overflow: hidden;
    }

    .project-info-header {
        background-color: var(--primary-color);
        color: white;
        padding: 15px 20px;
        font-weight: 600;
        font-size: 18px;
    }

    .project-info-body {
        padding: 30px;
        display: flex;
        align-items: center;
    }

    .project-name {
        font-size: 16px;
        font-weight: 500;
    }

    .project-id {
        margin-left: auto;
        background-color: var(--primary-light);
        color: var(--primary-color);
        padding: 5px 10px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    /* Image Upload Sections */
    .image-sections {
        display: flex;
        gap: 30px;
        flex-wrap: wrap;
    }

    .image-section {
        flex: 1;
        min-width: 300px;
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }

    .section-header {
        padding: 15px 20px;
        border-bottom: 1px solid #eee;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        display: flex;
        align-items: center;
    }

    .section-title i {
        color: var(--primary-color);
        margin-right: 10px;
        font-size: 18px;
    }

    .section-badge {
        background-color: var(--primary-light);
        color: var(--primary-color);
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 11px;
        font-weight: 500;
    }

    .section-body {
        padding: 20px;
        display: flex;
        flex-direction: column;
        flex-grow: 1;
    }

    /* Image Preview */
    .image-preview {
        height: 200px;
        border: 2px dashed #ddd;
        border-radius: var(--border-radius);
        background-color: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-weight: 500;
        margin-bottom: 20px;
        overflow: hidden;
        position: relative;
    }

    .image-preview img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
    }

    /* Download buttons for image items */
    .download-btn {
        background: rgba(151, 124, 73, 0.08);
        color: var(--primary-dark);
        border: 1px solid rgba(151, 124, 73, 0.25);
        border-radius: 10px;
        padding: 8px 12px;
        font-weight: 600;
        font-size: 13px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        transition: var(--transition);
        cursor: pointer;
        user-select: none;
        white-space: nowrap;
    }

    .download-btn i {
        font-size: 16px;
    }

    .download-btn:hover {
        background: rgba(151, 124, 73, 0.14);
        border-color: rgba(151, 124, 73, 0.45);
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(151, 124, 73, 0.18);
    }

    .download-btn:active {
        transform: translateY(-1px);
    }

    .download-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        box-shadow: none;
        transform: none;
    }

    .download-btn.loading {
        cursor: progress;
        position: relative;
        pointer-events: none;
        opacity: 0.85;
    }

    .download-btn.loading::after {
        content: '';
        width: 14px;
        height: 14px;
        border: 2px solid rgba(151, 124, 73, 0.35);
        border-top-color: var(--primary-color);
        border-radius: 50%;
        position: absolute;
        right: 10px;
        animation: bb-spin 0.8s linear infinite;
    }

    @keyframes bb-spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }

    /* Keep file list card height consistent (preview images vary in size) */
    .file-list-item {
        min-height: 44px;
    }

    @media (max-width: 576px) {
        .download-btn {
            padding: 8px 10px;
            font-size: 12px;
            gap: 6px;
        }
    }


    /* Upload Form */
    .upload-form {
        margin-bottom: 20px;
    }

    .form-label {
        font-weight: 600;
        color: var(--dark-color);
        margin-bottom: 10px;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .form-label i {
        color: var(--primary-color);
        font-size: 16px;
    }

    .form-control, .form-select {
        border: 2px solid #e9ecef;
        border-radius: var(--border-radius);
        padding: 12px 16px;
        font-size: 14px;
        transition: var(--transition);
        background: #fff;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 4px rgba(151, 124, 73, 0.1);
        outline: none;
        transform: translateY(-2px);
    }

    .form-control:hover, .form-select:hover {
        border-color: #d6d6d6;
    }
    
    .form-select {
        border: 2px solid #e9ecef;
        border-radius: var(--border-radius);
        padding: 12px 16px;
        font-size: 14px;
        transition: var(--transition);
        background: #fff;
    }

    .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 4px rgba(151, 124, 73, 0.1);
        outline: none;
        transform: translateY(-2px);
    }

    .btn {
        border-radius: var(--border-radius);
        font-weight: 600;
        padding: 12px 24px;
        font-size: 14px;
        transition: var(--transition);
        cursor: pointer;
        border: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-primary {
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        box-shadow: 0 4px 12px rgba(151, 124, 73, 0.3);
    }

    .btn-primary:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(151, 124, 73, 0.4);
    }

    .btn-primary:active {
        transform: translateY(-1px);
    }

    .btn-primary:disabled {
        background-color: #aaa;
        border-color: #aaa;
        transform: none;
        box-shadow: none;
    }

    /* File List */
    .file-list-container {
        margin-top: 20px;
        flex-grow: 1;
        overflow-y: auto;
    }

    .file-list-header {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        margin-bottom: 10px;
        padding-bottom: 5px;
        border-bottom: 1px solid #eee;
    }

    .file-list {
        list-style: none;
    }

    .file-list-item {
        padding: 10px;
        margin-bottom: 5px;
        border-radius: var(--border-radius);
        transition: var(--transition);
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;
    }

    .file-list-item:hover {
        background-color: #f8f9fa;
    }

    .file-list-item.active {
        background-color: var(--primary-light);
        border-left: 3px solid var(--primary-color);
    }

    .file-name {
        flex-grow: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        padding-right: 10px;
    }

    .file-actions {
        display: flex;
        align-items: center;
    }

    .delete-btn {
        background: none;
        border: none;
        color: #999;
        cursor: pointer;
        padding: 5px;
        border-radius: var(--border-radius);
        transition: var(--transition);
        display: none;
    }

    .file-list-item:hover .delete-btn,
    .file-list-item.active .delete-btn {
        display: block;
    }

    .delete-btn:hover {
        color: var(--danger-color);
        background-color: rgba(220, 53, 69, 0.1);
    }

    .file-list-item.active .delete-btn {
        color: white;
    }

    .file-list-item.active .delete-btn:hover {
        background-color: rgba(255, 255, 255, 0.2);
    }

    /* Status Messages */
    .upload-status {
        margin-top: 10px;
        font-size: 13px;
        text-align: center;
    }

    .text-success {
        color: var(--success-color);
    }

    .text-danger {
        color: var(--danger-color);
    }

    .text-warning {
        color: var(--warning-color);
    }

    .empty-state {
        text-align: center;
        padding: 20px;
        color: #999;
        font-style: italic;
    }
    
    /* Alert Styles */
    .alert {
        border-radius: var(--border-radius);
        padding: 15px 20px;
        margin-bottom: 20px;
        border: none;
        display: flex;
        align-items: center;
    }
    
    .alert i {
        margin-right: 10px;
        font-size: 16px;
    }
    
    .alert-success {
        background-color: rgba(40, 167, 69, 0.1);
        color: var(--success-color);
        border-left: 4px solid var(--success-color);
    }

    /* Responsive */
    @media (max-width: 1200px) {
        .image-sections {
            flex-direction: column;
        }
    }

    @media (max-width: 768px) {
        .mobile-menu-toggle {
            display: block;
        }
        
        .sidebar-nav {
            transform: translateX(-100%);
            width: 280px;
            z-index: 1001;
        }
        
        .sidebar-nav.show {
            transform: translateX(0);
        }
        
        .content-wrapper {
            margin-left: 0;
        }

        .overlay {
            z-index: 1000;
        }

        .overlay.show {
            display: block;
        }

        .content-header {
            padding: 15px 20px;
            flex-direction: column;
            align-items: flex-start;
        }

        .page-title {
            font-size: 20px;
            margin-bottom: 10px;
        }

        .main-content {
            padding: 20px;
        }

        .header {
            padding: 0 15px;
        }

        .logo {
            font-size: 18px;
        }

        .logo i {
            font-size: 20px;
        }

        .user-name {
            display: none;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            font-size: 14px;
        }
    }
    /* Custom scrollbar */
    ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    ::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    ::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 4px;
    }

    ::-webkit-scrollbar-thumb:hover {
        background: #ccc;
    }
    /* Overlay for mobile menu */
    .overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 998;
    }

    .overlay.show {
        display: block;
    }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="header">
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="bi bi-list"></i>
        </button>
        <a href="crmdashboard" class="logo">
            <img src="./assets/logo.png" alt="ConstructCRM Logo" style="height: 60px; width: 85px;">
        </a>
        <div class="header-actions">
            <!-- User Dropdown -->
            <div class="user-dropdown" id="userDropdown">
                <div class="user-profile" id="userProfile">
                    <div class="user-avatar"><?php echo htmlspecialchars(strtoupper(substr($user_name, 0, 1))); ?></div>
                    <span class="user-name"><?php echo htmlspecialchars($user_name); ?></span>
                    <i class="bi bi-chevron-down dropdown-arrow"></i>
                </div>
                <div class="user-dropdown-menu">
                    <a href="profile" class="dropdown-item">
                        <i class="bi bi-person"></i>
                        <span>Profile</span>
                    </a>
                    <a href="settings" class="dropdown-item">
                        <i class="bi bi-gear"></i>
                        <span>Settings</span>
                    </a>
                    <div class="dropdown-divider"></div>
                    <a href="signin?logout=true" class="dropdown-item">
                        <i class="bi bi-box-arrow-right"></i>
                        <span>Logout</span>
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="main-container">
        <!-- Overlay for mobile -->
        <div class="overlay" id="overlay"></div>

        <!-- Sidebar Navigation -->
        <nav class="sidebar-nav" id="sidebarNav">
            <div class="nav-section">
                <div class="nav-title">Main</div>
                <ul class="nav-list">
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="crmdashboard" class="nav-link">
                            <i class="bi bi-speedometer2"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item">
                        <a href="dashboard" class="nav-link">
                            <i class="bi bi-grid-1x2-fill"></i>
                            <span>Client</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="projectlist" class="nav-link">
                            <i class="bi bi-list-ul"></i>
                            <span>Project List</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="designimages" class="nav-link active">
                            <i class="bi bi-palette-fill"></i>
                            <span>Design images</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="assignmentcalendar" class="nav-link">
                            <i class="bi bi-calendar-event-fill"></i>
                            <span>Assignment Calendar</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>place_order" class="nav-link">
                            <i class="bi bi-cart-check"></i> 
                            <span>Place Order</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="financetracker" class="nav-link">
                            <i class="bi bi-cash-stack"></i>
                            <span>Finance Tracker</span>
                        </a>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item">
                        <a href="imagepin" class="nav-link">
                            <i class="bi bi-pin-map-fill"></i>
                            <span>Image Pin & Comment</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="designcost" class="nav-link">
                            <i class="bi bi-palette-fill"></i>
                            <span>Designs Cost</span>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
            
            <div class="nav-section">
                <div class="nav-title">Management</div>
                <ul class="nav-list">
                    <li class="nav-item">
                        <a href="taskmanager" class="nav-link">
                            <i class="bi bi-check2-square"></i>
                            <span>Task Manager</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="users" class="nav-link">
                            <i class="bi bi-people-fill"></i>
                            <span>Users</span>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
            
            <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
            <div class="nav-section">
                <div class="nav-title">Vendor Management</div>
                <ul class="nav-list">
                    <li class="nav-item">
                        <a href="addvendors" class="nav-link">
                            <i class="bi bi-person-plus-fill"></i>
                            <span>Add New Vendor</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="viewvendors" class="nav-link">
                            <i class="bi bi-card-list"></i>
                            <span>View All Vendors</span>
                        </a>
                    </li>
                </ul>
            </div>
            <?php endif; ?>
        </nav>

        <!-- Content Wrapper -->
        <div class="content-wrapper">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="page-title">Design Images</h1>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item"><a href="#">Main</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Design Images</li>
                    </ol>
                </nav>
            </div>

            <!-- Main Content -->
            <div class="main-content">
                <!-- Project Selection -->
                <div class="project-info-card">
                    <div class="project-info-header">
                        <i class="bi bi-folder"></i> Select Project
                    </div>
                    <div class="project-info-body">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <label for="projectSelect" class="form-label">Choose Project:</label>
                                <select class="form-select" id="projectSelect" name="projectSelect">
                                    <option value="" <?php echo !$currentProject ? 'selected' : ''; ?> disabled>Select a project...</option>
                                    <?php foreach ($projects as $project): ?>
                                        <option value="<?php echo $project['id']; ?>" <?php echo ($currentProject && $currentProject['id'] == $project['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($project['project_name'] . ' - ' . $project['client_name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4 text-end">
                                <button class="btn btn-primary" id="loadProjectBtn" <?php echo !$currentProject ? 'disabled' : ''; ?> style="width: 200px;margin-top: 26px;">
                                    <i class="bi bi-arrow-right-circle"></i> Load Project
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Project Info Card -->
                <div class="project-info-card" id="selectedProjectInfo" style="display: <?php echo $currentProject ? 'block' : 'none'; ?>;">
                    <div class="project-info-header">
                        Project Information
                    </div>
                    <div class="project-info-body">
                        <div class="project-name"><?php echo $currentProject ? htmlspecialchars($currentProject['project_name'] . ' - ' . $currentProject['client_name']) : 'My Sample Project'; ?></div>
                        <div class="project-id"><?php echo $currentProject ? 'PRJ-' . str_pad($currentProject['id'], 3, '0', STR_PAD_LEFT) : 'PRJ-001'; ?></div>
                    </div>
                </div>

                <!-- Image Sections -->
                <div class="image-sections">
                    <!-- 2D Image Section -->
                    <div class="image-section">
                        <div class="section-header">
                            <div class="section-title">
                                <i class="bi bi-image"></i>
                                2D Images
                            </div>
                            <div class="section-badge">Design</div>
                        </div>
                        <div class="section-body">
                            <div class="image-preview" id="preview-container-2d">
                                <span>2D Image Preview</span>
                            </div>
                            
                            <form id="upload-form-2d" class="upload-form">
                                <label for="image-file-2d" class="form-label">Add Images to Project</label>
                                <input class="form-control" type="file" id="image-file-2d" name="imageFile[]" accept="image/png, image/jpeg" multiple required> 
                                <input type="hidden" name="imageType" value="2d"> 
                                <button type="submit" class="btn btn-primary w-100 mt-2">
                                    <i class="bi bi-upload"></i>
                                    Upload Selected Images
                                </button>
                            </form>
                            <div id="upload-status-2d" class="upload-status"></div>

                            <div class="file-list-container">
                                <div class="file-list-header">Uploaded 2D Files</div>
                                <ul id="file-list-2d" class="file-list">
                                    <li class="empty-state">No files uploaded yet.</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <!-- 3D Image Section -->
                    <div class="image-section">
                        <div class="section-header">
                            <div class="section-title">
                                <i class="bi bi-box"></i>
                                3D Models
                            </div>
                            <div class="section-badge">Design</div>
                        </div>
                        <div class="section-body">
                            <div class="image-preview" id="preview-container-3d">
                                <span>3D Model Preview</span>
                            </div>
                            
                            <form id="upload-form-3d" class="upload-form">
                                <label for="image-file-3d" class="form-label">Add Images to Project</label>
                                <input class="form-control" type="file" id="image-file-3d" name="imageFile[]" accept="image/png, image/jpeg" multiple required>
                                <input type="hidden" name="imageType" value="3d">
                                <button type="submit" class="btn btn-primary w-100 mt-2">
                                    <i class="bi bi-upload"></i>
                                    Upload Selected Images
                                </button>
                            </form>
                            <div id="upload-status-3d" class="upload-status"></div>
                            
                            <div class="file-list-container">
                                <div class="file-list-header">Uploaded 3D Files</div>
                                <ul id="file-list-3d" class="file-list">
                                    <li class="empty-state">No files uploaded yet.</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <!-- Final Image Section -->
                    <div class="image-section">
                        <div class="section-header">
                            <div class="section-title">
                                <i class="bi bi-check-circle"></i>
                                Final Images
                            </div>
                            <div class="section-badge">Output</div>
                        </div>
                        <div class="section-body">
                            <div class="image-preview" id="preview-container-final">
                                <span>Final Output Preview</span>
                            </div>
                            
                            <form id="upload-form-final" class="upload-form">
                                <label for="image-file-final" class="form-label">Add Image to Project</label>
                                <input class="form-control" type="file" id="image-file-final" name="imageFile[]" accept="image/png, image/jpeg" required>
                                <input type="hidden" name="imageType" value="final">
                                <button type="submit" class="btn btn-primary w-100 mt-2">
                                    <i class="bi bi-upload"></i>
                                    Upload Selected Image
                                </button>
                            </form>
                            <div id="upload-status-final" class="upload-status"></div>
                            
                            <div class="file-list-container">
                                <div class="file-list-header">Uploaded Final Files</div>
                                <ul id="file-list-final" class="file-list">
                                    <li class="empty-state">No files uploaded yet.</li>
                                </ul>
                                <div id="pin-tool-section" style="margin-top: 15px; display: none;">
                                    <button class="btn btn-primary btn-sm" id="openPinToolBtn">
                                        <i class="bi bi-pin-map"></i> Open in Pin Tool
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        document.addEventListener("DOMContentLoaded", () => {

            const uploadForms = document.querySelectorAll(".upload-form");
            const projectSelect = document.getElementById('projectSelect');
            const loadProjectBtn = document.getElementById('loadProjectBtn');
            const selectedProjectInfo = document.getElementById('selectedProjectInfo');

            // Enable/disable load button based on selection
            projectSelect.addEventListener('change', () => {
                loadProjectBtn.disabled = !projectSelect.value;
            });

            // Handle project loading
            loadProjectBtn.addEventListener('click', () => {
                const selectedValue = projectSelect.value;
                if (selectedValue) {
                    // Set project in session via AJAX
                    fetch('designimages.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'set_project=1&project_id=' + encodeURIComponent(selectedValue)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Update project info display
                            const projectNameEl = selectedProjectInfo.querySelector('.project-name');
                            const projectIdEl = selectedProjectInfo.querySelector('.project-id');

                            // Get project name from select option
                            const selectedOption = projectSelect.options[projectSelect.selectedIndex];
                            projectNameEl.textContent = selectedOption.text;
                            projectIdEl.textContent = 'PRJ-' + selectedValue.padStart(3, '0');

                            // Show project info card
                            selectedProjectInfo.style.display = 'block';

// Show success message
                            const tempMessage = document.createElement('div');
                            tempMessage.className = 'alert alert-success mt-3';
                            tempMessage.innerHTML = `<i class="bi bi-check-circle"></i> Project loaded successfully!`;
                            selectedProjectInfo.parentNode.insertBefore(tempMessage, selectedProjectInfo.nextSibling);

                            // Remove message after 3 seconds
                            setTimeout(() => {
                                if (tempMessage.parentNode) {
                                    tempMessage.parentNode.removeChild(tempMessage);
                                }
                            }, 3000);

                            // Disable the Load Project button after successful load
                            loadProjectBtn.disabled = true;

                            // Reload images for the selected project
                            loadImages();
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Error loading project. Please try again.');
                    });
                }
            });

            let lastActiveListItem = null;

            // Mobile menu toggle
            const mobileMenuToggle = document.getElementById('mobileMenuToggle');
            const sidebarNav = document.getElementById('sidebarNav');
            const overlay = document.getElementById('overlay');
            const userDropdown = document.getElementById('userDropdown');
            const userProfile = document.getElementById('userProfile');

            // --- Mobile Menu Toggle ---
            mobileMenuToggle.addEventListener('click', () => {
                sidebarNav.classList.toggle('show');
                overlay.classList.toggle('show');
            });

            overlay.addEventListener('click', () => {
                sidebarNav.classList.remove('show');
                overlay.classList.remove('show');
            });

            // Close sidebar when clicking a nav link on mobile
            document.querySelectorAll('.nav-link').forEach(link => {
                link.addEventListener('click', () => {
                    if (window.innerWidth <= 768) {
                        sidebarNav.classList.remove('show');
                        overlay.classList.remove('show');
                    }
                });
            });

            // --- User Dropdown Toggle ---
            userProfile.addEventListener('click', (e) => {
                e.stopPropagation();
                userDropdown.classList.toggle('show');
            });

            // Close dropdown when clicking outside
            document.addEventListener('click', () => {
                userDropdown.classList.remove('show');
            });

            /**
             * --- Handles deleting a file from database ---
             * @param {number} fileId - The ID of the file to delete
             * @param {string} imageType - '2d', '3d', or 'final'
             */
            const handleFileDelete = (fileId, imageType) => {
                if (!confirm('Are you sure you want to delete this file?')) {
                    return;
                }

                fetch('designimages.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'action=delete&id=' + encodeURIComponent(fileId)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Reload images
                        loadImages();

                        // Clear preview if deleted item was active
                        if (lastActiveListItem && lastActiveListItem.dataset.fileId == fileId) {
                            const previewContainer = document.getElementById(`preview-container-${imageType}`);
                            previewContainer.innerHTML = `<span>${imageType.toUpperCase()} Preview</span>`;
                            lastActiveListItem = null;
                        }

                        // Show success message
                        const uploadStatus = document.getElementById(`upload-status-${imageType}`);
                        uploadStatus.textContent = 'File deleted successfully.';
                        uploadStatus.className = "upload-status text-success";
                        setTimeout(() => uploadStatus.textContent = "", 3000);
                    } else {
                        alert('Error deleting file. Please try again.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error deleting file. Please try again.');
                });
            };

            /**
             * --- Renders file list with click handlers for preview AND delete ---
             * @param {string} imageType '2d', '3d', or 'final'
             * @param {Array} files Array of file objects
             */
            const renderFileList = (imageType, files) => {
                const fileListContainer = document.getElementById(`file-list-${imageType}`);
                const previewContainer = document.getElementById(`preview-container-${imageType}`);

                fileListContainer.innerHTML = '';

                if (files.length === 0) {
                    fileListContainer.innerHTML = '<li class="empty-state">No files uploaded yet.</li>';
                    // Clear preview if list is empty
                    previewContainer.innerHTML = `<span>${imageType.toUpperCase()} Preview</span>`;
                    return;
                }

                files.forEach((file, index) => {
                    const listItem = document.createElement('li');
                    listItem.className = 'file-list-item';
                    listItem.dataset.fileId = file.id;
                    listItem.dataset.filePath = file.file_path;

                    // Create file name element
                    const nameElement = document.createElement('div');
                    nameElement.className = 'file-name';
                    nameElement.textContent = file.file_name;
                    nameElement.title = file.file_name;

                    // Create actions container
                    const actionsContainer = document.createElement('div');
                    actionsContainer.className = 'file-actions';

                    // Create Download button
                    const downloadButton = document.createElement('a');
                    downloadButton.className = 'download-btn';
                    downloadButton.href = file.file_path || '#';
                    downloadButton.download = file.file_path ? '' : undefined;
                    downloadButton.setAttribute('role', 'button');
                    downloadButton.setAttribute('aria-label', `Download ${file.file_name || 'image'}`);
                    downloadButton.innerHTML = '<b><i class="bi bi-download"></i></b>';

                    if (!file.file_path) {
                        downloadButton.style.display = 'none';
                    }

                    // Handle loading UX on click
                    downloadButton.addEventListener('click', (e) => {
                        if (!file.file_path) {
                            e.preventDefault();
                            return;
                        }

                        // Prevent any custom navigation; allow native download.
                        // (do not call preventDefault so the browser can download)
                        downloadButton.classList.add('');
                        e.stopPropagation();
                    });


                    // Create delete button
                    const deleteButton = document.createElement('button');
                    deleteButton.className = 'delete-btn';
                    deleteButton.innerHTML = '<i class="bi bi-trash"></i>';
                    deleteButton.title = 'Delete file';


                    // --- Click listener for PREVIEW ---
                    listItem.addEventListener('click', (e) => {
                        // Don't trigger if clicking on delete button
                        if (e.target.closest('.delete-btn')) return;

                        // 1. Update preview box
                        previewContainer.innerHTML = '';
                        const img = document.createElement('img');
                        img.src = file.file_path + '?t=' + new Date().getTime();
                        img.alt = file.file_name;
                        previewContainer.appendChild(img);

                        // 2. Update active class in list
                        document.querySelectorAll('.file-list-item').forEach(item => {
                            item.classList.remove('active');
                        });
                        listItem.classList.add('active');
                        lastActiveListItem = listItem;
                    });

                    // --- Click listener for DELETE ---
                    deleteButton.addEventListener('click', (e) => {
                        e.stopPropagation();
                        handleFileDelete(file.id, imageType);
                    });

                    // Build list item
                    actionsContainer.appendChild(downloadButton);
                    actionsContainer.appendChild(deleteButton);
                    listItem.appendChild(nameElement);
                    listItem.appendChild(actionsContainer);
                    fileListContainer.appendChild(listItem);
                });

                // Show/hide pin tool button for final images
                if (imageType === 'final') {
                    const pinToolSection = document.getElementById('pin-tool-section');
                    pinToolSection.style.display = files.length > 0 ? 'block' : 'none';
                }
            };

            /**
             * --- Display latest image in preview container ---
             * For 2D and 3D: Show only the latest uploaded image
             * For Final: Show the single uploaded image
             * @param {string} imageType - '2d', '3d', or 'final'
             * @param {Object|null} latestImage - The latest image object or null
             */
            const displayLatestImage = (imageType, latestImage) => {
                const previewContainer = document.getElementById(`preview-container-${imageType}`);
                
                if (!latestImage) {
                    // Show placeholder when no image exists
                    previewContainer.innerHTML = `<span>${imageType.toUpperCase()} Image Preview</span>`;
                    return;
                }
                
                // Display the latest image
                previewContainer.innerHTML = '';
                const img = document.createElement('img');
                img.src = latestImage.file_path + '?t=' + new Date().getTime();
                img.alt = latestImage.file_name;
                previewContainer.appendChild(img);
            };

            /**
             * --- Load images from server ---
             */
            const loadImages = () => {
                fetch('designimages.php?fetch_images=1')
                .then(response => response.json())
                .then(data => {
                    // data.all_images contains all images for file list
                    // data.latest_images contains only the latest image for preview
                    renderFileList('2d', data.all_images['2d']);
                    renderFileList('3d', data.all_images['3d']);
                    renderFileList('final', data.all_images['final']);
                    
                    // Display latest images in preview containers
                    displayLatestImage('2d', data.latest_images['2d']);
                    displayLatestImage('3d', data.latest_images['3d']);
                    displayLatestImage('final', data.latest_images['final']);
                })
                .catch(error => {
                    console.error('Error loading images:', error);
                });
            };

            // --- Common Submission Handler ---
            uploadForms.forEach(form => {
                form.addEventListener("submit", (e) => {
                    e.preventDefault();

                    const formData = new FormData(form);
                    const imageType = form.querySelector('input[name="imageType"]').value;
                    const uploadStatusId = 'upload-status-' + imageType;
                    const uploadStatus = document.getElementById(uploadStatusId);
                    const submitButton = form.querySelector('button[type="submit"]');

                    uploadStatus.textContent = "Uploading...";
                    uploadStatus.className = "upload-status text-warning";
                    submitButton.disabled = true;

                    fetch('designimages.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        submitButton.disabled = false;
                        form.querySelector('input[type="file"]').value = '';
                        console.log('Upload response:', data);

                        if (data.success) {
                            uploadStatus.textContent = `Successfully uploaded ${data.files.length} image(s) to the ${imageType} section.`;
                            uploadStatus.className = "upload-status text-success";

                            // Also update preview immediately with the first uploaded file - BEFORE loadImages
                            if (data.files && data.files.length > 0) {
                                const previewContainerId = `preview-container-${imageType}`;
                                console.log('Looking for container:', previewContainerId);
                                const previewContainer = document.getElementById(previewContainerId);
                                console.log('Container found:', previewContainer);
                                if (previewContainer) {
                                    previewContainer.innerHTML = '';
                                    const img = document.createElement('img');
                                    img.src = data.files[0].path + '?t=' + new Date().getTime();
                                    img.alt = data.files[0].name;
                                    img.onload = function() {
                                        console.log('Image loaded successfully');
                                    };
                                    img.onerror = function() {
                                        console.error('Image failed to load:', img.src);
                                    };
                                    previewContainer.appendChild(img);
                                    console.log('Preview updated with image:', data.files[0].path);
                                } else {
                                    console.error('Preview container not found!');
                                }
                            }
                            
                            // Reload images
                            loadImages();
                        } else {
                            uploadStatus.textContent = data.message || "Upload failed.";
                            uploadStatus.className = "upload-status text-danger";
                        }

                        setTimeout(() => uploadStatus.textContent = "", 5000);
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        submitButton.disabled = false;
                        form.querySelector('input[type="file"]').value = '';
                        uploadStatus.textContent = "Upload failed. Please try again.";
                        uploadStatus.className = "upload-status text-danger";
                        setTimeout(() => uploadStatus.textContent = "", 5000);
                    });
                });
            });

            // Handle opening pin tool for final images
            document.addEventListener('click', (e) => {
                if (e.target.id === 'openPinToolBtn') {
                    // Get the final image ID from the active list item
                    const activeItem = document.querySelector('#file-list-final .file-list-item.active');
                    if (activeItem) {
                        const imageId = activeItem.dataset.fileId;
                        window.location.href = `imagepin.php?image_id=${imageId}`;
                    } else {
                        // If no image is selected, get the first final image
                        const firstItem = document.querySelector('#file-list-final .file-list-item');
                        if (firstItem) {
                            const imageId = firstItem.dataset.fileId;
                            window.location.href = `imagepin.php?image_id=${imageId}`;
                        }
                    }
                }
            });

            // Initial render of file lists from PHP data
            <?php
            echo "renderFileList('2d', " . json_encode($imagesByType['2d']) . ");\n";
            echo "renderFileList('3d', " . json_encode($imagesByType['3d']) . ");\n";
            echo "renderFileList('final', " . json_encode($imagesByType['final']) . ");\n";
            // Display latest images in preview containers on initial load
            echo "displayLatestImage('2d', " . json_encode($latestImages['2d']) . ");\n";
            echo "displayLatestImage('3d', " . json_encode($latestImages['3d']) . ");\n";
            echo "displayLatestImage('final', " . json_encode($latestImages['final']) . ");\n";
            ?>

            // --- Preview selected image before upload ---
            // Add onchange handlers to file inputs to preview selected images
            const fileInputs = document.querySelectorAll('input[type="file"]');
            fileInputs.forEach(input => {
                input.addEventListener('change', function(e) {
                    if (this.files && this.files[0]) {
                        const file = this.files[0];
                        const imageType = this.closest('form').querySelector('input[name="imageType"]').value;
                        const previewContainer = document.getElementById(`preview-container-${imageType}`);
                        
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            previewContainer.innerHTML = '';
                            const img = document.createElement('img');
                            img.src = e.target.result;
                            img.alt = file.name;
                            previewContainer.appendChild(img);
                        };
                        reader.readAsDataURL(file);
                    }
                });
            });
        });
    </script>
</body>
</html>