<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once 'main_db_connect.php'; // Use admin_db database for all operations

$username = isset($_SESSION['username']) ? $_SESSION['username'] : 'Guest';

// Decide where to redirect after operations: users go to users/user_dashboard.php, admins to admin_dashboard.php
$dashboardRedirect = (isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'user') ? 'users/user_dashboard.php' : 'admin_dashboard.php';

// Prefer the pmed DB connection for pmed_documents operations
$db = isset($conn2) ? $conn2 : $conn;

// Log user actions to audit_logs table in admin_db database
if (!function_exists('logAction')) {
    function logAction($adminConn, $userId, $username, $action, $documentId = null, $documentName = null) {
        // $adminConn should be the main admin DB connection ($conn)
        if (!$adminConn) return false;
        // Use a simple escaped query to avoid bind_param type issues (nullable document IDs) and to surface DB errors.
        $uid = (int)$userId;
        $uname = $adminConn->real_escape_string($username ?? '');
        $act = $adminConn->real_escape_string($action ?? '');
        $fname = $adminConn->real_escape_string($documentName ?? '');
        $docIdPart = is_null($documentId) ? 'NULL' : (int)$documentId;

        $sql = "INSERT INTO audit_logs (user_id, username, action, document_id, file_name) VALUES ($uid, '$uname', '$act', $docIdPart, '" . $fname . "')";
        if ($adminConn->query($sql) === TRUE) {
            return true;
        } else {
            error_log('logAction failed: ' . $adminConn->error . ' SQL: ' . $sql);
            return false;
        }
    }
}

// Get image resolution
function getImageResolution($filePath) {
    if (file_exists($filePath)) {
        list($width, $height) = getimagesize($filePath);
        return "{$width}x{$height}";
    }
    return 'N/A';
}

// Get video resolution
function getVideoResolution($filePath) {
    if (function_exists('shell_exec') && shell_exec('which ffmpeg')) {
        $output = shell_exec("ffmpeg -i " . escapeshellarg($filePath) . " 2>&1");
        if (preg_match('/(\d{1,4})x(\d{1,4})/', $output, $matches)) {
            return $matches[0]; 
        }
    }
    return 'N/A'; 
}

// Ensure upload directory exists
function ensureUploadDirectoryExists($dir) {
    if (!is_dir($dir)) {
        if (!mkdir($dir, 0755, true)) {
            return false;
        }
    }
    return $dir;
}

// Clear all documents
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['clear_all'])) {
    $db->query("DELETE FROM pmed_documents");
    
    // Clear uploaded files
    $targetDir = "uploads/";
    $files = glob($targetDir . '*');
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file);
        }
    }
    
    // logAction($conn, $_SESSION['user_id'] ?? 0, $username, "Cleared all documents");
    header("Location: $dashboardRedirect");
    exit();
}

// Add a new document (only when documentId is NOT provided)
// The form includes a hidden documentId field; when it's empty this is an add operation.
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fileName']) && empty($_POST['documentId'])) {
    $fileName = $_POST['fileName'];
    $fileAuthor = $_POST['fileAuthor'];
    $description = $_POST['fileDescription'];
    $fileStatus = $_POST['fileStatus'];
    $refNo = $_POST['refNo'];
    $uploadOk = 1;

    if (!empty($_FILES['fileInput']['name'])) {
        $file = $_FILES['fileInput'];
        
        $targetDir = "uploads/";
        $targetDir = ensureUploadDirectoryExists($targetDir);
        
        $fileType = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $fileNameWithExt = $fileName . '.' . $fileType;
        $target_file = $targetDir . $fileNameWithExt;
        $fileSize = $file['size'];

        $allowed_types = [
            'doc', 'docx', 'xls', 'xlsx', 'pdf', 'ppt', 'pptx', 'jpg', 'jpeg', 'png', 'ico', 'mp4', 
            'mp3', 'mpeg', 'gif', 'svg', 'wav', 'aiff', 'avi', 'mov', 'wmv', 'mkv', 'php', 'html', 'js', 'css', 'py', 
            'csv', 'h', 'H', 'sql', 'zip', 'bmp', 'tiff', 'webp', 'json', 'xml', 'md', 'txt'
        ];

        // Check file type
        if (!in_array($fileType, $allowed_types)) {
            $uploadOk = 0;
        }

        // Check if file already exists and remove it
        if (file_exists($target_file)) {
            unlink($target_file);
        }

        // Check file size (limit to 500MB)
        if ($fileSize > 5000000000) {
            $uploadOk = 0;
        }

        if ($uploadOk == 1) {
            if (move_uploaded_file($file['tmp_name'], $target_file)) {
                $resolution = 'N/A';
                if (in_array($fileType, ['jpg', 'jpeg', 'png'])) {
                    $resolution = getImageResolution($target_file);
                } elseif (in_array($fileType, ['mp4', 'avi', 'mov', 'mkv'])) {
                    $resolution = getVideoResolution($target_file);
                }

                $stmt = $db->prepare("INSERT INTO pmed_documents (pmed_ref_no, pmed_file_name, pmed_author, pmed_file_type, pmed_file_size, pmed_resolution, pmed_upload_date,
                pmed_last_updated, pmed_file_path, pmed_description, pmed_status) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW(), ?, ?, ?)");
                $stmt->bind_param("ssssissss", $refNo, $fileNameWithExt, $fileAuthor, $fileType, $fileSize, $resolution, $target_file, $description, $fileStatus);
                $stmt->execute();
                $stmt->close();

                // Audit log: added a file to Project MOnitoring and Evaluation Division
                $insertedId = $db->insert_id ?? null;
                logAction(isset($conn) ? $conn : null, $_SESSION['user_id'] ?? 0, $username, "added a file to Project MOnitoring and Evaluation Division (PMED", $insertedId, $fileNameWithExt);
                header("Location: $dashboardRedirect");
                exit();
            }
        }
    }
}

// Edit a document (only when documentId is provided)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['documentId'])) {
    $documentId = $_POST['documentId'];
    $fileName = $_POST['fileName'];
    $fileAuthor = $_POST['fileAuthor'];
    $description = $_POST['fileDescription'];
    $status = $_POST['fileStatus'];
    $refNo = $_POST['refNo'];

    // Fetch existing file details
    $result = $db->query("SELECT pmed_file_path FROM pmed_documents WHERE pmed_document_id = '$documentId'");
    $currentFile = $result->fetch_assoc()['pmed_file_path'];

    // Remove existing file if requested or new file uploaded
    if ((isset($_POST['removeExistingFile']) && $_POST['removeExistingFile'] == '1') || !empty($_FILES['fileInput']['name'])) {
        if (file_exists($currentFile)) {
            unlink($currentFile);
        }
    }

    $filePathUpdate = '';
    if (!empty($_FILES['fileInput']['name'])) {
        $file = $_FILES['fileInput'];

        $targetDir = ensureUploadDirectoryExists("uploads/");
        $fileType = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $fileNameWithExt = $fileName . '.' . $fileType;
        $target_file = $targetDir . $fileNameWithExt;
        $fileSize = $file['size'];

        if (move_uploaded_file($file['tmp_name'], $target_file)) {
            $resolution = 'N/A';
            if (in_array($fileType, ['jpg', 'jpeg', 'png'])) {
                $resolution = getImageResolution($target_file);
            } elseif (in_array($fileType, ['mp4', 'avi', 'mov', 'mkv'])) {
                $resolution = getVideoResolution($target_file);
            }

            $filePathUpdate = ", pmed_file_path = ?, pmed_file_type = ?, pmed_file_size = ?, pmed_resolution = ?";
        }
    }

    $query = "UPDATE pmed_documents SET pmed_ref_no = ?, pmed_file_name = ?, pmed_author = ?, pmed_description = ?, pmed_status = ?, pmed_last_updated = NOW() $filePathUpdate WHERE pmed_document_id = ?";
    $stmt = $db->prepare($query);

    if ($filePathUpdate) {
        $stmt->bind_param("sssssssssi", $refNo, $fileName, $fileAuthor, $description, $status, $target_file, $fileType, $fileSize, $resolution, $documentId);
    } else {
        $stmt->bind_param("sssssi", $refNo, $fileName, $fileAuthor, $description, $status, $documentId);
    }

    $stmt->execute();
    $stmt->close();
    // Audit log: edited a file in Project MOnitoring and Evaluation Division
    logAction(isset($conn) ? $conn : null, $_SESSION['user_id'] ?? 0, $username, "edited a file in Project MOnitoring and Evaluation Division (PMED)", $documentId, $fileName);
    header("Location: $dashboardRedirect");
    exit();
}

// Delete a document
if (isset($_GET['delete_id'])) {
    $documentId = $_GET['delete_id'];
    
    // Get file info before deleting
    $stmt = $db->prepare("SELECT pmed_file_name, pmed_file_path FROM pmed_documents WHERE pmed_document_id = ?");
    $stmt->bind_param("i", $documentId);
    $stmt->execute();
    $result = $stmt->get_result();
    $fileInfo = $result->fetch_assoc();
    $stmt->close();
    
    if ($fileInfo && file_exists($fileInfo['pmed_file_path'])) {
        unlink($fileInfo['pmed_file_path']);
    }
    
    // Delete from database
    $stmt = $db->prepare("DELETE FROM pmed_documents WHERE pmed_document_id = ?");
    $stmt->bind_param("i", $documentId);
    $stmt->execute();
    $stmt->close();
    
    if ($fileInfo) {
    // Audit log: deleted a file from Project MOnitoring and Evaluation Division
    logAction(isset($conn) ? $conn : null, $_SESSION['user_id'] ?? 0, $username, "deleted a file from Project MOnitoring and Evaluation Division (PMED)", $documentId, $fileInfo['pmed_file_name']);
    }
    
    header("Location: $dashboardRedirect");
    exit();
}

