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

$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$project_id = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;

if ($project_id <= 0) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>Invalid Project ID</h2>");
}
// Fetch Project Details with Error Handling
$project_result = $conn->query("SELECT id, project_code, project_name FROM project_master WHERE id = $project_id");
$project = $project_result ? $project_result->fetch_assoc() : null;
// Handle AJAX Delete
if (isset($_POST['action']) && $_POST['action'] === 'delete') {
    header('Content-Type: application/json');
    $id = (int)$_POST['id'];

    $file = $conn->query("SELECT file_path FROM site_documents WHERE id = $id AND project_id = $project_id")->fetch_assoc();
    
    if ($file) {
        // Delete physical file
        if (file_exists($file['file_path'])) {
            unlink($file['file_path']);
        }
        // Delete from database
        $conn->query("DELETE FROM site_documents WHERE id = $id");
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false]);
    }
    exit;
}

// Handle Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['site_file'])) {
    header('Content-Type: application/json');
    $file = $_FILES['site_file'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','pdf','doc','docx','xls','xlsx'];

    if (!in_array($ext, $allowed)) {
        echo json_encode(['success' => false, 'message' => 'Invalid file type']);
        exit;
    }

    $upload_dir = "../uploads/site_documents/{$project_id}/";
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

    $new_name = date('Ymd_His') . "_" . bin2hex(random_bytes(8)) . "." . $ext;
    $file_path = $upload_dir . $new_name;

    if (move_uploaded_file($file['tmp_name'], $file_path)) {
        $type = in_array($ext, ['jpg','jpeg','png']) ? 'photo' : 'document';
        
        $stmt = $conn->prepare("INSERT INTO site_documents 
            (project_id, uploaded_by, file_name, file_path, file_type) 
            VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("iisss", $project_id, $user_id, $file['name'], $file_path, $type);
        $stmt->execute();

        echo json_encode(['success' => true, 'message' => 'Uploaded successfully!', 'type' => $type]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Upload failed']);
    }
    exit;
}

// Fetch Files
$photos = $conn->query("SELECT * FROM site_documents WHERE project_id = $project_id AND file_type = 'photo' ORDER BY uploaded_at DESC");
$documents = $conn->query("SELECT * FROM site_documents WHERE project_id = $project_id AND file_type = 'document' ORDER BY uploaded_at DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Site Photos & Documents</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.09);
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.85), rgba(0,0,0,0.95)), url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
        }
        .container { max-width: 1350px; margin: auto; }
        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 28px;
            border: 1px solid rgba(255,255,255,0.15);
            overflow: hidden;
        }
        .header { background: linear-gradient(90deg, rgba(168,85,247,0.3), rgba(192,132,252,0.2)); padding: 35px; text-align: center; }
        .upload-area { padding: 50px 40px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }

        .upload-box {
            border: 3px dashed var(--accent);
            border-radius: 20px;
            padding: 50px 30px;
            cursor: pointer;
            transition: 0.3s;
        }
        .upload-box:hover { background: rgba(192,132,252,0.1); }

        .tabs { display: flex; background: rgba(0,0,0,0.3); }
        .tab { flex: 1; padding: 18px; text-align: center; cursor: pointer; font-weight: 600; }
        .tab.active { background: var(--primary); color: white; }

        .gallery {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
            gap: 20px;
            padding: 40px;
        }
        .photo-card {
            border-radius: 16px;
            overflow: hidden;
            background: rgba(0,0,0,0.4);
            position: relative;
            cursor: pointer;
        }
        .photo-card:hover .delete-btn { opacity: 1; }
        .photo-card img { width: 100%; height: 200px; object-fit: cover; }

        .delete-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(239,68,68,0.9);
            color: white;
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            cursor: pointer;
            opacity: 0;
            transition: 0.3s;
        }

        .document-list { padding: 30px 40px; }
        .doc-item {
            display: flex;
            align-items: center;
            gap: 15px;
            background: rgba(0,0,0,0.3);
            padding: 16px;
            border-radius: 12px;
            margin-bottom: 12px;
        }

        #lightbox {
            display: none;
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.95);
            z-index: 9999;
            align-items: center;
            justify-content: center;
        }
        #lightbox.active { display: flex; }
        #lightbox img { max-width: 90%; max-height: 85vh; border-radius: 12px; }
    </style>
</head>
<body>
<?php include '../config/header.php' ?>
<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="../project/project_dashboard.php?id=<?= $project_id ?>" style="float:left; color:#c4b5fd; text-decoration:none;">← Back</a>
            <h1><i class="fas fa-images"></i> Site Photos & Documents</h1>
            <p><?= htmlspecialchars($project['project_code']) ?> - <?= htmlspecialchars($project['project_name']) ?></p>
        </div>

        <div id="successMsg" style="display:none; padding:15px 40px; background:#22c55e33; color:#86efac; margin:10px 40px; border-radius:12px;"></div>

        <!-- Upload -->
        <div class="upload-area">
            <form id="uploadForm" enctype="multipart/form-data">
                <div class="upload-box" id="uploadBox">
                    <i class="fas fa-cloud-upload-alt" style="font-size:3.8rem; color:var(--accent);"></i>
                    <h3>Click or Drag to Upload</h3>
                    <input type="file" id="fileInput" name="site_file" accept="image/*,.pdf,.doc,.docx,.xls,.xlsx" hidden>
                </div>
            </form>
        </div>

        <!-- Tabs -->
        <div class="tabs">
            <div class="tab active" onclick="showTab(0)">📸 Photos</div>
            <div class="tab" onclick="showTab(1)">📄 Documents</div>
        </div>

        <!-- Photos -->
        <div id="photosTab" class="gallery">
            <?php while ($photo = $photos->fetch_assoc()): ?>
                <div class="photo-card" onclick="openLightbox('<?= htmlspecialchars($photo['file_path']) ?>')">
                    <img src="<?= htmlspecialchars($photo['file_path']) ?>" alt="">
                    <button class="delete-btn" onclick="deleteFile(<?= $photo['id'] ?>, this); event.stopImmediatePropagation();">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            <?php endwhile; ?>
        </div>

        <!-- Documents -->
        <div id="docsTab" class="document-list" style="display:none;">
            <?php while ($doc = $documents->fetch_assoc()): ?>
                <div class="doc-item">
                    <i class="fas fa-file-pdf" style="font-size:2.2rem; color:#ef4444;"></i>
                    <div style="flex:1;">
                        <strong><?= htmlspecialchars($doc['file_name']) ?></strong><br>
                        <small><?= date('d M Y H:i', strtotime($doc['uploaded_at'])) ?></small>
                    </div>
                    <a href="<?= htmlspecialchars($doc['file_path']) ?>" target="_blank" style="padding:10px 18px; background:var(--accent); border-radius:8px; color:white; margin-right:10px;">
                        <i class="fas fa-download"></i>
                    </a>
                    <button class="delete-btn" style="opacity:1; position:relative; top:0; right:0;" onclick="deleteFile(<?= $doc['id'] ?>, this)">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            <?php endwhile; ?>
        </div>
    </div>
</div>

<!-- Lightbox -->
<div id="lightbox">
    <span onclick="closeLightbox()" style="position:absolute; top:30px; right:40px; font-size:3rem; color:white; cursor:pointer;">×</span>
    <img id="lightboxImage" src="" alt="">
</div>

<script>
// Upload
document.getElementById('uploadBox').addEventListener('click', () => document.getElementById('fileInput').click());

document.getElementById('fileInput').addEventListener('change', function() {
    const formData = new FormData();
    formData.append('site_file', this.files[0]);

    fetch(window.location.href, { method: 'POST', body: formData })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            document.getElementById('successMsg').innerHTML = `✅ ${data.message}`;
            document.getElementById('successMsg').style.display = 'block';
            setTimeout(() => location.reload(), 1200);
        } else {
            alert(data.message);
        }
    });
});

// Delete Function
function deleteFile(id, btn) {
    if (!confirm("Are you sure you want to delete this file?")) return;

    fetch(window.location.href, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=delete&id=${id}`
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            btn.closest('.photo-card, .doc-item').remove();
        } else {
            alert("Failed to delete file");
        }
    });
}

// Lightbox
function openLightbox(src) {
    document.getElementById('lightboxImage').src = src;
    document.getElementById('lightbox').style.display = 'flex';
}

function closeLightbox() {
    document.getElementById('lightbox').style.display = 'none';
}

function showTab(n) {
    document.getElementById('photosTab').style.display = n === 0 ? 'grid' : 'none';
    document.getElementById('docsTab').style.display = n === 1 ? 'block' : 'none';
    document.querySelectorAll('.tab').forEach((t,i) => t.classList.toggle('active', i===n));
}

window.onload = () => showTab(0);
</script>

</body>
</html>

<?php $conn->close(); ?>