<?php
// This script is intended to be included within admin_dashboard.php,
// ensuring $conn (database connection) is available.

$message = '';
$message_class = '';

// --- NEW 0. HANDLE PHOTO DELETION LOGIC (FIX) ---
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id']) && is_numeric($_GET['id'])) {
    
    $photo_id_to_delete = (int)$_GET['id'];
    
    if (isset($conn)) {
        // Step 1: Get the file path from the database
        $sql_select_path = "SELECT file_path FROM general_photos WHERE photo_id = ?";
        if ($stmt_path = $conn->prepare($sql_select_path)) {
            $stmt_path->bind_param("i", $photo_id_to_delete);
            $stmt_path->execute();
            $result_path = $stmt_path->get_result();
            
            if ($result_path->num_rows > 0) {
                $photo = $result_path->fetch_assoc();
                $file_path = $photo['file_path'];
                
                $file_deleted = true;
                if (file_exists($file_path)) {
                    // Step 2: Delete the file from the server
                    if (!unlink($file_path)) {
                        $message = "Error: DB entry removed, but **file system failed to delete the file** '{$file_path}'. Check permissions.";
                        $message_class = 'error';
                        $file_deleted = false;
                    }
                } else {
                    $message = "Warning: File was missing from disk, but DB record will be removed.";
                    $message_class = 'error';
                }
                
                // Step 3: Delete the record from the database
                $sql_delete = "DELETE FROM general_photos WHERE photo_id = ?";
                if ($stmt_delete = $conn->prepare($sql_delete)) {
                    $stmt_delete->bind_param("i", $photo_id_to_delete);
                    
                    if ($stmt_delete->execute()) {
                        if ($file_deleted || !file_exists($file_path)) {
                            $message = "Success: Photo ID: {$photo_id_to_delete} deleted successfully.";
                            $message_class = 'success';
                        }
                    } else {
                        $message = "Error deleting photo from DB: " . $stmt_delete->error;
                        $message_class = 'error';
                    }
                    $stmt_delete->close();
                }
            } else {
                $message = "Error: Photo ID {$photo_id_to_delete} not found.";
                $message_class = 'error';
            }
            $stmt_path->close();
        } else {
             $message = "Error: DB statement preparation failed for path lookup.";
             $message_class = 'error';
        }
    } else {
        $message = "Error: Database connection not available.";
        $message_class = 'error';
    }
}
// --- END OF DELETE LOGIC ---

// --- 1. HANDLE PHOTO UPLOAD LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['upload_photo'])) {
    
    // Check if a file was actually uploaded
    if (isset($_FILES['photo_file']) && $_FILES['photo_file']['error'] === UPLOAD_ERR_OK) {
        
        $file_info = $_FILES['photo_file'];
        $file_name_raw = $file_info['name'];
        $file_extension = strtolower(pathinfo($file_name_raw, PATHINFO_EXTENSION));
        
        // **File Type Validation: Allowed Image Types**
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        if (!in_array($file_extension, $allowed_extensions)) {
            $message = "Error: File type '{$file_extension}' is not allowed. Only image formats (JPG, PNG, GIF, WEBP) are supported.";
            $message_class = 'error';
        } else {
            // Define the server path for photos. Using 'general_photos/' directory.
            // CRITICAL: Ensure this directory exists on your server and has write permissions (uploads/general_photos/)
            $target_dir = 'uploads/general_photos/'; 
            
            // FIX: Append timestamp to prevent overwriting existing files and ensure unique path in DB
            $path_info = pathinfo($file_name_raw);
			$base_name = $path_info['filename'];
			$ext = isset($path_info['extension']) ? $path_info['extension'] : '';
            $timestamp = date('Ymd_His');
            $file_name_unique = $base_name . '_' . $timestamp . ($ext ? '.' . $ext : '');
            $file_path = $target_dir . $file_name_unique; 
            
            // Use the authenticated user's ID for the Foreign Key constraint.
            $uploaded_by_id = $_SESSION['user_id'] ?? 1; 

            // **FIXED TABLE NAME: Using `general_photos`**
            // Columns used: photo_name, file_path, file_extension, uploaded_by
            $sql_insert = "INSERT INTO `general_photos` (photo_name, file_path, file_extension, uploaded_by) VALUES (?, ?, ?, ?)";

            if (isset($conn) && $stmt = $conn->prepare($sql_insert)) {
                
                // Bind parameters: (String, String, String, Integer)
                $stmt->bind_param("sssi", $file_name_unique, $file_path, $file_extension, $uploaded_by_id);
                
                if ($stmt->execute()) {
                    
                    // === CORE FIX: MOVES THE FILE FROM TEMP STORAGE TO ITS FINAL LOCATION ===
                    if (move_uploaded_file($file_info['tmp_name'], $file_path)) {
                        echo "<script>window.alert.call(window,'Success: Photo file {$file_name_unique}) uploaded and saved successfully.'); </script>";
                           
                    } else {
                        // If file move fails, report the file system error
                        $message = "Error: Database updated, but **file system failed to save the photo** to '{$file_path}'. Check that the directory ({$target_dir}) exists and has write permissions (e.g., chmod 777).";
                        $message_class = 'error';
                        
                        // OPTIONAL: Delete the DB entry since the file is missing
                        // $conn->query("DELETE FROM `general_photos` WHERE photo_id = {$conn->insert_id}");
                    }
                    // =======================================================================

                } else {
                    $message = "Error uploading photo (DB): " . $stmt->error;
                    $message_class = 'error';
                }
                $stmt->close();
            } else {
                $message = "Error: Database preparation failed for upload or connection unavailable.";
                $message_class = 'error';
            }
        }
    } else {
        // Handle case where no file was selected or a specific upload error occurred
        if (isset($_POST['upload_photo'])) {
            $error_code = $_FILES['photo_file']['error'] ?? UPLOAD_ERR_NO_FILE;
            
            switch ($error_code) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $message = "Error: The uploaded file exceeds the maximum file size allowed by the server configuration (php.ini limits).";
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $message = "Error: Please select a file to upload.";
                    break;
                case UPLOAD_ERR_PARTIAL:
                    $message = "Error: The file was only partially uploaded.";
                    break;
                default:
                    $message = "Error: An unknown upload error occurred (Code: {$error_code}).";
                    break;
            }
            $message_class = 'error';
        }
    }
}

// --- 2. FETCH ALL PHOTOS FOR DISPLAY ---
$all_photos = [];

if (isset($conn)) {
    // Select the necessary fields including file_path
    // **FIXED TABLE NAME: Using `general_photos`**
    $sql_fetch = "
        SELECT 
            p.photo_id, 
            p.photo_name, 
            p.file_path, 
            p.file_extension, 
            u.username AS uploaded_by_name, 
            p.uploaded_at 
        FROM `general_photos` p
        LEFT JOIN users u ON p.uploaded_by = u.user_id
        ORDER BY p.uploaded_at DESC
    ";
    
    $result = $conn->query($sql_fetch);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $row['uploaded_by'] = $row['uploaded_by_name'] ?? 'N/A';
            $all_photos[] = $row;
        }
    } else {
        // Updated error message to reflect the table name
        $message_fetch = "Error retrieving photos. Check if the 'general_photos' table exists and has the correct columns: " . $conn->error;
    }
}
?>

<style>
    /* Styling for buttons and table */
    .section-header {
        margin-bottom: 25px;
        color: #2c3e50;
    }
    .data-container {
        margin-top: 30px;
    }
    .btn-action {
        padding: 5px 10px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s;
        margin-right: 5px; 
        display: inline-block;
        text-decoration: none; /* Important for <a> tags */
        text-align: center;
    }
    /* Added style for View button */
    .btn-view {
        background-color: #3498db;
        color: white;
    }
    .btn-view:hover {
        background-color: #2980b9;
    }
    .btn-delete {
        background-color: #e74c3c;
        color: white;
    }
    .btn-delete:hover {
        background-color: #c0392b;
    }
    .btn-download { /* New style for the download button */
        background-color: #27ae60;
        color: white;
    }
    .btn-download:hover {
        background-color: #2ecc71;
    }
    
    /* Messages and form group styles remains the same */
    .message {
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 4px;
        font-weight: bold;
    }
    .message.success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .message.error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    .upload-form-group {
        display: flex;
        gap: 10px;
        align-items: flex-end;
    }
    .upload-form-group > div {
        flex-grow: 1;
    }
    .upload-form-group button {
        margin-top: 0;
        padding: 10px 15px;
    }
</style>

<script>
/**
 * Opens the photo in a simple modal/popup.
 * @param {string} filePath - The server path to the photo.
 */
function openPopup(filePath) {
    const popup = document.getElementById('popupModal');
    const content = document.getElementById('popupContent');

    // For images, we simply use an <img> tag inside the popup
    let viewerHTML = `<img src="${filePath}" style="max-width: 100%; max-height: 80vh; display: block; margin: 0 auto;" alt="Photo Preview">`;

    content.innerHTML = viewerHTML;
    // Ensure the modal is displayed as a flex container to center it
    popup.style.display = 'flex';
}

function closePopup() {
    document.getElementById('popupModal').style.display = 'none';
}
</script>

<div class="form-card">
    <h2 class="section-header">Upload New Photo</h2>
    
    <?php if ($message): ?>
        <div class="message <?php echo $message_class; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <form method="POST" action="admin_dashboard.php?page=manage_photos" enctype="multipart/form-data">
        <input type="hidden" name="upload_photo" value="1">
        
        <div class="upload-form-group">
            <div>
                <label for="photo_file">Select Photo (JPG, PNG, GIF, etc.)</label>
                                <input type="file" id="photo_file" name="photo_file" style="padding-top: 5px;" accept=".jpg,.jpeg,.png,.gif,.webp" required>
            </div>
            
            <button type="submit" class="btn-primary">Upload Photo</button>
        </div>
    </form>
</div>

<div class="form-card data-container">
    <h2 class="section-header">Photo List</h2>
    
    <?php if (isset($message_fetch)): ?>
        <div class="message error"><?php echo htmlspecialchars($message_fetch); ?></div>
    <?php elseif (!empty($all_photos)): ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Extension</th> 
                    <th>Uploaded By</th>
                    <th>Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($all_photos as $photo): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($photo['photo_id']); ?></td>
                        <td><?php echo htmlspecialchars($photo['photo_name']); ?></td> 
                        <td><?php echo htmlspecialchars($photo['file_extension']); ?></td>
                        <td><?php echo htmlspecialchars($photo['uploaded_by']); ?></td>
                        <td><?php echo htmlspecialchars(substr($photo['uploaded_at'], 0, 10)); ?></td>
                        <td>
                            <a href="<?php echo htmlspecialchars($photo['file_path']); ?>" 
                               class="btn-action btn-download" 
                               download="<?php echo htmlspecialchars($photo['photo_name']); ?>">
                                Download
                            </a>
                            <button class="btn-action btn-view" onclick="openPopup('<?php echo htmlspecialchars($photo['file_path']); ?>')">View</button>
							
                            <a href="admin_dashboard.php?page=manage_photos&action=delete&id=<?php echo (int)$photo['photo_id']; ?>" 
                               onclick="return confirm('Are you sure you want to delete this photo? This cannot be undone.');" 
                               class="btn-action btn-delete">
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p>No photos found in the database. Upload one above to get started.</p>
    <?php endif; ?>
</div>

<div id="popupModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%;
 background-color:rgba(0,0,0,0.8); z-index:9999; justify-content:center; align-items:center;">
    <div style="background:white; padding:20px; border-radius:8px; max-width:90%; max-height:90%; overflow:auto; position:relative;">
        <button onclick="closePopup()" style="position:absolute; top:10px; right:15px; background:red; color:white; border:none; border-radius:4px; padding:5px 10px; cursor:pointer;">X</button>
        <div id="popupContent" style="text-align:center;"></div>
    </div>
</div>